-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathauth.js
96 lines (86 loc) · 2.97 KB
/
auth.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
const passport = require('passport')
const validator = require('validator')
const User = require('../models/User')
exports.getLogin = (req, res) => {
if (req.user) {
return res.redirect('/todos')
}
res.render('login', {
title: 'Login'
})
}
exports.postLogin = (req, res, next) => {
const validationErrors = []
if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' })
if (validator.isEmpty(req.body.password)) validationErrors.push({ msg: 'Password cannot be blank.' })
if (validationErrors.length) {
req.flash('errors', validationErrors)
return res.redirect('/login')
}
req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false })
passport.authenticate('local', (err, user, info) => {
if (err) { return next(err) }
if (!user) {
req.flash('errors', info)
return res.redirect('/login')
}
req.logIn(user, (err) => {
if (err) { return next(err) }
req.flash('success', { msg: 'Success! You are logged in.' })
res.redirect(req.session.returnTo || '/todos')
})
})(req, res, next)
}
exports.logout = (req, res) => {
req.logout(() => {
console.log('User has logged out.')
})
req.session.destroy((err) => {
if (err) console.log('Error : Failed to destroy the session during logout.', err)
req.user = null
res.redirect('/')
})
}
exports.getSignup = (req, res) => {
if (req.user) {
return res.redirect('/todos')
}
res.render('signup', {
title: 'Create Account'
})
}
exports.postSignup = (req, res, next) => {
const validationErrors = []
if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' })
if (!validator.isLength(req.body.password, { min: 8 })) validationErrors.push({ msg: 'Password must be at least 8 characters long' })
if (req.body.password !== req.body.confirmPassword) validationErrors.push({ msg: 'Passwords do not match' })
if (validationErrors.length) {
req.flash('errors', validationErrors)
return res.redirect('../signup')
}
req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false })
const user = new User({
userName: req.body.userName,
email: req.body.email,
password: req.body.password
})
User.findOne({$or: [
{email: req.body.email},
{userName: req.body.userName}
]}, (err, existingUser) => {
if (err) { return next(err) }
if (existingUser) {
req.flash('errors', { msg: 'Account with that email address or username already exists.' })
return res.redirect('../signup')
}
user.save((err) => {
if (err) { return next(err) }
req.logIn(user, (err) => {
if (err) {
return next(err)
}
res.redirect('/todos')
})
})
})
}