Untitled

mail@pastecode.io avatar
unknown
typescript
a year ago
761 B
1
Indexable
Never
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 };