Skip to content

Instantly share code, notes, and snippets.

@saman-ghm
Last active October 25, 2019 14:51
Show Gist options
  • Save saman-ghm/274ca8231cd01b9f594662c1260a833a to your computer and use it in GitHub Desktop.
Save saman-ghm/274ca8231cd01b9f594662c1260a833a to your computer and use it in GitHub Desktop.
import { Request, Response, NextFunction } from "express";
import * as jwt from "jsonwebtoken";
import config from "../config";
export const checkAuthToken = function(req: Request, res: Response, next: NextFunction) {
const token = <string>req.headers.authorization;
let jwtPayload;
try {
// check if access token is valid
jwtPayload = <any>jwt.verify(token, config.jwtSecret);
res.locals.jwtPayload = jwtPayload;
// extract username from payload and place it in response locals
res.locals.username = jwtPayload["username"];
} catch (error) {
res.status(401).send();
return;
}
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment