feat: add sample endpoint to test JWT
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
// https://github.com/TomDoesTech/REST-API-Tutorial-Updated/blob/7b5f040e1acd94d267df585516b33ee7e3b75f70/src/middleware/deserializeUser.ts
|
||||
import { get } from 'lodash';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { verifyJwt } from '../tools/jwt';
|
||||
import * as jwt from '../tools/jwt';
|
||||
|
||||
const inferUser = async (
|
||||
req: Request,
|
||||
@@ -17,12 +17,9 @@ const inferUser = async (
|
||||
|
||||
if (!accessToken) return next();
|
||||
|
||||
const { decoded } = verifyJwt(accessToken, 'accessTokenPublicKey');
|
||||
|
||||
// console.log('decoded user:', decoded);
|
||||
|
||||
if (decoded) {
|
||||
res.locals.user = decoded;
|
||||
const token = jwt.verifyJwt(accessToken, 'accessTokenPrivateKey');
|
||||
if (token) {
|
||||
res.locals.user = token;
|
||||
return next();
|
||||
}
|
||||
|
||||
|
||||
41
src/middleware/requireUser.ts
Normal file
41
src/middleware/requireUser.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { ErrorDTO } from "../schemas/miscSchema";
|
||||
import * as jwt from "../tools/jwt";
|
||||
|
||||
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;
|
||||
Reference in New Issue
Block a user