-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
294 lines (249 loc) · 7.45 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const sassMiddleware = require('node-sass-middleware');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const User = require('./models/user');
const moment = require('moment');
const flash = require('connect-flash');
const GoogleStrategy = require("passport-google-oauth")
.OAuth2Strategy;
const util = require('util');
//Authentication & Authorization modules
const LocalStrategy = require('passport-local')
.Strategy;
const bcrypt = require('bcrypt');
const passport = require('passport');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
// Mongoose connection configuration
mongoose.connect('mongodb://localhost/swarovski');
//routes path's
const index = require('./routes/index');
const auth = require('./routes/auth');
const users = require('./routes/users');
const collections = require('./routes/collections');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//layouts
app.set('layout', 'layouts/index');
app.use(expressLayouts);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(sassMiddleware({
src: path.join(__dirname, 'public'),
dest: path.join(__dirname, 'public'),
indentedSyntax: false, // true = .sass and false = .scss
outputStyle: 'compressed',
sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));
//SESSION
/* app.use(session({
secret: 'our-passport-local-strategy-app',
resave: true,
saveUninitialized: true
})); */
app.use(session({
secret: 'swarovskiproject1',
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 2000000
},
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 6 * 60 * 60 // (1/4) day
})
}));
//flash
app.use(flash());
app.locals.moment = moment;
/*SESSION */
passport.serializeUser((user, cb) => {
//console.log('serialize user:', user);
cb(null, user._id);
});
passport.deserializeUser((id, cb) => {
//console.log('desserialize id:', id);
User.findOne({
'_id': id
}, (err, user) => {
if (err) {
return cb(err);
}
cb(null, user);
});
});
// Signing Up
passport.use(new GoogleStrategy({
clientID: '60359403657-2kb369umburkbc39rl0stodcc4vvuj6q.apps.googleusercontent.com',
clientSecret: 'wPvEsVlevR0t-mB5aV-AZ5Gn',
callbackURL: '/auth/google/callback',
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
User.findOne({
googleID: profile.id
}, (err, user) => {
if (err) {
return done(err);
}
if (user) {
console.log(`USER FOUND!!!!!!`);
// if a user is found, log him in
return done(null, user);
}
console.log(`FIRST USER CREATE!!!!!!`);
// if the user isnt in our database, create a new user
const newUser = new User({
googleID: profile.id,
name: profile.name.givenName, // console.log(`name: ${profile.name.givenName}`);
surname: profile.name.familyName,
email: profile.emails[0].value,
avatar: profile.photos[0].value
});
console.log(`user-->${newUser}`);
newUser.save((err) => {
if (err)
throw err;
return done(null, newUser);
});
});
}));
/**
* LocalStrategy expects to find credentials in parameters named 'username' and 'password'.
*
*/
passport.use('local-signup', new LocalStrategy({
passReqToCallback: true,
usernameField: 'email' // change the defaults username parameter
},
(req, email, password, next) => {
// To avoid race conditions
// Make code async, User.findOne won't fire until we have all our data back
process.nextTick(() => {
console.log(`LocalStrategy. FIRST`);
User.findOne({
'email': email
}, (err, user) => {
if (err) {
let key = 'errorMsg',
msg = 'Something wrong, try again!';
return next(err, req.flash(key, msg));
}
if (user) {
let key = 'errorMsg',
msg = `${email} is already taken. Plase, try another one`;
return next(null, false, req.flash(key, msg));
} else {
// Destructure the body
/* const {
email,
password,
name,
surname,
address,
city,
country,
birthday
} = req.body; */
console.log(`NO ERRORS`);
const hashPass = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(8), null);
console.log(`HASPASS.`);
const newUser = new User({
email: req.body.email,
password: hashPass,
name: req.body.name,
surname: req.body.surname,
address: req.body.address,
city: req.body.city,
country: req.body.country,
birthday: req.body.birthday
});
if(req.file){
newUser.avatar = `/uploads/${req.file.filename}`;
}
console.log(`NEW USER ${newUser}`);
console.log(`NEW USER/${util.inspect(newUser,false,null)}`);
newUser.save((err) => {
if (err) {
next(err);
}
let key = 'message',
msg = `Thanks! ${newUser.email} has successfully signed up!`;
return next(null, newUser, req.flash(key, msg));
});
}
});
});
}));
// Login
passport.use('local-login', new LocalStrategy({
passReqToCallback: true,
usernameField: 'email'
}, (req, email, password, next) => {
console.log(`LOCAL-LOGIN`);
User.findOne({
email
}, (err, user) => {
if (err) {
let key = 'errorMsg',
msg = 'Error, try again';
return next(err, req.flash(key, msg));
}
if (!user) {
let key = 'errorMsg',
msg = `${email} doesn't exist, sign up or try again`;
return next(null, false, req.flash(key, msg));
}
if (!bcrypt.compareSync(password, user.password)) {
let key = 'errorMsg',
msg = `Incorrect password, try again`;
return next(null, false, req.flash(key, msg));
}
return next(null, user);
});
}));
app.use(passport.initialize());
app.use(passport.session());
app.use((req, res, next) => {
if (typeof (req.user) !== 'undefined') {
res.locals.userSignedIn = true;
} else {
res.locals.userSignedIn = false;
}
next();
});
//use routes
app.use('/', index);
app.use('/', auth);
app.use('/users', users);
app.use('/collections', collections);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;