55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
import { Request, Response, NextFunction } from 'express';
|
|
import { ErrorDTO } from '../schemas/miscSchema';
|
|
import * as jwt from '../tools/jwt';
|
|
|
|
/**
|
|
* Checks if user is singed in.
|
|
* Returns 401 when user is unauthorized.
|
|
*
|
|
* To check if user is an admin, chain requireUser and requireAdmin together.
|
|
* So: use requireUser first, and after that requireAdmin to enforce
|
|
* admin privilege requirement.
|
|
*
|
|
* @param {Request} req The request
|
|
* @param {Response} res The resource
|
|
* @param {(Function|NextFunction)} next The next
|
|
* @return {any} Next function on success, unauthorized error otherwise
|
|
*/
|
|
const requireUser = (req: Request, res: Response, next: NextFunction) => {
|
|
const user: jwt.JwtStatus = res.locals.user;
|
|
let error: ErrorDTO | null = null;
|
|
|
|
// No user? Something errored partway. Display an error.
|
|
if (!user)
|
|
error = {
|
|
status: 'error',
|
|
error: 'Unauthorized, please sign in',
|
|
code: 'unauthorized_generic'
|
|
};
|
|
// Check if token is expired first.
|
|
// This is because a token can be valid
|
|
// (if signature matches) while being expired.
|
|
else if (user.expired)
|
|
error = {
|
|
status: 'error',
|
|
error: 'Token expired, please sign in again',
|
|
code: 'expired_token'
|
|
};
|
|
// Previous checks failed?
|
|
// As a last resort, check if the token is valid.
|
|
else if (!user.valid)
|
|
error = {
|
|
status: 'error',
|
|
error: 'Invalid token, please sign in',
|
|
code: 'invalid_token'
|
|
};
|
|
|
|
if (error !== null)
|
|
return res.status(401)
|
|
.send(error);
|
|
|
|
return next();
|
|
};
|
|
|
|
export default requireUser;
|