mirror of
https://github.com/bubblecup-12/VogelSocialMedia.git
synced 2025-07-09 20:18:48 +00:00
added authentication and swagger
This commit is contained in:
parent
c311e3adda
commit
64c0d79438
8 changed files with 447 additions and 56 deletions
|
@ -1,15 +1,19 @@
|
|||
import express, { NextFunction, Request, Response } from "express";
|
||||
import jwt from "jsonwebtoken";
|
||||
import jwt, { TokenExpiredError } from "jsonwebtoken";
|
||||
import dotenv from "dotenv";
|
||||
import { string } from "zod";
|
||||
dotenv.config();
|
||||
// imports the JWT secret
|
||||
const JWT_SECRET: string = process.env.TOKEN_SECRET!;
|
||||
|
||||
if (!JWT_SECRET) console.log("no JWT secret");
|
||||
// create an interface for the JWT payload
|
||||
// this interface is used to define the structure of the JWT payload
|
||||
interface JwtPayload {
|
||||
username: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
// extend the Express Request interface to include the user property
|
||||
// this is used to store the JWT payload in the request object
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
|
@ -17,27 +21,26 @@ declare global {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware function to authenticate the JWT token
|
||||
export function authenticateToken() {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
const authHeader = req.headers["authorization"];
|
||||
const token = authHeader && authHeader.split(" ")[1];
|
||||
const authHeader = req.headers["authorization"]; // get the authorization header from the request
|
||||
const token = authHeader && authHeader.split(" ")[1]; // split the header to get the token
|
||||
|
||||
if (token == null) res.sendStatus(401);
|
||||
if (token == null)
|
||||
res.sendStatus(401); // if there is no token, return 401 Unauthorized
|
||||
else {
|
||||
jwt.verify(
|
||||
token,
|
||||
process.env.TOKEN_SECRET as string,
|
||||
(err: any, user: any) => {
|
||||
console.log(err);
|
||||
|
||||
if (err) res.sendStatus(403);
|
||||
|
||||
req.user = user;
|
||||
|
||||
next();
|
||||
},
|
||||
);
|
||||
jwt.verify(token, JWT_SECRET, (err: any, user: any) => {
|
||||
// verify the token with the secret
|
||||
console.log(err);
|
||||
if (err) {
|
||||
if (err instanceof TokenExpiredError)
|
||||
// check if the error is expired and return 401
|
||||
res.status(401).json({ message: "Token expired" });
|
||||
else res.status(403).json({ message: "Invalid token" });
|
||||
}
|
||||
next();
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue