-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (51 loc) · 1.8 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
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const expressJWT = require('express-jwt');
const app = express();
const config = require('./config/config');
const router = require('./config/routes');
mongoose.connect(config.db);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(`${__dirname}/public`));
app.use(cors());
app.use('/api', expressJWT({ secret: config.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.' });
}
const User = require('./models/user');
const jwt = require('jsonwebtoken');
function assignUser(req, res, next){
const token = getToken(req, res);
if (!token) return next();
const payload = jwt.verify(token, config.secret);
User.findById(payload.id, (err, user) => {
if (err || !user) res.status(500).json({ message: 'Invalid JWT provided.'});
req.user = user;
return 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(assignUser);
app.use('/api', router);
app.get('/*', (req, res) => res.sendFile(__dirname + '/index.html'));
app.listen(config.port, () => console.log(`Express started on port: ${config.port}`));
module.exports = app;