-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
69 lines (56 loc) · 1.92 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
/*
* Name-ly main server
*/
/** Require environment variable(s) */
require('dotenv').config();
/** Require middlewares */
const express = require('express');
const methodOverride = require('method-override');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
/** Instantiate server */
const app = express();
const PORT = process.env.PORT || 3000;
/** Use middlewares */
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static('public'));
app.use(cookieParser());
/** Custom auth-checking middleware */
const checkAuth = (req, res, next) => {
// console.log('Checking authentication');
if (typeof req.cookies.nameToken === 'undefined' || req.cookies === null) {
req.user = null;
} else {
const token = req.cookies.nameToken;
const decodedToken = jwt.decode(token, { complete: true }) || {};
req.user = decodedToken.payload;
}
next();
};
app.use(checkAuth);
/** Send Email */
/** Database connection */
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/name-ly', { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Database connected successfully.');
});
/** Require controllers */
require('./controllers/auth.js')(app);
require('./controllers/about.js')(app);
require('./controllers/quizzes.js')(app);
require('./controllers/nameLists.js')(app);
require('./controllers/users.js')(app);
/** Port listener */
app.listen(PORT, () => {
console.log('Name Generator listening on port', PORT);
});
module.exports = app;