Skip to content

Commit af0c15e

Browse files
author
shawon-majid
committed
fixed custom request type issue, implemented authorization in stsById api
1 parent b5382f8 commit af0c15e

File tree

10 files changed

+48
-147
lines changed

10 files changed

+48
-147
lines changed

server/.DS_Store

0 Bytes
Binary file not shown.

server/build/index.js

Lines changed: 0 additions & 2 deletions
This file was deleted.

server/package-lock.json

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

server/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"description": "",
55
"main": "index.js",
66
"scripts": {
7+
"install": "cd ./src && npx prisma migrate dev --name init && createdb ecosync 2> /dev/null || echo 'database already exists'",
78
"build": "tsc",
89
"start": "node build/index.js",
910
"dev": "ts-node src/index.ts",

server/src/controllers/sts.ts

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { PrismaClient, STS, Vehicle } from "@prisma/client";
22
import { Request, Response } from "express";
33
import errorWrapper from "../middlewares/errorWrapper";
44
import CustomError from "../services/CustomError";
5+
import { RoleName } from "../types/rolesTypes";
56

67
const prisma = new PrismaClient();
78

@@ -33,6 +34,9 @@ const getAllSTS = errorWrapper(
3334
const getSTSById = errorWrapper(
3435
async (req: Request, res: Response) => {
3536
const { stsId } = req.params;
37+
38+
console.log(req.user?.id);
39+
3640
const sts = await prisma.sTS.findUnique({
3741
where: {
3842
id: stsId,
@@ -46,9 +50,19 @@ const getSTSById = errorWrapper(
4650
throw new CustomError("STS not found", 404);
4751
}
4852

53+
console.log(sts.manager);
54+
55+
// authorization check
56+
if (
57+
req.user?.role != RoleName.SYSTEM_ADMIN &&
58+
!sts.manager.map((man) => man.id).includes(req.user?.id)
59+
) {
60+
throw new CustomError("Unauthorized", 401);
61+
}
62+
4963
const percentage = await calculatePercentage(sts);
5064

51-
res.status(200).json({ sts, graphData: percentage });
65+
res.status(200).json({ sts, graphData: percentage });
5266
},
5367
{ statusCode: 404, message: "STS not found" }
5468
);
@@ -62,11 +76,13 @@ async function calculatePercentage(sts: STS) {
6276
const graphData = {
6377
empty: mot - ase,
6478
full: ase,
65-
emptyPercentage: parseFloat((((mot - ase) / mot) * 100).toString()).toFixed(2),
79+
emptyPercentage: parseFloat((((mot - ase) / mot) * 100).toString()).toFixed(
80+
2
81+
),
6682
fullPercentage: parseFloat(((ase / mot) * 100).toString()).toFixed(2),
6783
};
68-
69-
return graphData; // Replace with the actual calculation
84+
85+
return graphData; // Replace with the actual calculation
7086
}
7187

7288
const updateSTS = errorWrapper(

server/src/middlewares/auth.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Request, Response, NextFunction } from "express";
22
import errorWrapper from "./errorWrapper";
33
import CustomError from "../services/CustomError";
44
import { getToken, verifyToken } from "../services/Token";
5+
import { JwtPayload } from "jsonwebtoken";
56

67
const authChecker = errorWrapper(
78
async (req: Request, res: Response, next: NextFunction) => {
@@ -10,7 +11,8 @@ const authChecker = errorWrapper(
1011
throw new CustomError("Unauthorized", 401);
1112
}
1213
const decoded = verifyToken(token);
13-
(req as any).user = decoded;
14+
req.user = decoded as JwtPayload;
15+
console.log(req.user);
1416
next();
1517
}
1618
);

server/src/middlewares/authorizer.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import { getPermittedRoleNames } from "../permissions/permissions";
66
const authRole = (roles: string[]) => {
77
return errorWrapper(
88
async (req: Request, res: Response, next: NextFunction) => {
9-
const userRole = ((req as any).user as any).role;
9+
const userRole = req.user?.role;
10+
if (!userRole) throw new CustomError("Unauthorized", 401);
1011
if (!roles.includes(userRole)) {
1112
throw new CustomError("Unauthorized", 401);
1213
}
@@ -18,13 +19,10 @@ const authRole = (roles: string[]) => {
1819
const authorizer = (permission: string) => {
1920
return errorWrapper(
2021
async (req: Request, res: Response, next: NextFunction) => {
21-
const userRole = ((req as any).user as any)?.role;
22+
const userRole = req.user?.role;
2223

2324
const permittedRoles = await getPermittedRoleNames(permission);
2425

25-
console.log(userRole);
26-
console.log(permittedRoles);
27-
2826
if (userRole && permittedRoles.includes(userRole)) {
2927
next();
3028
} else throw new CustomError("Unauthorized", 401);

server/src/test.ts

Lines changed: 13 additions & 124 deletions
Original file line numberDiff line numberDiff line change
@@ -1,124 +1,13 @@
1-
import bcrypt from "bcrypt";
2-
import express, { urlencoded, Request, Response } from "express";
3-
import dotenv from "dotenv";
4-
dotenv.config();
5-
import checkDatabaseConnection from "./db/connection";
6-
7-
import { PrismaClient } from "@prisma/client";
8-
import errorWrapper from "./middlewares/errorWrapper";
9-
import CustomError from "./services/CustomError";
10-
const prisma = new PrismaClient();
11-
const PORT = process.env.PORT || 3000;
12-
const app = express();
13-
14-
app.use(express.json());
15-
app.use(urlencoded({ extended: true }));
16-
17-
app.get("/", (req, res) => {
18-
res.send("EcoSync Server is Up...");
19-
});
20-
21-
app.post("/addUser", async (req, res) => {
22-
try {
23-
const { name, email, password } = req.body;
24-
const user = await prisma.user.create({
25-
data: {
26-
username: name,
27-
email,
28-
hashedPassword: password,
29-
},
30-
});
31-
32-
res.json(user);
33-
} catch (error) {
34-
console.log(error);
35-
}
36-
});
37-
38-
app.get("/users", async (req, res) => {
39-
try {
40-
console.log("Fetching users...");
41-
// get all user and include the role also
42-
const users = await prisma.user.findMany({
43-
include: {
44-
role: true,
45-
},
46-
});
47-
48-
res.json(users);
49-
} catch (error) {
50-
console.log(error);
51-
}
52-
});
53-
54-
app.put(
55-
"/updateUser/:id",
56-
errorWrapper(async (req: Request, res: Response) => {
57-
const { id } = req.params;
58-
const { name, email, password } = req.body;
59-
// check if the user exist
60-
const userExists = await prisma.user.findUnique({
61-
where: {
62-
id: id,
63-
},
64-
});
65-
66-
if (!userExists) {
67-
throw new CustomError("User not found", 404);
68-
}
69-
70-
const user = await prisma.user.update({
71-
where: {
72-
id: id,
73-
},
74-
data: {
75-
username: name,
76-
email,
77-
hashedPassword: password,
78-
},
79-
});
80-
81-
res.json(user);
82-
})
83-
);
84-
85-
// get all roles
86-
app.get("/roles", async (req, res) => {
87-
try {
88-
console.log("Fetching roles...");
89-
const roles = await prisma.role.findMany({});
90-
res.json(roles);
91-
} catch (error) {
92-
console.log(error);
93-
}
94-
});
95-
96-
app.post(
97-
"/permission",
98-
errorWrapper(async (req: Request, res: Response) => {
99-
const { name, description } = req.body;
100-
101-
const permission = await prisma.permission.create({
102-
data: {
103-
name,
104-
description,
105-
},
106-
});
107-
108-
res.json(permission);
109-
})
110-
);
111-
112-
app.get(
113-
"/permissions",
114-
errorWrapper(async (req: Request, res: Response) => {
115-
console.log("Fetching permissions...");
116-
const permissions = await prisma.permission.findMany({});
117-
res.json(permissions);
118-
})
119-
);
120-
121-
app.listen(PORT, async () => {
122-
await checkDatabaseConnection();
123-
console.log(`Server is running on PORT ${PORT}`);
124-
});
1+
interface myObj {
2+
name: string;
3+
sayHello: () => void;
4+
}
5+
6+
const obj: myObj = {
7+
name: "John",
8+
sayHello() {
9+
console.log(`Hello ${this.name}`);
10+
},
11+
};
12+
13+
obj.sayHello();

server/src/types/express/index.d.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,9 @@ import { JwtPayload } from "jsonwebtoken";
22
import { User } from "../custom";
33

44
// to make the file a module and avoid the TypeScript error
5-
export {};
65

7-
declare global {
8-
namespace Express {
9-
export interface Request {
10-
user?: User;
11-
}
6+
declare module "express-serve-static-core" {
7+
interface Request {
8+
user?: JwtPayload;
129
}
1310
}

server/tsconfig.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
{
22
"include": [
33
"src/**/*",
4-
"src/**/*.d.ts"
54
],
65
"compilerOptions": {
76
/* Visit https://aka.ms/tsconfig to read more about this file */
@@ -24,5 +23,6 @@
2423
"strict": true, /* Enable all strict type-checking options. */
2524
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
2625
"skipLibCheck": true /* Skip type checking all .d.ts files. */
27-
}
26+
},
27+
"files": ["src/types/express/index.d.ts"]
2828
}

0 commit comments

Comments
 (0)