1
0
Fork 0
mirror of https://github.com/plankanban/planka.git synced 2025-07-19 13:19:44 +02:00
planka/server/api/hooks/current-user/index.js

52 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-08-31 04:07:25 +05:00
/**
* current-user hook
*
* @description :: A hook definition. Extends Sails by adding shadow routes, implicit actions,
* and/or initialization logic.
2019-08-31 04:07:25 +05:00
* @docs :: https://sailsjs.com/docs/concepts/extending-sails/hooks
*/
module.exports = function defineCurrentUserHook(sails) {
const TOKEN_PATTERN = /^Bearer /;
2020-04-03 00:35:25 +05:00
const getUser = async (accessToken) => {
2019-08-31 04:07:25 +05:00
let id;
try {
id = sails.helpers.utils.verifyToken(accessToken);
} catch (error) {
return null;
2019-08-31 04:07:25 +05:00
}
return sails.helpers.users.getOne(id);
2019-08-31 04:07:25 +05:00
};
return {
/**
* Runs when this Sails app loads/lifts.
*/
async initialize() {
2019-08-31 04:07:25 +05:00
sails.log.info('Initializing custom hook (`current-user`)');
},
routes: {
before: {
'/*': {
async fn(req, res, next) {
2019-08-31 04:07:25 +05:00
const { authorization: authorizationHeader } = req.headers;
if (authorizationHeader && TOKEN_PATTERN.test(authorizationHeader)) {
const accessToken = authorizationHeader.replace(TOKEN_PATTERN, '');
2019-08-31 04:07:25 +05:00
req.currentUser = await getUser(accessToken);
}
return next();
},
},
},
},
2019-08-31 04:07:25 +05:00
};
};