Skip to content

Commit 387fc78

Browse files
Merge pull request #402 from tcet-opensource/feat-200-Added-middleware-for-authentication-and-authorization
200-Added-authorization.js-and-authentication.js-for-access-management
2 parents bf61cac + 37e3cc2 commit 387fc78

23 files changed

+480
-92
lines changed

.github/workflows/test.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ on:
1010
env:
1111
TOKEN_SECRET: ${{ secrets.TOKEN_SECRET }}
1212
DB_URL: ${{ secrets.DB_URL }}
13+
ENVIRONMENT: ${{ secrets.ENVIRONMENT }}
1314

1415
permissions:
1516
contents: read

_apidoc.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1749,4 +1749,4 @@
17491749
* @apiSuccess {String[]} faculty.designation Faculty member's designation.
17501750
* @apiSuccess {String} faculty.natureOfAssociation Nature of association with the institution.
17511751
* @apiSuccess {String} faculty.additionalResponsibilities Additional responsibilities of the faculty.
1752-
**/
1752+
*/

middleware/auth.js

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,36 @@ import jwt from "jsonwebtoken";
22
import util from "#util";
33

44
async function authenticateToken(req, res, next) {
5-
const authHeader = req.headers.authorization;
6-
const token = authHeader && authHeader.split(" ")[1];
7-
if (token == null) return res.sendStatus(401);
8-
try {
9-
const payload = jwt.verify(token, process.env.TOKEN_SECRET);
10-
const decryptedIP = util.decrypt(payload.ip);
11-
if (decryptedIP !== req.ip) {
5+
if (process.env.ENVIRONMENT === "local") {
6+
return next();
7+
}
8+
const authHeader = req.headers.authorization || req.headers.Authorization;
9+
// Inside header when we are going to provide the value for key authentication we have
10+
// to start it with 'Bearer acesstoken'
11+
if (authHeader && authHeader.startsWith("Bearer")) {
12+
const token = authHeader.split(" ")[1];
13+
if (token == null) return res.sendStatus(401);
14+
try {
15+
const payload = jwt.verify(token, process.env.TOKEN_SECRET);
16+
const decryptedIP = util.decrypt(payload.ip);
17+
if (decryptedIP !== req.ip) {
18+
res.status(403);
19+
res.send({ err: "Unauthorized" });
20+
}
21+
22+
req.user = payload.data;
23+
next();
24+
return true;
25+
} catch (error) {
1226
res.status(403);
1327
res.send({ err: "Unauthorized" });
28+
return false;
1429
}
15-
16-
req.user = payload.data;
17-
next();
18-
return true;
19-
} catch (error) {
20-
res.status(403);
21-
res.send({ err: "Unauthorized" });
22-
return false;
30+
} else {
31+
res.json({
32+
msg: "Kindly login",
33+
});
2334
}
35+
return null;
2436
}
25-
26-
export default { authenticateToken };
37+
export default authenticateToken;

middleware/authorization.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
function authorization(access = []) {
2+
return (req, res, next) => {
3+
// remove this in production
4+
if (process.env.ENVIRONMENT === "local") {
5+
return next();
6+
}
7+
if (!req.user) return res.json({ msg: "kindly login first" });
8+
if (!access.includes(req.user.type))
9+
return res.json({ msg: "Unauthorized request" });
10+
return next();
11+
};
12+
}
13+
14+
export default authorization;

models/user.js

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,13 @@ const userSchema = {
77
emailId: { type: String, unique: true, required: true },
88
password: { type: String, required: true },
99
uid: { type: String, unique: true, required: true },
10-
userType: { type: String, required: true },
10+
userType: {
11+
type: String,
12+
required: true,
13+
enum: ["ADMIN", "FACULTY", "EMPLOYEE", "STUDENT"],
14+
default: "ADMIN",
15+
// for now we are keeping the default usertype as ADMIN
16+
},
1117
};
1218

1319
const User = connector.model("User", userSchema);
@@ -18,9 +24,7 @@ async function remove(filter) {
1824
}
1925

2026
async function create(userData) {
21-
const {
22-
name, password, emailId, uid, userType,
23-
} = userData;
27+
const { name, password, emailId, uid, userType } = userData;
2428
const hashedPassword = await hashPassword(password);
2529
const user = new User({
2630
name,
@@ -39,10 +43,17 @@ async function read(filter, limit = 1) {
3943
}
4044

4145
async function update(filter, updateObject, options = { multi: true }) {
42-
const updateResult = await User.updateMany(filter, { $set: updateObject }, options);
46+
const updateResult = await User.updateMany(
47+
filter,
48+
{ $set: updateObject },
49+
options,
50+
);
4351
return updateResult.acknowledged;
4452
}
4553

4654
export default {
47-
create, read, update, remove,
55+
create,
56+
read,
57+
update,
58+
remove,
4859
};

routes/accreditation.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,21 @@
11
import express from "express";
2+
import authenticateToken from "#middleware/auth";
3+
import authorization from "#middleware/authorization";
24
import accreditationController from "#controller/accreditation";
35

46
const router = express.Router();
5-
router.get("/list", accreditationController.showAccreditation);
6-
router.post("/add", accreditationController.addAccreditation);
7+
router.get(
8+
"/list",
9+
authenticateToken,
10+
authorization(["ADMIN"]),
11+
accreditationController.showAccreditation,
12+
);
13+
router.post(
14+
"/add",
15+
authenticateToken,
16+
authorization(["ADMIN"]),
17+
accreditationController.addAccreditation,
18+
);
719
router.delete("/delete/:id", accreditationController.deleteAccreditation);
820
router.post("/update/:id", accreditationController.updateAccreditation);
921

routes/activity.js

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,32 @@
11
import express from "express";
2+
import authenticateToken from "#middleware/auth";
3+
import authorization from "#middleware/authorization";
24
import activityController from "#controller/activity";
35

4-
const router=express.Router();
5-
router.post("/add",activityController.addActivity);
6-
router.get("/list",activityController.getActivity);
7-
router.post("/update/:id",activityController.updateActivity);
8-
router.delete("/delete/:id",activityController.deleteActivity);
6+
const router = express.Router();
7+
router.post(
8+
"/add",
9+
authenticateToken,
10+
authorization(["ADMIN", "FACULTY"]),
11+
activityController.addActivity,
12+
);
13+
router.get(
14+
"/list",
15+
authenticateToken,
16+
authorization(["ADMIN", "FACULTY"]),
17+
activityController.getActivity,
18+
);
19+
router.post(
20+
"/update/:id",
21+
authenticateToken,
22+
authorization(["ADMIN", "FACULTY"]),
23+
activityController.updateActivity,
24+
);
25+
router.delete(
26+
"/delete/:id",
27+
authenticateToken,
28+
authorization(["ADMIN", "FACULTY"]),
29+
activityController.deleteActivity,
30+
);
931

10-
export default router;
32+
export default router;

routes/assignment.js

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,32 @@
11
import express from "express";
22
import assingmentController from "#controller/assignment";
3+
import authenticateToken from "#middleware/auth";
4+
import authorization from "#middleware/authorization";
35

46
const router = express.Router();
5-
router.post("/add", assingmentController.addAssignment);
6-
router.get("/list", assingmentController.getAssignment);
7-
router.post("/update/:id", assingmentController.updateAssignment);
8-
router.delete("/delete/:id", assingmentController.deleteAssignment);
7+
router.post(
8+
"/add",
9+
authenticateToken,
10+
authorization(["ADMIN", "FACULTY"]),
11+
assingmentController.addAssignment,
12+
);
13+
router.get(
14+
"/list",
15+
authenticateToken,
16+
authorization(["ADMIN", "FACULTY"]),
17+
assingmentController.getAssignment,
18+
);
19+
router.post(
20+
"/update/:id",
21+
authenticateToken,
22+
authorization(["ADMIN", "FACULTY"]),
23+
assingmentController.updateAssignment,
24+
);
25+
router.delete(
26+
"/delete/:id",
27+
authenticateToken,
28+
authorization(["ADMIN", "FACULTY"]),
29+
assingmentController.deleteAssignment,
30+
);
931

1032
export default router;

routes/coursework.js

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,32 @@
11
import express from "express";
2+
import authenticateToken from "#middleware/auth";
3+
import authorization from "#middleware/authorization";
24
import courseworkController from "#controller/coursework";
35

46
const router = express.Router();
5-
router.post("/add", courseworkController.addCoursework);
6-
router.get("/list", courseworkController.getCoursework);
7-
router.post("/update/:id", courseworkController.updateCoursework);
8-
router.delete("/delete/:id", courseworkController.deleteCoursework);
7+
router.post(
8+
"/add",
9+
authenticateToken,
10+
authorization(["ADMIN", "FACULTY"]),
11+
courseworkController.addCoursework,
12+
);
13+
router.get(
14+
"/list",
15+
authenticateToken,
16+
authorization(["ADMIN", "FACULTY"]),
17+
courseworkController.getCoursework,
18+
);
19+
router.post(
20+
"/update/:id",
21+
authenticateToken,
22+
authorization(["ADMIN", "FACULTY"]),
23+
courseworkController.updateCoursework,
24+
);
25+
router.delete(
26+
"/delete/:id",
27+
authenticateToken,
28+
authorization(["ADMIN", "FACULTY"]),
29+
courseworkController.deleteCoursework,
30+
);
931

1032
export default router;

routes/department.js

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,33 @@
11
import express from "express";
2+
import authenticateToken from "#middleware/auth";
3+
import authorization from "#middleware/authorization";
24
import departmentContoller from "#controller/department";
35

46
const router = express.Router();
57

6-
router.get("/list", departmentContoller.showdepartments);
7-
router.post("/create", departmentContoller.addDepartment);
8-
router.delete("/delete/:id", departmentContoller.removedepartmentbyid);
9-
router.post("/update/:id", departmentContoller.updatedDepartment);
8+
router.get(
9+
"/list",
10+
authenticateToken,
11+
authorization(["ADMIN"]),
12+
departmentContoller.showdepartments,
13+
);
14+
router.post(
15+
"/create",
16+
authenticateToken,
17+
authorization(["ADMIN"]),
18+
departmentContoller.addDepartment,
19+
);
20+
router.delete(
21+
"/delete/:id",
22+
authenticateToken,
23+
authorization(["ADMIN"]),
24+
departmentContoller.removedepartmentbyid,
25+
);
26+
router.post(
27+
"/update/:id",
28+
authenticateToken,
29+
authorization(["ADMIN"]),
30+
departmentContoller.updatedDepartment,
31+
);
1032

1133
export default router;

0 commit comments

Comments
 (0)