Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added authorization middleware #31

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
"exclude": [
"src/index.spec.ts",
"src/databases/**/*.*",
"src/modules/**/test/*.spec.ts"
"src/modules/**/test/*.spec.ts",
"src/middlewares/index.ts"
],
"reporter": [
"html",
Expand Down
48 changes: 48 additions & 0 deletions src/middlewares/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import Users, { UsersAttributes } from "../databases/models/users";

const SECRET: string = process.env.JWT_SECRET;

interface ExtendedRequest extends Request {
user: UsersAttributes;
}

export const protect = async function (
req: ExtendedRequest,
res: Response,
next: NextFunction
) {
try {
//? 1. Get token and check if it's there
let token: string;
if (req.headers.authorization?.startsWith("Bearer")) {
token = req.headers.authorization.split(" ").at(-1);
}

if (!token) throw new Error("Login to get access to this resource");

//? 2. Validate the token to see if it is valid or if it has not expired
const decoded: any = await jwt.verify(token, SECRET);

//? 3. Check if the user still exists
const user = await Users.findByPk(decoded.id);
if (!user) {
throw new Error("User belonging to this token does not exist");
}

//?4. Grant access to the protected route
req.user = user;
next();
} catch (err: any) {
console.log(err);
let message: string;
if (err.name === "JsonWebTokenError" || err.name === "TokenExpiredError") {
message = "Invalid token. Log in again to get a new one";
} else {
message = err.message;
}
res.status(401).json({ ok: false, status: "fail", message: message });
}
};
Loading