60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
require('dotenv').config();
|
|
import jwt from 'jsonwebtoken';
|
|
import {RequestHandler} from 'express';
|
|
|
|
import * as t from './types';
|
|
|
|
/**
|
|
* @param {json} user - the data to store in the token
|
|
* @return {jwt} - an Access Token
|
|
* This function generates an access token
|
|
*/
|
|
export function generateAccessToken(user: t.User) {
|
|
return jwt.sign(user,
|
|
process.env.ACCESS_TOKEN_SECRET!);
|
|
};
|
|
|
|
export const checkNoAuth: RequestHandler = (req, res, next) => {
|
|
if (req.cookies.accessToken == undefined) {
|
|
return next();
|
|
}
|
|
return res.redirect('/admin');
|
|
};
|
|
|
|
export const authorize: RequestHandler = async (req, res, next) => {
|
|
const token = req.cookies.accessToken;
|
|
if (token == undefined) {
|
|
req.flash('info', 'You must be signed in to access that resource');
|
|
return res.status(401).redirect('/admin/signin');
|
|
}
|
|
return jwt.verify(token, process.env.ACCESS_TOKEN_SECRET!,
|
|
(err: any, _payload: any) => {
|
|
if (err) {
|
|
res.cookie('accessToken', '', {expires: new Date()});
|
|
req.flash('error', `Error in token verification,
|
|
you've been automatically signed out`);
|
|
return res.status(401).redirect('/admin/signin');
|
|
}
|
|
return next();
|
|
});
|
|
};
|
|
|
|
export const authorizeEmailVerification: RequestHandler = (req, res, next) => {
|
|
const token = req.cookies.accessToken;
|
|
if (token == undefined) {
|
|
req.flash('error', `Please sign in then click the email
|
|
verification link again`);
|
|
return res.status(401).redirect('/admin/signin');
|
|
}
|
|
return jwt.verify(token, process.env.ACCESS_TOKEN_SECRET!,
|
|
(err: any, _user: any) => {
|
|
if (err) {
|
|
res.cookie('accessToken', '', {expires: new Date()});
|
|
req.flash('error', `Error in token verification,
|
|
you've been automatically signed out`);
|
|
return res.status(401).redirect('/admin/signin');
|
|
}
|
|
return next();
|
|
});
|
|
};
|