Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
59 lines (51 loc) · 1.71 KB
/
Copy pathapp.js
File metadata and controls
59 lines (51 loc) · 1.71 KB
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
const express = require('express');
const morgan = require('morgan');
const cookieSession = require('cookie-session');
const path = require('path');
const userRoutes = require('./controllers/users');
const app = express();
app.locals.projDir = __dirname;
app.use(
cookieSession({
name: 'session',
maxAge: 1000 * 60 * 60 * 24 * 7, // miliseconds from now to expire, 1wk
httpOnly: true, // unreadable via client JS
sameSite: 'lax', // only sent from same website
signed: true, // include signature to check tampering
// secure: true, // must be over https
keys: ['s3cr3t'],
})
);
app.init = (config, logger, db) => {
userRoutes.init(config, logger, db);
app.use(
morgan('tiny', {
stream: {
write: (message) => logger.info(message),
},
})
);
const checkAuth = (req, res, next) => {
if (!(req.session && req.session.ref)) {
if (req.headers['x-requested-with']) {
res.status(302).send({ url: '/' }); // if request is an ajax request send json back
} else {
res.redirect('/'); // do normal 302 redirect
}
} else next(); // they have an untampored with token, could further validatate here
};
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/', (req, res) => {
logger.info(`running in ${config.app.env} environment`);
res.sendFile(`${__dirname}/dist/index.html`);
});
app.get('/home.html', checkAuth, (req, res) => {
res.sendFile(`${__dirname}/dist/home.html`);
});
app.post('/login', userRoutes.login);
app.post('/register', userRoutes.register);
app.get('/logout', userRoutes.logout);
app.use(express.static(path.join(__dirname, '/dist/')));
};
module.exports = app;