forked from Tythla/TopFlush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
53 lines (45 loc) · 1.29 KB
/
auth.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
const express = require('express');
const bcrypt = require('bcryptjs');
const User = require('./models/users');
const router = express.Router();
// Login route
router.post('/login', async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.getUserByUsername(username);
if (user && bcrypt.compareSync(password, user.hashedPassword)) {
req.session.user = user;
res.redirect('/home');
} else {
res.redirect('/login');
}
} catch (err) {
console.error(err);
res.status(500).send('Error during login.');
}
});
// Register route
router.post('/register', async (req, res) => {
try {
const { username, email, password } = req.body;
const existingUser = await User.getUserByUsername(username);
if (existingUser) {
// username already taken
res.redirect('/register');
} else {
await User.createUser(username, email, password);
const newUser = await User.getUserByUsername(username);
req.session.user = newUser;
res.redirect('/home');
}
} catch (err) {
console.error(err);
res.status(500).send('Error during registration.');
}
});
// Logout route
router.get('/logout', (req, res) => {
req.session.destroy();
res.redirect('/login');
});
module.exports = router;