-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
315 lines (272 loc) · 9.06 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//jshint esversion:12
require('dotenv').config(); // fot creating and using env var
const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const encrypt = require('mongoose-encryption'); // for encryption
const md5 = require('md5');
const bcrypt = require('bcrypt');
const saltRounds =7; // Number of rounds for hashing via salting
const session = require('express-session'); // Adding sessions to the page
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
var FacebookStrategy = require('passport-facebook');
const findOrCreate = require('mongoose-findorcreate')
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine","ejs"); // templating engine
app.use(express.static("public"));
app.use(session({ //Initilising session
secret : process.env.SECRET ,
resave : false ,
saveUninitialized: true,
resave : false
}))
app.use(passport.initialize()); // initilising PASSPORT
app.use(passport.session()); // using Initilised session
mongoose.connect("mongodb://localhost:27017/userAuthDB",{useNewUrlParser: true});
// ============== Secrets Schema =======================
const Secret_text_schema = mongoose.Schema({
text : String
})
const secret_text = mongoose.model('SText',Secret_text_schema);
//=============== L1 - Basic Auth ======================
// const userSchema = mongoose.Schema({
// email : String,
// password : {
// type : String ,
// max : (10 , 'Maximum Password length is 10'),
// min : (2 , 'Minimum Password length is 2')
// },
// secrets : [Secret_text_schema]
// })
// ============= L2 - AES Encryption ===================
// const userSchema = new mongoose.Schema({
// email : String ,
// password : {
// type : String ,
// max : (10 , 'Maximum Password length is 10'),
// min : (2 , 'Minimum Password length is 2')
// },
// secrets : [Secret_text_schema]
// });
// userSchema.plugin(encrypt ,{secret : process.env.SECRET , encryptedFields :['password']}); // Add plugin before creating collection
// ============= L3 - Hashing ==========================
// const userSchema = mongoose.Schema({
// email : String,
// password : {
// type : String ,
// max : (10 , 'Maximum Password length is 10'),
// min : (2 , 'Minimum Password length is 2')
// },
// secrets : [Secret_text_schema]
// })
// ============ L4 - Salting with hashing ==============
// const userSchema = mongoose.Schema({
// email : String,
// password : {
// type : String ,
// max : (10 , 'Maximum Password length is 10'),
// min : (2 , 'Minimum Password length is 2')
// },
// secrets : [Secret_text_schema]
// })
// =========== L5 - Adding Cookies and Sessions =======
const userSchema = new mongoose.Schema({
email : String ,
password : {
type : String ,
max : (10 , 'Maximum Password length is 10'),
min : (2 , 'Minimum Password length is 2')
},
googleId:String,
facebookId:String,
secrets : [Secret_text_schema]
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const userAuth = mongoose.model("userAuth",userSchema);
passport.use(userAuth.createStrategy());
// passport.serializeUser(userAuth.serializeUser()); // to add user identification throughout session
// passport.deserializeUser(userAuth.deserializeUser()); // to remove user identification
passport.serializeUser((user,done)=>{
done(null,user.id);
});
passport.deserializeUser((id,done)=>{
userAuth.findById(id,(err,user)=>{
done(err,user);
});
});
//========= Google Auth==========
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:315/auth/google/secrets",
userProfileURL:"https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
userAuth.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
//==== google route =====
app.get('/auth/google',
passport.authenticate('google',{scope:['profile']})
)
app.get('/auth/google/secrets',passport.authenticate('google',{failureRedirect:'/login'}),
(req,res)=>{
res.redirect('/secrets');
})
// ===== facebook Auth ====
passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: "http://localhost:315/auth/facebook/secrets"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
userAuth.findOrCreate({ facebookId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
app.get('/auth/facebook',
passport.authenticate('facebook'));
app.get('/auth/facebook/secrets',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/secrets');
});
// =========== Routes =====================
app.get('/',(req,res)=>{
res.render('home');
})
app.get('/login',(req,res)=>{
res.render('login');
})
app.get('/register',(req,res)=>{
res.render('register');
})
app.get('/submit',(req,res)=>{
if(req.isAuthenticated()){res.render('submit');}
else{res.redirect('/login')};
});
app.get('/secrets',(req,res)=>{
if(req.isAuthenticated()){
console.log(req.user.secrets);
res.render('secrets',{secret : req.user.secrets});}
else{res.redirect('/login')};
})
app.get('/logout',function(req,res){
req.logout((err)=>{
if(!err){
res.redirect('/');
}});
});
app.post('/submit',(req,res)=>{
const SecretText = req.body.secret;
userAuth.findOne({_id:req.user._id},(err,result)=>{
if(!err){
const newSecret = new secret_text({
text:SecretText
})
result.secrets.push(newSecret);
result.save();
res.redirect('/secrets');
}
})
})
app.post('/register',(req,res)=>{
const Email = req.body.username;
const Password = req.body.password;
// ====== MD5 Hashing ======
// const Password = md5(req.body.password);
// ======= Bcrypt Salting ==========
// bcrypt.hash(Password,saltRounds,(error,hash)=>{
// if(!error){const newUser = new userAuth({
// email : Email ,
// password : hash
// })
// newUser.save((err)=>{
// if(!err){res.render('secrets'),{secrets :[]}};
// });}
// })
// ===== ========== ========== =========== ======
// const newUser = new userAuth({
// email : Email ,
// password : Password
// })
// newUser.save((err)=>{
// if(!err){res.render('secrets'),{secrets :[]}};
// });
userAuth.register({username : req.body.username} , Password,function(err , user){
if(err){
console.log(err);
res.redirect('/register');
}else{
passport.authenticate("local")(req,res,()=>{
res.redirect('/secrets');
})
}
})
})
app.post('/login',(req,res)=>{
// const Email = req.body.username;
// const Password = req.body.password;
// const Password = md5(req.body.password); // md5 encryption
// userAuth.findOne({email : Email} , (err,result)=>{
// if(!err){
// // if(result.password === Password)
// // {res.render('secrets');}else{
// // console.log('Password is Incorrect');
// // console.log(Password);
// // console.log(result.password)
// // }
// // ===== Bycrypt Salting =====
// // if(result)
// // {bcrypt.compare(Password,result.password,function(err,BcryptRes){
// // if(BcryptRes===true){
// // res.render('secrets');
// // }
// // })}else{
// // console.log('Password is Incorrect');
// // }
// }
// else{
// console.log(err);
// }
// })
// ==== Using Auth Session === //
const user = new userAuth({
username : req.body.username ,
password : req.body.password
});
req.login(user,(err)=>{
if(err){
console.log(err);
res.redirect('/login');
}
else{
passport.authenticate('local')(req,res,()=>{
res.redirect('/secrets');
})
}
})
})
app.post('/submit',(req,res)=>{
const SText = req.body.secret;
const newSecret = new secret_text({
text : SText
});
newSecret.save();
res.render('secrets',{secret : req.user.secrets});
})
app.listen(process.env.PORT||315,(error)=>{
if(error){console.log(error);}else{
console.log("Running at Port : 315");
}
})