-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (45 loc) · 1.58 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
const express = require('express')
const app = express()
const cors = require('cors')
const bodyParser = require('body-parser')
const passport = require('passport');
const cookieSession = require('cookie-session')
require('./passport-setup');
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//this is because it is only a sample application
app.use(cookieSession({
name: 'web1',
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('hey this is home page go to "/google"'))
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${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(3000, () => console.log(`Example app listening on port ${3000}!`))