-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
102 lines (87 loc) · 2.34 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
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var sessions = require('client-sessions');
var app = express();
app.locals.pretty = true;
app.set('view engine', 'jade');
var Schema = mongoose.Schema;
var objectId = Schema.ObjectId;
// connect to Mongo database
mongoose.connect('mongodb://localhost/auth');
var User = mongoose.model('user', new Schema( {
id: objectId,
login: String,
email: {type: String, unique: true},
password: String
}));
// middleware
app.use(bodyParser.urlencoded({extended: true}));
app.use(sessions({
cookieName: 'session',
secret: 'dkwfrejkgkvkpengo0243090504959469',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000
}));
app.get('/', function(req, res) {
res.render('index.jade');
});
app.get('/register', function(req, res) {
res.render('register.jade');
});
app.post('/register', function(req, res) {
var user = new User({
login: req.body.login,
email: req.body.email,
password: req.body.password
});
user.save(function(errorReason) {
var err;
if(errorReason) {
err = 'Something went wrong. Please try again!';
if(errorReason.code === 11000) {
err = 'This email is already taken. Please use another one.';
}
res.render('register.jade', {error: err});
} else {
res.redirect('/dashboard');
}
});
});
app.get('/login', function(req, res) {
res.render('login.jade');
});
app.post('/login', function(req, res) {
User.findOne({email: req.body.email}, function(err, user) {
if(!user) {
res.render('login.jade', {error: 'Invalid email or password'});
} else {
if(req.body.password === user.password) {
req.session.user = user;
res.redirect('/dashboard');
} else {
res.render('login.jade', {error: 'Invalid email or password'});
}
}
});
});
app.get('/dashboard', function(req, res) {
if(req.session && req.session.user) {
User.findOne({email: req.session.user.email}, function(err, user) {
if(!user) {
req.session.reset();
res.redirect('/login');
} else {
res.locals.user = user;
res.render('dashboard.jade');
}
})
} else {
res.redirect('/login');
}
});
app.get('/logout', function(req, res) {
req.session.reset();
res.redirect('/');
});
app.listen(3000);