add user session

This commit is contained in:
João Geonizeli
2022-07-08 20:50:48 -03:00
parent 688d5e89b7
commit c3fe6e6f1c
18 changed files with 330 additions and 15 deletions

View File

@@ -0,0 +1,8 @@
import { signInPath } from '../../controller/users.controller';
import { UNPROTECTED_ROUTES } from '../session.middleware'
describe('Unprotected Routes', () => {
it('check content', () => {
expect(UNPROTECTED_ROUTES.sort()).toEqual([signInPath].sort());
})
})

View File

@@ -0,0 +1,28 @@
import { Handler, Request, Response } from 'express';
import { verify } from 'jsonwebtoken';
import { signInPath } from '../controller/users.controller';
import { AuthService } from '../service/auth.service';
export const UNPROTECTED_ROUTES = [signInPath];
export const sessionMiddleware: Handler = (req: Request, res: Response, next) => {
const token = req.headers['x-access-token'];
if (UNPROTECTED_ROUTES.includes(req.url)) {
next();
} else if (typeof token === 'string') {
AuthService.isSessionValid(token).then(valid => {
verify(token, process.env.SECRET, function (err, decoded) {
if (err || !valid) return res.status(500).json({ auth: false, message: 'Failed to authenticate token.' });
if (!(typeof decoded === 'string')) {
req.userId = +decoded.sub;
}
next();
});
})
} else {
return res.status(401).json({ auth: false, message: 'No token provided.' })
}
}