-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUserController.js
42 lines (33 loc) · 1.29 KB
/
UserController.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
const { AUTH_TOKEN_SALT } = process.env
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const { UserService } = require('../services')
const { errorWrapper, errorGenerator } = require('../errors')
const signUp = errorWrapper(async (req, res) => {
const { email, password } = req.body
const hashedPassword = await bcrypt.hash(password, 10)
const foundUser = await UserService.findUser({ email })
if (foundUser) errorGenerator({ statusCode: 409, message: 'duplicated' })
const createdUser = await UserService.createUser({
email,
password: hashedPassword,
})
res.status(201).json({
message: 'user created',
email: createdUser.email,
})
})
const logIn = errorWrapper(async (req, res) => {
const { email, password: inputPassword } = req.body
const foundUser = await UserService.findUser({ email })
if (!foundUser) errorGenerator({ statusCode: 400, message: 'client input invalid' })
const { id, password: hashedPassword } = foundUser
const isValidPassword = await bcrypt.compare(inputPassword, hashedPassword)
if (!isValidPassword) errorGenerator({ statusCode: 400, message: 'client input invalid' })
const token = jwt.sign({ id }, AUTH_TOKEN_SALT)
res.status(200).json({ message: 'login success!', token })
})
module.exports = {
logIn,
signUp,
}