Last active
September 14, 2020 05:40
-
-
Save kingsley-einstein/d8e3c94d5183a248dc2db26c829068ac to your computer and use it in GitHub Desktop.
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 jwt from "jsonwebtoken"; | |
import { User, Session } from "../db"; | |
export class Auth { | |
static async checkToken(req: any, res: any, next: any) { | |
try { | |
const { authorization } = req.headers; | |
// Throw error if authorization header is not present in the request | |
if (!authorization) | |
throw new ErrorResponse(401, "Authorization header not present in request"); | |
// Throw error if authorization header doesn't begin with 'Bearer' string | |
if (!authorization.startsWith("Bearer")) | |
throw new ErrorResponse(400, "Authorization header must begin with 'Bearer'"); | |
// Obtain token | |
const token = authorization.substring(7, authorization.length); | |
// Throw error if token is not present | |
if (!token || token.trim().length === 0) | |
throw new ErrorResponse(401, "Token not present in authorization header"); | |
// Decode payload | |
const payload = jwt.decode(token); | |
// Check if user has signed out of session | |
if (await Session.isInvalid(payload.sessionId)) | |
throw new ErrorResponse(401, "Invalid session. Log in again to sign a session token"); | |
// Find user using ID | |
const user = await User.findById(payload.id); | |
// Throw error if user is not found | |
if (!user) | |
throw new ErrorResponse(404, "Could not get authentication information from token"); | |
// Modify the request to hold the authentication object | |
req.user = user; | |
// Modify the request to hold the session id | |
req.sessionId = payload.sessionId; | |
next(); | |
} catch (error) { | |
res.status(error.c || 500).json({ | |
message: error.message | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment