-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
90 lines (72 loc) · 2.19 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const initializePassport = require("./config/passport.config");
const express = require("express");
const passport = require("passport");
const session = require("express-session");
const path = require("path");
const helmet = require("helmet");
const flash = require("express-flash");
const methodOverride = require("method-override");
const logger = require("morgan");
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(flash());
//initialise user session
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 3 * 60 * 60 * 1000,
httpOnly: true,
},
})
);
app.use(passport.session());
app.use(passport.initialize());
app.use(methodOverride("_method"));
//auth the user in the DB
initializePassport(passport);
const checkAuthenticated = (requiredRole) => (req, res, next) => {
if (!req.isAuthenticated()) {
return res.redirect("/login/recruter");
}
const userType = req.user.userType;
if (userType !== requiredRole) {
return redirectToRoleHomePage(req, res);
}
return next();
};
const checkNotAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return redirectToRoleHomePage(req, res);
}
return next();
};
const redirectToRoleHomePage = (req, res) => {
const userType = req.user.userType;
console.log(userType);
switch (userType) {
case "recruteur":
return res.redirect("/recruter/dashboard");
case "users":
return res.redirect("/users/dashboard");
case "admin":
return res.redirect("/admin/dashboard");
default:
return res.redirect("/login");
}
};
const staticFilesPath = path.join(__dirname, "views");
app.use(helmet());
app.use(express.json());
app.use(express.static(path.join(__dirname, "views")));
app.use("views", express.static(path.join(__dirname, "views", "public")));
app.use(express.static(staticFilesPath, { type: "application/javascript" }));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(logger("tiny"));
module.exports = { app, checkAuthenticated, checkNotAuthenticated };