-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutes.js
More file actions
85 lines (80 loc) · 2.75 KB
/
Copy pathroutes.js
File metadata and controls
85 lines (80 loc) · 2.75 KB
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
const passport = require('passport');
const GitHubStrategy = require('passport-github').Strategy;
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
};
module.exports = function (app, myDataBase) {
app.route('/').get((req, res) => {
//Change the response to render the Pug template
res.render('pug', {
title: 'Connected to Database',
message: 'Please login',
showLogin: true,
showRegistration: true,
showSocialAuth: true
});
});
app.route('/profile').get(ensureAuthenticated, (req, res) => {
//Change the response to render the Pug template
res.render(process.cwd() + '/views/pug/profile', { username: req.user.username });
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', {
failureRedirect: '/'
}), (req, res) => {
req.session.user_id = req.user.id;
return res.redirect('/chat');
});
app.post('/login', passport.authenticate('local', {
failureRedirect: '/'
}), (req, res) => {
return res.redirect('/profile');
}
);
app.route('/logout')
.get((req, res) => {
req.logout();
res.redirect('/');
});
app.route('/register')
.post((req, res, next) => {
myDataBase.findOne({ username: req.body.username }, function (err, user) {
if (err) {
next(err);
} else if (user) {
res.redirect('/');
} else {
myDataBase.insertOne({
username: req.body.username,
password: bcrypt.hashSync(req.body.password, 12)
},
(err, doc) => {
if (err) {
res.redirect('/');
} else {
// The inserted document is held within
// the ops property of the doc
next(null, doc.ops[0]);
}
}
)
}
})
},
passport.authenticate('local', { failureRedirect: '/' }),
(req, res, next) => {
res.redirect('/profile');
}
);
app.get('/chat', ensureAuthenticated, (req, res) => {
return res.render(process.cwd() + '/views/pug/chat', { user: req.user })
})
app.use((req, res, next) => {
res.status(404)
.type('text')
.send('Not Found');
});
}