Readonly
extensionReadonly
schema type Return = (
// Return a status code and a function that will be called with the body of the response
[statusCode: number, bodyFunction: (body: any) => any] |
// Return a function that will be called with the body of the response
(body: any) => any
)
api.auth(client => async (req, res, next) => {
const unauthorized = () => [401, () => ({error: 'Unauthorized'})];
const isOp = api.createOpChecker(req);
const token = req.headers['authorization'];
const {path} = api.describeRequest(req)
// Do not use a users email as your auth token, just an example
const user: Schema['users'] = await client.query('select * from users where email = $1', [token]).then(({rows}) => rows[0]);
if (!user) return unauthorized();
if (isOp('users/:id', 'GET')) {
if (user.id.toString() !== path.split('/').pop())
return unauthorized();
}
});
See
createApi