-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathapp.js
72 lines (53 loc) · 1.62 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
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const path = require('path');
// Bring in the database object
const config = require('./config/database');
// Mongodb Config
mongoose.set('useCreateIndex', true);
// Connect with the database
mongoose.connect(config.database, {
useNewUrlParser: true
})
.then(() => {
console.log('Databse connected successfully ' + config.database);
}).catch(err => {
console.log(err);
});
// Initialize the app
const app = express();
// Defining the PORT
const PORT = process.env.PORT || 5000;
// Defining the Middlewares
app.use(cors());
// Set the static folder
app.use(express.static(path.join(__dirname, 'public')));
// BodyParser Middleware
app.use(bodyParser.json());
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) => {
return res.json({
message: "This is node.js role based authentication system"
});
});
// Create a custom middleware function
const checkUserType = function (req, res, next) {
const userType = req.originalUrl.split('/')[2];
// Bring in the passport authentication starategy
require('./config/passport')(userType, passport);
next();
};
app.use(checkUserType);
// Bring in the user routes
const users = require('./routes/users');
app.use('/api/users', users);
const admin = require('./routes/admin');
app.use('/api/admin', admin);
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});