initial commit - far from runnable
This commit is contained in:
commit
db057ce342
8614 changed files with 1032171 additions and 0 deletions
25
src/middleware/authenticationMiddleware.ts
Normal file
25
src/middleware/authenticationMiddleware.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { NextFunction, Request, Response } from "express";
|
||||
import * as jwt from "jsonwebtoken";
|
||||
import * as dotenv from "dotenv";
|
||||
dotenv.config();
|
||||
|
||||
export const authentication = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
const header = req.headers.authorization;
|
||||
if (!header) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
const token = header.split(" ")[1];
|
||||
if (!token) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
const decode = jwt.verify(token, process.env.JWT_SECRET);
|
||||
if (!decode) {
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
req[" currentUser"] = decode;
|
||||
next();
|
||||
};
|
||||
17
src/middleware/authorizationMiddleware.ts
Normal file
17
src/middleware/authorizationMiddleware.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { NextFunction, Request, Response } from "express";
|
||||
import { AppDataSource } from "../data-source";
|
||||
import { UserEntity } from "../entities/UserEntity";
|
||||
|
||||
export const authorization = (roles: string[]) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const userRepo = AppDataSource.getRepository(UserEntity);
|
||||
const user = await userRepo.findOne({
|
||||
where: { id: req[" currentUser"].id },
|
||||
});
|
||||
console.log(user);
|
||||
if (!roles.includes(user.role)) {
|
||||
return res.status(403).json({ message: "Forbidden" });
|
||||
}
|
||||
next();
|
||||
};
|
||||
};
|
||||
11
src/middleware/errorHandler.ts
Normal file
11
src/middleware/errorHandler.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { NextFunction, Request, Response } from "express";
|
||||
|
||||
export const errorHandler = (
|
||||
error: Error,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
console.error(`Error: ${error.message}`);
|
||||
return res.status(500).json({ message: "Internal server error" });
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue