-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (59 loc) · 1.91 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
57
58
59
60
61
62
63
64
65
66
67
68
69
require('dotenv').config()
const path = require('path')
const express = require('express')
const _ = require('lodash')
const cookieSession = require('cookie-session')
const { createJwtClient, createRouter } = require('pnp-authentication-service')
const config = { EMAIL_TEMPLATES_DIR: path.join(__dirname, 'templates') }
const jwt = createJwtClient(config)
exports.startServer = (callback) => {
const port = process.env.PORT || 3000
const app = express()
app.set('view engine', 'pug')
app.set('views', './views')
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2'],
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))
const router = createRouter(config)
app.use('/auth', router)
app.get('/', (req, res, next) => {
const user = req.session.user
res.render('index.pug', { user })
})
app.get('/home', (req, res, next) => {
const user = req.session.user
if (!user) return res.redirect('/auth/signin')
jwt.sign({ userId: user.id })
.then(jwtToken => {
res.render('home.pug', { user, jwtToken })
})
.catch(next)
})
app.get('/callback', (req, res, next) => {
if (!req.query.jwt) return res.redirect('/')
jwt.verify(req.query.jwt)
.then(data => {
const user = _.pick(data.user, ['id', 'firstName', 'lastName', 'image'])
req.session.user = user
res.redirect('/home')
})
.catch(next)
})
app.get('/logout', (req, res, next) => {
req.session = null
res.redirect('/')
})
const stylesheetFullPath = path.join(__dirname, '/static/stylesheet.css')
app.get('/stylesheet.css', (req, res, next) => {
res.sendFile(stylesheetFullPath, {}, err => err && next(err))
})
return app.listen(port, callback)
}
if (require.main === module) {
const server = exports.startServer(() => {
const port = server.address().port
console.log(`Listening on port ${port}! Visit http://127.0.0.1:${port}/`)
})
}