Rework JWT decoding for better security
This commit is contained in:
parent
dd52d44cc2
commit
fb98314bf4
13 changed files with 185 additions and 113 deletions
33
backend/src/app/controllers/user/auth/decode.ts
Normal file
33
backend/src/app/controllers/user/auth/decode.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { Request, Response } from "express";
|
||||
import * as jwt from "jsonwebtoken";
|
||||
import moment from "moment";
|
||||
|
||||
export type JwtDecodedUser = {
|
||||
_id: string;
|
||||
email: string;
|
||||
first: string;
|
||||
last: string;
|
||||
admin: boolean;
|
||||
expiresAt: string;
|
||||
};
|
||||
|
||||
export default async (req: Request, res: Response) => {
|
||||
try {
|
||||
if (!req.query.token) {
|
||||
return res.status(422).json({ error: "No user token was provided" });
|
||||
}
|
||||
|
||||
const data = jwt.verify(
|
||||
req.query.token as string,
|
||||
process.env.JWT_SECRET as string
|
||||
) as JwtDecodedUser;
|
||||
|
||||
if (moment(moment()).isAfter(data.expiresAt)) {
|
||||
return res.status(410).json({ error: "This token has expired" });
|
||||
}
|
||||
|
||||
return res.status(200).json(data);
|
||||
} catch (ex) {
|
||||
return res.status(500).json({ error: ex });
|
||||
}
|
||||
};
|
||||
|
|
@ -5,6 +5,7 @@ import validate from "./auth/validate";
|
|||
import create from "./crud/create";
|
||||
import del from "./crud/delete";
|
||||
import get from "./crud/get";
|
||||
import decode from "./auth/decode";
|
||||
|
||||
const routes: RouteCollection[] = [
|
||||
{
|
||||
|
|
@ -12,6 +13,11 @@ const routes: RouteCollection[] = [
|
|||
path: "/api/v1/user",
|
||||
handler: get,
|
||||
},
|
||||
{
|
||||
httpMethod: "GET",
|
||||
path: "/api/v1/user/decode",
|
||||
handler: decode,
|
||||
},
|
||||
{
|
||||
httpMethod: "PUT",
|
||||
path: "/api/v1/user",
|
||||
|
|
|
|||
Loading…
Reference in a new issue