-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
73 lines (62 loc) · 2.24 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
70
71
72
73
require('dotenv').config()
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const cors = require('cors');
const User = require('./models/user');
// Connect to MongoDB
const mongoDB = process.env.MONGOURL || 'mongodb://localhost:27017/testdb';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('connected', () => console.log('Connected to MongoDB'));
db.on('error', () => console.error('MongoDB connection error'));
// Configure JWT authentication
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
var options = {}
options.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
options.secretOrKey = process.env.JWT_SECRET;
passport.use(new JwtStrategy(options, (jwtPayload, done) => {
User.findById(jwtPayload.id, (err, user) => {
if (err) {
return done(err, false);
}
return done(null, user || false);
}).select('+isAdmin +email');
}));
const app = express();
// initialize middlewares
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const postsRouter = require('./routes/posts');
const commentsRouter = require('./routes/comments');
const votesRouter = require('./routes/votes');
// register routes
app.use('/api', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/posts', postsRouter);
app.use('/api/comments', commentsRouter);
app.use('/api/votes', votesRouter);
// not found
app.use(function (req, res, next) {
res.status(404).json({ message: "Not Found" })
});
// error handler
app.use(function (err, req, res, next) {
const isDev = req.app.get('env') === 'development';
const message = isDev ? err.message : "Internal server error";
const error = isDev ? err : {};
res.status(err.status || 500).json({ success: false, message });
});
module.exports = app;