Created
March 10, 2020 12:10
-
-
Save dmytro-kerest/93821a555369bf5aa3652168d99551b8 to your computer and use it in GitHub Desktop.
jwt middleware
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 { Request, Response, NextFunction } from "express"; | |
| import * as jwt from "jsonwebtoken"; | |
| import config from "../config/config"; | |
| export const checkJwt = (req: Request, res: Response, next: NextFunction) => { | |
| const token = <string>req.headers["authorization"].match(/^Bearer (.*)$/)[1]; | |
| let jwtPayload; | |
| try { | |
| jwtPayload = <any>jwt.verify(token, config.jwtSecret); | |
| res.locals.jwtPayload = jwtPayload; | |
| } catch (error) { | |
| res.status(401).send(); | |
| return; | |
| } | |
| const { userId, username } = jwtPayload; | |
| const newToken = jwt.sign({ userId, username }, config.jwtSecret, { | |
| expiresIn: config.jwtExpirationTimeframe | |
| }); | |
| res.setHeader("token", newToken); | |
| next(); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment