-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
172 lines (137 loc) · 4.69 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/* eslint-disable no-underscore-dangle */
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
// const GoogleStrategy = require('passport-google-oauth20').Strategy;
const bcrypt = require('bcrypt');
const cors = require('cors');
// ℹ️ Gets access to environment variables/settings
// https://www.npmjs.com/package/dotenv
require('dotenv/config');
// ℹ️ Connects to the database
require('./db');
// Handles http requests (express is node js framework)
// https://www.npmjs.com/package/express
const express = require('express');
const app = express();
// ℹ️ This function is getting exported from the config folder. It runs most middlewares
require('./config')(app);
app.use(
cors({
// this could be multiple domains/origins, but we will allow just our React app
origin: ['http://localhost:3000'],
}),
);
// session configuration
const session = require('express-session');
// session store using mongo
const MongoStore = require('connect-mongo')(session);
const mongoose = require('./db/index');
app.use(
session({
secret: process.env.SESSION_SECRET,
cookie: { maxAge: 1000 * 60 * 60 * 24 },
saveUninitialized: false,
// Forces the session to be saved back to the session store,
// even if the session was never modified during the request.
resave: true,
store: new MongoStore({
mongooseConnection: mongoose.connection,
mongoUrl: 'mongodb://localhost/BugOut',
}),
}),
);
// end of session configuration
// passport configuration
const User = require('./models/User.model');
// we serialize only the `_id` field of the user to keep the information stored minimum
passport.serializeUser((user, done) => {
done(null, user._id);
});
// when we need the information for the user, the deserializeUser function is called with
// the id that we previously serialized to fetch the user from the database
passport.deserializeUser((id, done) => {
User.findById(id)
.then((dbUser) => {
done(null, dbUser);
})
.catch((err) => {
done(err);
});
});
passport.use(
// new GoogleStrategy(
// {
// clientID: process.env.GOOGLE_CLIENTID,
// clientSecret: process.env.GOOGLE_CLIENTSECRET,
// callbackURL: '/auth/google/callback',
// },
// (accessToken, refreshToken, profile, done) => {
// // to see the structure of the data in received response:
// console.log('Google account details:', profile);
// User.findOne({ googleID: profile.id })
// .then((user) => {
// if (user) {
// done(null, user);
// return;
// }
// User.create({ googleID: profile.id })
// .then((newUser) => {
// done(null, newUser);
// })
// .catch((err) => done(err)); // closes User.create()
// })
// .catch((err) => done(err)); // closes User.findOne()
// },
// ),
new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
},
(email, password, done) => {
// login
User.findOne({ email })
.then((userFromDB) => {
if (userFromDB === null) {
// there is no user with this email
done(null, false, { message: 'This email does not exist in the database' });
} else if (!bcrypt.compareSync(password, userFromDB.password)) {
// the password is not matching
done(null, false, { message: 'Wrong password' });
} else {
// the userFromDB should now be logged in
done(null, userFromDB);
}
})
.catch((err) => {
console.log(err);
});
},
),
);
app.use(passport.initialize());
app.use(passport.session());
// end of passport
// 👇 Start handling routes here
// Contrary to the views version, all routes are controled from the routes/index.js
const index = require('./routes');
app.use('/api', index);
const auth = require('./routes/auth-routes');
app.use('/api/auth', auth);
// Allows access to the API from different domains/origins BEFORE session
app.use(
cors({
// this could be multiple domains/origins, but we will allow just our React app
origin: ['http://localhost:3000'],
}),
);
// 👇 Start handling routes here
// Contrary to the views version, all routes are controled from the routes/index.js
// This could be a conflict with line 104, so I commented it out. We can reinstate
// const allRoutes = require('./routes');
// app.use('/api', allRoutes);
const admin = require('./routes/admin');
app.use('/api', admin);
// ❗ To handle errors. Routes that don't exist or errors that you handle in specific routes
require('./error-handling')(app);
module.exports = app;