Last active
November 11, 2023 03:36
-
-
Save 1mehdifaraji/d32d4da28871fb301697fc6ce131fa05 to your computer and use it in GitHub Desktop.
Jsonwebtoken jwt token generation and verification with express js framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { RequestHandler } from "express"; | |
import jwt, { Secret } from "jsonwebtoken"; | |
import { errors } from "@util/locale/errors"; | |
export const generateToken = (userId: string) => | |
jwt.sign(userId, process.env.SECRET as Secret); | |
export const verifyToken = (async (req, res, next) => { | |
const bearerHeader = req.headers["authorization"] as string; | |
if (!bearerHeader) { | |
const err: Error = new Error(errors.authentication.tokenNotProvided); | |
err.statusCode = 500; | |
next(err); | |
} else { | |
const bearer = bearerHeader.split(" "); | |
const bearerToken = bearer[1]; | |
try { | |
jwt.verify(bearerToken, process.env.SECRET as Secret); | |
next(); | |
} catch (e) { | |
const err: Error = new Error(errors.authentication.tokenNotVerified); | |
err.statusCode = 500; | |
next(err); | |
} | |
} | |
}) as RequestHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment