Skip to content

Commit 83279a5

Browse files
Main server file to handle requests
1 parent 014224d commit 83279a5

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

server.js

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
const express = require('express')
2+
const hbs = require('express-handlebars')
3+
const app = express()
4+
const bcrypt = require('bcrypt')
5+
const passport = require('passport')
6+
const flash = require('express-flash')
7+
const session = require('express-session')
8+
const methodOverride = require('method-override')
9+
10+
const initializePassport = require('./authentication')
11+
initializePassport(
12+
passport,
13+
email => users.find(user => user.email === email),
14+
id => users.find(user => user.id === id)
15+
)
16+
17+
const users = []
18+
app.engine('handlebars', hbs())
19+
app.set('view engine', 'handlebars')
20+
21+
app.use(express.urlencoded({ extended: false }))
22+
app.use(flash())
23+
app.use(session({
24+
secret: 'secret',
25+
resave: false,
26+
saveUninitialized: false
27+
}))
28+
app.use(passport.initialize())
29+
app.use(passport.session())
30+
app.use(methodOverride('_method'))
31+
32+
app.get('/', checkAuthenticated, (req, res) => {
33+
res.render('index', { name: req.user.name })
34+
})
35+
36+
app.get('/login', checkNotAuthenticated, (req, res) => {
37+
res.render('login')
38+
})
39+
40+
app.post('/login', checkNotAuthenticated, passport.authenticate('local', {
41+
successRedirect: '/',
42+
failureRedirect: '/login',
43+
failureFlash: true
44+
}))
45+
46+
app.get('/register', checkNotAuthenticated, (req, res) => {
47+
res.render('register')
48+
})
49+
50+
app.post('/register', checkNotAuthenticated, async (req, res) => {
51+
try {
52+
const hashedPassword = await bcrypt.hash(req.body.password, 10)
53+
users.push({
54+
id: Date.now().toString(),
55+
name: req.body.name,
56+
email: req.body.email,
57+
password: hashedPassword
58+
})
59+
console.log(users)
60+
res.redirect('/login')
61+
} catch {
62+
res.redirect('/register')
63+
}
64+
})
65+
66+
app.delete('/logout', (req, res) => {
67+
req.logOut()
68+
res.redirect('/login')
69+
})
70+
71+
function checkAuthenticated(req, res, next) {
72+
if (req.isAuthenticated()) {
73+
return next()
74+
}
75+
76+
res.redirect('/login')
77+
}
78+
79+
function checkNotAuthenticated(req, res, next) {
80+
if (req.isAuthenticated()) {
81+
return res.redirect('/')
82+
}
83+
next()
84+
}
85+
86+
app.listen(3000)

0 commit comments

Comments
 (0)