-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
113 lines (99 loc) · 3.05 KB
/
router.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
const express = require("express");
const passport = require('./passport.config');
const { User, Secret } = require("./models")
const router = express.Router();
router.get('/', (req, res) => {
res.render('home');
});
router.route('/register')
.get((req, res) => res.render('register'))
.post((req, res) =>
User.register(
{ username: req.body.username, active: true },
req.body.password, (err, user) => {
if (err) {
console.log(err);
res.redirect('/register');
} else {
passport.authenticate('local')(req, res, () =>
res.redirect('/secrets'));
}
})
);
router.get('/auth/google',
passport.authenticate('google', { scope: ['profile'] }));
router.get('/auth/google/secrets',
passport.authenticate('google', { failureRedirect: '/login' }),
function (req, res) {
// Successful authentication
res.redirect('/secrets');
});
router.route('/login')
.get((req, res) => res.render('login'))
.post((req, res) => {
const user = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, (err) => {
if (err)
console.log(err)
else {
passport.authenticate('local')(req, res, () =>
res.redirect('/secrets')
);
}
})
});
router.get('/logout', (req, res) => {
req.logout((err) => {
if (err)
console.log(err)
else {
res.redirect('/login');
}
})
})
router.get('/secrets', function (req, res) {
const secretNames = [];
Secret.find(function (err, secrets) {
if (err) {
console.log(err);
} else {
if (req.isAuthenticated()) {
secrets.forEach(secret => {
secretNames.push(secret.name);
});
res.render('secrets', { secrets: secretNames });
} else {
res.redirect('/login');
}
}
});
});
router.route('/submit')
.get((req, res) => {
if (req.isAuthenticated()) {
res.render('submit');
} else {
res.redirect('/login');
}
})
.post((req, res) => {
if (req.isAuthenticated()) {
User.findById(req.user.id, (err, user) => {
if (err) {
console.log(err);
} else if (!user) {
console.log('user not found');
} else {
const submittedSecret = new Secret({ name: req.body.secret, user: user });
submittedSecret.save();
}
});
res.redirect('/secrets');
} else {
res.redirect('/login');
}
})
module.exports = router;