-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
74 lines (66 loc) · 2.57 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
// Imports
const connectDB = require('./config/db');
const cookieSession = require("cookie-session");
const express = require("express");
const cors = require("cors");
const passportSetup = require("./config/passport"); // needed otherwise Unknown authentication strategy "google"
const passport = require("passport");
const authRoute = require("./routes/auth");
const media = require('./routes/api/media');
const userApi = require('./routes/api/user');
const constants = require('./config/constants');
const app = express();
connectDB();
// For Cross Domain requests (Localhost 3000 & 8082 or Vercel client & Render server or example.com & api.example.com)
// Setup CORS before Cookie-Session, Routes and Passport Initialization
app.set('trust proxy', 1)
app.use(
cors({
origin: constants['CLIENT_URL'], // access-control-allow-origin
methods: "GET,POST,PUT,DELETE",
credentials: true, // access-control-allow-credentials
allowedHeaders: "Content-Type,Authorization", // Access-Control-Allow-Headers
}));
if(process.env.STATUS === 'local') {
app.use(
cookieSession({ name: "session", keys: ["lama"], maxAge: 24 * 60 * 60 * 100 })
);
}
else if(process.env.STATUS === 'deploy')
{
app.use(
cookieSession({ name: "session", keys: ["lama"], maxAge: 24 * 60 * 60 * 100,
secure: true })
);
}
// Problem using with passport 0.6.0: session.regenerate is not a function
// Solution from https://github.com/jaredhanson/passport/issues/904
// register regenerate & save after the cookieSession middleware initialization
app.use(function(request, response, next) {
if (request.session && !request.session.regenerate) {
request.session.regenerate = (cb) => {
cb()
}
}
if (request.session && !request.session.save) {
request.session.save = (cb) => {
cb()
}
}
next()
})
// Middleware to parse JSON data comes before passport - for sending POST data
app.use(express.json());
// this function checks if req.session.passport.user exists
// if it does it will call passport.session()
// if it finds a serialized user object in the session,
// it will consider this req is authenticated. And then deserializeUser() will be invoked
// it will retrieve the user and attach it to req.user
app.use(passport.initialize());
app.use(passport.session());
// use Routes
app.use('/api/media', media);
app.use('/api/user', userApi);
app.use('/auth', authRoute);
const port = process.env.PORT || 8082;
app.listen(port, () => console.log(`Server running on port ${port}`));