-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.router.js
63 lines (48 loc) · 1.76 KB
/
users.router.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
import express from 'express';
import bcrypt from 'bcrypt';
import { nanoid } from 'nanoid';
import { createUser, getUserByUsername } from '../data/queries.js';
const usersRouter = express.Router();
const saltRounds = 10;
usersRouter.post('/', async (req, res) => {
const { username, password } = req.body;
// Minimal Input Validation
if (!username || !password) {
return res.status(400).json({ error: 'Missing required property' });
}
// Hash Password
const hashedPassword = await bcrypt.hash(password, saltRounds);
const userId = nanoid();
const recordedUser = getUserByUsername.get(username);
if (recordedUser)
return res.status(400).json({ error: 'Username already exists' });
const newUser = createUser.get(userId, username, hashedPassword, Date.now());
return res.status(201).json({
userId: newUser.user_id,
username: newUser.username,
joined: new Date(newUser.created_at).toISOString(),
});
});
// No real login implementation will be used, this is only for the purpose of illustration
usersRouter.post('/session', async (req, res) => {
const { username, password } = req.body;
// Minimal Input Validation
if (!username || !password) {
return res.status(400).json({ error: 'Missing required property' });
}
const registeredUser = getUserByUsername.get(username);
if (!registeredUser) return res.status(400).json({ error: 'User not found' });
// Check for password
const isCorrectPassword = await bcrypt.compare(
password,
registeredUser.password
);
if (!isCorrectPassword) {
return res.status(400).json({ error: 'Incorrect Password' });
}
// Login Implementation
return res
.status(200)
.json({ message: 'Login Success', user: registeredUser.username });
});
export default usersRouter;