-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
79 lines (63 loc) · 2.11 KB
/
server.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
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var session = require('cookie-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bcrypt = require('bcryptjs');
var mongod = require('mongod');
var app = express();
var db = mongod(process.env.DB, ['users', 'polish']);
app.set('views', __dirname + '/views');
app.engine('jade', require('jade').renderFile);
passport.serializeUser(function(user, done){
done(null, user);
});
passport.deserializeUser(function(user, done){
done(null, user);
});
passport.use('local', new LocalStrategy(function(email, password, done){
db.users.findOne({_id: email}).done(function(user){
if (!user) return done(null, false, {message: 'Incorrect'});
bcrypt.compare(password, user.passwordHash, function(err, match) {
if (err) return done(err);
if (match) return done(null, {email: email});
else done(null, false, {message: 'Incorrect'});
});
}, done);
}));
app.use(session({keys: ['hhdhdjk5uh298tyhsknfkjwh48rh4j']}));
app.use(bodyParser.urlencoded({extended: false}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function(req, res, next){
if (req.isAuthenticated()) {
res.render('index.jade');
} else {
res.render('login.jade');
}
});
app.post('/signup', function(req, res, next){
bcrypt.hash(req.body.password, 10, function(err, hash){
if (err) return next(err);
db.users.insert({_id: req.body.username, passwordHash: hash}).done(function(){
res.send('Registered');
}, next);
});
});
app.post('/login', passport.authenticate('local', {successRedirect: '/'}));
app.post('/addnew', function(req, res, next){
db.polish.insert({user: req.user, name: req.body.polishname}).done(function(){
res.send('Polish added');
}, next);
});
app.get('/logout', function(req, res, next){
req.logout();
res.redirect('/');
});
app.get('/list', function(req, res, next){
db.polish.find({user: req.user}).done(function(polishes){
res.render('polishlist.jade', {polishes: polishes});
});
});
app.listen(3000);