Untitled
unknown
typescript
3 years ago
761 B
6
Indexable
import { Request, Response, NextFunction } from 'express';
import { AUTHENTICATION, TOKEN_COOKIE_NAME, PayloadRequest } from '../utils/config';
import jwt from 'jsonwebtoken';
const getUser = (req: Request, res: Response, next: NextFunction) => {
try {
if (req.cookies) {
const token = req.cookies[TOKEN_COOKIE_NAME];
if (token) {
if (!AUTHENTICATION.secret) {
throw new Error('No secret key');
}
const decoded = jwt.verify(token, AUTHENTICATION.secret);
(req as PayloadRequest).userPayload = decoded;
return res.send(decoded);
}
}
throw new Error('Cannot authenticate');
} catch (error) {
res.statusCode = 401;
next(new Error('Unauthenticated'));
}
};
export default { getUser };
Editor is loading...