-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreateUser.ts
More file actions
67 lines (44 loc) · 1.48 KB
/
createUser.ts
File metadata and controls
67 lines (44 loc) · 1.48 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
import { Request, Response } from 'express';
import { insertUser } from '../data/insertUser';
import { generate } from '../services/idGenerator';
import { generateToken } from '../services/authenticator';
import { users } from '../types/users';
import { hash } from '../services/hashManager'
import { USER_ROLES } from '../types/users'
export default async function createUser(
req: Request,
res: Response,
): Promise<void> {
try {
const { email, password, role } = req.body
if (!email || email.indexOf("@") === -1) {
throw new Error("E-mail inválido!")
}
if (!password || password.length < 6) {
throw new Error("A senha deve conter mais de seis digitos!")
}
if (role !== USER_ROLES.ADMIN && role !== USER_ROLES.NORMAL) {
throw new Error(`"role" deve ser "NORMAL" ou "ADMIN"`)
}
const id: string = generate()
const cypherPassword: string = await hash(password)
const newUser: users = {
id,
email,
password: cypherPassword,
role
}
await insertUser(newUser)
const token = generateToken({
id,
role: req.body.role
})
res
.status(200)
.send({message: "Usuário criado com sucesso!", token })
} catch (error) {
res.status(400).send({
message: error.message || error.sqlMessage
})
}
}