-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (51 loc) · 1.92 KB
/
index.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
require('dotenv').config();
const PORT = process.env.PORT || 3030;
const express = require("express");
const cors = require('cors');
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
const morgan = require("morgan");
const app = express();
const datahelpers = require('./src/DataHelpers/data-helpers');
const passport = require('passport');
const passportSetup = require('./src/authConfig/passport-github')(datahelpers.users);
const jwt = require('jsonwebtoken');
const path = require('path');
const authRoutes = require('./src/routes/auth-routes')(datahelpers.users);
const usersRoutes = require('./src/routes/users');
const projectRoutes = require("./src/routes/projects.js")(datahelpers);
const eventRoutes = require("./src/routes/events.js")(datahelpers);
const topicRoutes = require("./src/routes/topics.js")(datahelpers);
// TODO: move this function from this file
function middleware(req, res, next) {
let user;
if (req.headers["authorization"]) {
const header = req.headers["authorization"].replace(/Bearer\s+/i, "")
user = jwt.verify(header, process.env.JWT_SECRET);
req.user = user;
}
next();
}
const authorize = (req, res, next) => {
if (!req.user) {
res.status(403).json({ error: "Unauthorized" });
return
}
next();
}
app.use(morgan('dev'));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth', authRoutes);
app.use("/projects", middleware, projectRoutes);
app.use("/events", middleware, eventRoutes);
app.use("/user", middleware, authorize, usersRoutes);
app.use("/topics", middleware, topicRoutes);
const server = app.listen(process.env.PORT || PORT, () => {
console.log("Example app listening on port " + (process.env.PORT || PORT));
});
module.exports = server;