-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
100 lines (87 loc) · 2.62 KB
/
server.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
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
// Require necessary packages
const express = require('express')
const app = express()
const bcrypt = require('bcryptjs')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const methodOverride = require('method-override')
// Initialize Passport.js for login inputs
const initializePassport = require('./passport-config')
initializePassport(
passport,
email => users.find(user => user.email === email),
id => users.find(user => user.id === id)
)
// Array for storing users
const users = []
// Set packages in use
app.set('view-engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.use('/public', express.static(__dirname + '/public' ));
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))
// GET request for index file
app.get('/', checkAuthenticated, (req, res) => {
res.render('index.ejs', { name: req.user.name })
})
// GET for login file
app.get('/login', checkNotAuthenticated, (req, res) => {
res.render('login.ejs')
})
// POST request for login file
app.post('/login', checkNotAuthenticated, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}))
// GET request for register file
app.get('/register', checkNotAuthenticated, (req, res) => {
res.render('register.ejs')
})
// POST request for register file, including password encryption
app.post('/register', checkNotAuthenticated, async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
users.push({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
res.redirect('/login')
} catch {
res.redirect('/register')
}
})
// DELETE request, for logout
app.delete('/logout', (req, res) => {
req.logOut()
res.redirect('/login')
})
// Check if user is authenticated
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.redirect('/login')
}
// Check if user is not authenticated
function checkNotAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return res.redirect('/')
}
next()
}
// Listen to port 3000
app.listen(3000)