handler: (request, reply) => { const { req, res } = request.raw // Try to find the bearer token in the request. const token = permit.check(req) // No token found, so ask for authentication. if (!token) { permit.fail(res) return reply(new Error(`Authentication required!`)) } // Perform your authentication logic however you'd like... db.users.findByToken(token, (err, user) => { if (err) return reply(err) // No user found, so their token was invalid. if (!user) { permit.fail(res) return reply(new Error(`Authentication invalid!`)) } // Authentication succeeded, save the context and proceed... request.user = user reply('Some restricted content.') }) },
module.exports = async (req, res) => { const token = permit.check(req) // Token not in request if (token == null) { permit.fail(res) throw createError(400, 'Token missing') } const entry = await tokens.get(token) // Token not in database if (entry == null) { permit.fail(res) throw createError(400, 'Token invalid') } const valid = ttl(entry.updated, process.env.TTL) // Token too old if (valid === false) { permit.fail(res) throw createError(400, 'Token invalid') } await tokens.update(token) context(req, 'token', token) }
db.users.findByToken(token, (err, user) => { if (err) return reply(err) // No user found, so their token was invalid. if (!user) { permit.fail(res) return reply(new Error(`Authentication invalid!`)) } // Authentication succeeded, save the context and proceed... request.user = user reply('Some restricted content.') })