-
Notifications
You must be signed in to change notification settings - Fork 383
/
index.js
56 lines (45 loc) · 1.62 KB
/
index.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
const express = require('express')
const app = express()
const cors = require('cors')
const passport = require('passport');
const cookieSession = require('cookie-session')
require('dotenv').config()
require('./passport-setup');
app.use(cors())
// parse application/json
app.use(express.json())
// For an actual app you should configure this with an experation time, better keys, proxy and secure
app.use(cookieSession({
name: 'tuto-session',
keys: ['key1', 'key2']
}))
// Auth middleware that checks if the user is logged in
const isLoggedIn = (req, res, next) => {
if (req.user) {
next();
} else {
res.sendStatus(401);
}
}
// Initializes passport and passport sessions
app.use(passport.initialize());
app.use(passport.session());
// Example protected and unprotected routes
app.get('/', (req, res) => res.send('Example Home page!'))
app.get('/failed', (req, res) => res.send('You Failed to log in!'))
// In this route you can see that if the user is logged in u can acess his info in: req.user
app.get('/good', isLoggedIn, (req, res) => res.send(`Welcome mr ${req.user.displayName}!`))
// Auth Routes
app.get('/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/google/callback', passport.authenticate('google', { failureRedirect: '/failed' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/good');
}
);
app.get('/logout', (req, res) => {
req.session = null;
req.logout();
res.redirect('/');
})
app.listen(process.env.EXPRESS_PORT, () => console.log(`Example app listening on port ${process.env.EXPRESS_PORT}!`))