forked from amand33p/bug-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
75 lines (60 loc) · 1.91 KB
/
Copy pathauth.ts
File metadata and controls
75 lines (60 loc) · 1.91 KB
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
import { Request, Response } from 'express';
import { User } from '../entity/User';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import { JWT_SECRET } from '../utils/config';
import { registerValidator, loginValidator } from '../utils/validators';
export const signupUser = async (req: Request, res: Response) => {
const { username, password } = req.body;
const { errors, valid } = registerValidator(username, password);
if (!valid) {
return res.status(400).send({ message: Object.values(errors)[0] });
}
const existingUser = await User.findOne({
where: `"username" ILIKE '${username}'`,
});
if (existingUser) {
return res
.status(401)
.send({ message: `Username '${username}' is already taken.` });
}
const saltRounds = 10;
const passwordHash = await bcrypt.hash(password, saltRounds);
const user = User.create({ username, passwordHash });
await user.save();
const token = jwt.sign(
{
id: user.id,
username: user.username,
},
JWT_SECRET
);
return res.status(201).json({
id: user.id,
username: user.username,
token,
});
};
export const loginUser = async (req: Request, res: Response) => {
const { username, password } = req.body;
const { errors, valid } = loginValidator(username, password);
if (!valid) {
return res.status(400).send({ message: Object.values(errors)[0] });
}
const user = await User.findOne({
where: `"username" ILIKE '${username}'`,
});
if (!user) {
return res.status(401).send({ message: `User: '${username}' not found.` });
}
const credentialsValid = await bcrypt.compare(password, user.passwordHash);
if (!credentialsValid) {
return res.status(401).send({ message: 'Invalid credentials.' });
}
const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET);
return res.status(201).json({
id: user.id,
username: user.username,
token,
});
};