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

66 lines
1.6 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) => {
let payload;
2019-08-31 04:07:25 +05:00
try {
payload = sails.helpers.utils.verifyToken(accessToken);
} catch (error) {
return null;
2019-08-31 04:07:25 +05:00
}
const user = await sails.helpers.users.getOne(payload.subject);
if (user && user.passwordChangedAt > payload.issuedAt) {
return null;
}
return user;
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: {
'/api/*': {
async fn(req, res, next) {
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();
},
},
'/attachments/*': {
async fn(req, res, next) {
if (req.cookies.accessToken) {
req.currentUser = await getUser(req.cookies.accessToken);
}
2019-08-31 04:07:25 +05:00
return next();
},
},
},
},
2019-08-31 04:07:25 +05:00
};
};