feat: Use new (tested) accessToken utils to authoize requests
This commit is contained in:
committed by
mrugesh mohapatra
parent
2f944b3aed
commit
3e8bac4590
@ -1,9 +1,12 @@
|
||||
import loopback from 'loopback';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { isBefore } from 'date-fns';
|
||||
import { isEmpty } from 'lodash';
|
||||
|
||||
import {
|
||||
getAccessTokenFromRequest,
|
||||
errorTypes,
|
||||
authHeaderNS
|
||||
} from '../utils/getSetAccessToken';
|
||||
import { homeLocation } from '../../../config/env';
|
||||
import { jwtSecret as _jwtSecret } from '../../../config/secrets';
|
||||
|
||||
import { wrapHandledError } from '../utils/create-handled-error';
|
||||
|
||||
@ -19,18 +22,15 @@ export function isWhiteListedPath(path, whiteListREs = _whiteListREs) {
|
||||
return whiteListREs.some(re => re.test(path));
|
||||
}
|
||||
|
||||
export default ({
|
||||
_jwtSecret = process.env.JWT_SECRET,
|
||||
getUserById = _getUserById
|
||||
} = {}) =>
|
||||
export default ({ jwtSecret = _jwtSecret, getUserById = _getUserById } = {}) =>
|
||||
function requestAuthorisation(req, res, next) {
|
||||
const { path } = req;
|
||||
if (apiProxyRE.test(path) && !isWhiteListedPath(path)) {
|
||||
const cookie =
|
||||
(req.signedCookies && req.signedCookies['jwt_access_token']) ||
|
||||
(req.cookie && req.cookie['jwt_access_token']);
|
||||
|
||||
if (!cookie) {
|
||||
const { accessToken, error, jwt } = getAccessTokenFromRequest(
|
||||
req,
|
||||
jwtSecret
|
||||
);
|
||||
if (!accessToken && error === errorTypes.noTokenFound) {
|
||||
throw wrapHandledError(
|
||||
new Error('Access token is required for this request'),
|
||||
{
|
||||
@ -41,22 +41,15 @@ export default ({
|
||||
}
|
||||
);
|
||||
}
|
||||
let token;
|
||||
try {
|
||||
token = jwt.verify(cookie, _jwtSecret);
|
||||
} catch (err) {
|
||||
throw wrapHandledError(new Error(err.message), {
|
||||
if (!accessToken && error === errorTypes.invalidToken) {
|
||||
throw wrapHandledError(new Error('Access token is invalid'), {
|
||||
type: 'info',
|
||||
redirect: `${homeLocation}/signin`,
|
||||
message: 'Your access token is invalid',
|
||||
status: 403
|
||||
});
|
||||
}
|
||||
const {
|
||||
accessToken: { created, ttl, userId }
|
||||
} = token;
|
||||
const valid = isBefore(Date.now(), Date.parse(created) + ttl);
|
||||
if (!valid) {
|
||||
if (!accessToken && error === errorTypes.expiredToken) {
|
||||
throw wrapHandledError(new Error('Access token is no longer vaild'), {
|
||||
type: 'info',
|
||||
redirect: `${homeLocation}/signin`,
|
||||
@ -64,8 +57,9 @@ export default ({
|
||||
status: 403
|
||||
});
|
||||
}
|
||||
|
||||
res.set(authHeaderNS, jwt);
|
||||
if (isEmpty(req.user)) {
|
||||
const { userId } = accessToken;
|
||||
return getUserById(userId)
|
||||
.then(user => {
|
||||
if (user) {
|
||||
|
Reference in New Issue
Block a user