-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapplication.js
74 lines (62 loc) · 2.72 KB
/
application.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
const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const winston = require('winston');
const jwtStrategy = require('./middleware/jwt-strategy');
const configuration = require('./constants/configuration');
const authController = require('./controllers/auth.controller');
const combosController = require('./controllers/combos.controller');
const projectsController = require('./controllers/projects.controller');
const tasksController = require('./controllers/tasks.controller');
const usersController = require('./controllers/users.controller');
// Configure the logger appenders and level
// FIXME: Be careful of the winston v3 changes
winston.level = process.env.LOGLEVEL || 'debug';
// MongoDB connection
mongoose.connect(configuration.database, { useNewUrlParser: true, useUnifiedTopology: true });
// ExpressJS service
const applicationPort = process.env.PORT || 3300;
const application = express();
application.disable('x-powered-by');
application.use((req, res, next) => {
const allowedOrigins = ['https://ng-taskmanager.surge.sh'];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.header('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, Authorization');
// Allow all preflight OPTIONS requests in order to avoid issues since they don't have the Authorization header
if (req.method === 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
// Configure Passport to use our JWT strategy and attach it to the application
application.use(passport.initialize());
passport.use(jwtStrategy);
// Server configuration
// Serve static resources and parse requests body as JSON
application.use(bodyParser.json());
application.use(bodyParser.urlencoded({
extended: true
}));
// Use JWT passport for all the api/* endpoints to securize them all
application.use('/auth', authController.router);
application.all('/api/*', passport.authenticate('jwt', { session: false }));
application.use('/api/combos', combosController.router);
application.use('/api/projects', projectsController.router);
application.use('/api/tasks', tasksController.router);
application.use('/api/users', usersController.router);
// Default fallback for unbound requests
application.get('*', (request, response) => {
response.sendStatus(404);
});
application.listen(applicationPort, () => {
console.log(`TaskManager backend listening on port ${applicationPort}!`)
});
application.on('error', (error) => {
console.log(` ## ERROR # ${error} ## `);
throw error;
});