-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (61 loc) · 1.99 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const expressJWT = require('express-jwt');
const jwt = require('jsonwebtoken');
const User = require('./models/user');
const app = express();
const env = require('./config/env');
const router = require('./config/routes');
const dest = `${__dirname}/public`;
const port = process.env.PORT || 4000;
const errorHandler = require('./lib/errors');
mongoose.Promise = require('bluebird');
app.use(express.static(dest));
mongoose.connect(env.db);
app.use(cors());
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use('/api', expressJWT({ secret: env.secret })
.unless({
path: [
{ url: '/api/register', methods: ['POST'] },
{ url: '/api/login', methods: ['POST'] }
]
}));
app.use(jwtErrorHandler);
function jwtErrorHandler(err, req, res, next){
if (err.name !== 'UnauthorizedError') return next();
return res.status(401).json({ message: 'Unauthorized request.' });
}
app.use(assignUser);
function assignUser(req, res, next) {
const token = getToken(req);
if (!token) return next();
const payload = jwt.verify(token, env.secret);
User
.findById(payload.id)
.exec()
.then(user => {
if (!user) return res.status(500).json({
message: 'Invalid JWT provided.'
});
req.user = user;
return next();
})
.catch(next);
}
function getToken(req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
}
app.use('/api', router);
app.get('/*', (req, res) => res.sendFile(`${dest}/index.html`));
app.use(errorHandler);
app.listen(port, () => console.log(`Express has started on port: ${port}`));
module.exports = app;