-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
376 lines (296 loc) · 9.45 KB
/
index.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
var express = require('express')
, passport = require('passport')
, util = require('util')
, LocalStrategy = require('passport-local').Strategy;
var port = process.env.PORT || 3030;
const DB_COLLECTION={
ADS:'ads'
}
var dburl ;
var crypto = require("crypto");
// dburl = "mz:mz123@ds057934.mongolab.com:57934/letitgo";
dburl = "mongodb://localhost:27017/letitgo";
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var monk = require('monk');
var db = monk(dburl);
//var flash = require('connect-flash');
/*
* You may think you know what the following code does.
* But you don't. Trust me.
* Fiddle with it, and you'll spend many a sleepless
* night cursing the moment you thought you'd be clever
* enough to "optimize" the code below.
* Now close this file and go play with something else.
*/
function findByUsername(username, fn) {
var collection = db.get('loginUsers');
console.log("yeh user name hai latest!!",username);
collection.findOne({email:username},{},function(e,docs){
console.log("now in user" ,docs);
if(docs)
{
return fn(null,docs);
}
else {
return fn(null,null);
}
});
}
function getAllAds(res){
var collect=db.get("ads");
collect.find({},{},function(e,docs){
console.log("Blogs",docs);
if(docs)
{
sendData(res,docs);
}
else
{
return null;
}
});
}
function findAd(res,ind){
var collect=db.get("ads");
console.log("ind ko check kr rha !",ind);
collect.findOne({_id:ind},{},function(e,docs){
console.log("Blogs",docs);
if(docs)
{
sendData(res,docs);
}
else
{
return null;
}
});
}
function findById(id, fn) {
var collection = db.get('loginUsers');
collection.findOne({_id:id},{},function(e,docs){
console.log("now in id",docs);
if(docs)
{
return fn(null,docs);
}
else
{
return fn(null,null);
}
});
}
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// configure Express
app.use(cookieParser());
//app.use(express.methodOverride());
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
//cookie : { secure : false, maxAge : (40 * 60 * 60 * 1000)}, // 4 hours
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req,res,next){
req.db = db;
next();
})
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
findById(id, function (err, user) {
done(err, user);
});
});
// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object. In the real world, this would query a database;
// however, in this example we are using a baked-in set of users.
passport.use(new LocalStrategy(
function (email, password, done) {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
console.log(email, password);
findByUsername(email, function (err, user) {
console.log("yaha aya");
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {message: 'Unknown user ' + email});
}
var OldPassword = user.password.password;
console.log("This is an Old " + OldPassword);
var NewPassword = hash(password, user.password.salt);
console.log("This is a New " + NewPassword);
if (OldPassword != NewPassword) {
console.log("Error");
return done(null, false, {message: 'Invalid password'});
}
return done(null, user);
});
}
));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
//app.use(flash());
app.use(express.static(__dirname + '/public'));
function sendData(res,obj)
{
console.log("finally checking object",obj);
res.send(obj);
}
app.get('/login', function(req, res){
res.send({msg:"login kr"});
});
app.get('/sent', ensureAuthenticated, function(req, res){
var obj=findforSent(res,req.user.email);
console.log("checking object",obj);
});
app.get('/ads', function(req, res){
var obj=getAllAds(res);
console.log("checking object",obj);
});
app.get('/ads/*', ensureAuthenticated, function(req, res){
console.log("quer id",req.params[0]);
var abc=req.params[0];
if(abc)
{
var obj=findAd(res,req.params[0]);
}
else {
res.send({error:true})
}
});
// POST /login
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
//
// curl -v -d "username=bob&password=secret" http://127.0.0.1:3000/login
app.post('/login', function(req,res){
var email=req.body.email;
var password=req.body.password;
var collection = db.get('loginUsers');
console.log("yeh user name hai latest!!",email);
collection.findOne({email:email},{},function(e,docs){
console.log("now in user" ,docs);
if(docs)
{
var OldPassword = docs.password.password;
console.log("This is an Old " + OldPassword);
var NewPassword = hash(password, docs.password.salt);
console.log("This is a New " + NewPassword);
if (OldPassword != NewPassword) {
console.log("Error");
res.send('Invalid password');
}
res.send(true);
}
else {
res.send("Invalid User");
}
});
});
app.get('/loginFailure', function(req, res){
console.log("erre");
res.send({error:true});
});
app.post('/register', function (req, res) {
var collection = req.db.get("loginUsers");
var mail = req.body.email;
collection.findOne({email: mail}, {}, function (e, docs2) {
console.log("checking docs 2", docs2);
if (docs2 != null) {
var obj = 'Used';
res.send(obj);
}
else {
var name = req.body.name;
console.log("pushing in the database!!!");
var saltPass = newSalt(16);
var pass = {password: hash(req.body.password, saltPass), salt: saltPass};
var obje = {name: req.body.name, email: req.body.email, password: pass};
collection.insert(obje, function (err, doc) {
if (err) {
// If it failed, return error
console.log(err);
res.send(false);
}
else {
console.log("pushed");
res.send(true);
}
});
}
});
// Submit to the DB
});
/*
* You may think you know what the following code does.
* But you don't. Trust me.
* Fiddle with it, and you'll spend many a sleepless
* night cursing the moment you thought you'd be clever
* enough to "optimize" the code below.
* Now close this file and go play with something else.
*/
app.post('/ad',ensureAuthenticated, function(req,res){
var collection = req.db.get("blogs");
var title=req.body.ptitle;
var subtitle=req.body.subtitle;
var author=req.body.author;
var post=req.body.post;
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = year + "/" + month + "/" + day;
var temp={'ptitle':title,'subtitle':subtitle,'author':author,'post':post,'date':newdate};
console.log(temp);
collection.insert(temp, function (err, doc) {
if (err) {
// If it failed, return error
res.send({error:true});
}
else {
res.send({msg:"success"});
}
});
})
app.get('/logout', function(req, res){
req.logout();
res.redirect("/#/blog");
});
app.listen(port);
// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next)
{
if (req.isAuthenticated()) {
return next(); }
res.redirect("/#/login");
}
function newSalt(size) {
return crypto.randomBytes(size).toString('hex');
}
function hash(password, salt) {
var sha256 = crypto.createHash('sha256').update(salt + password).digest("hex");
return sha256;
}