-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
64 lines (55 loc) · 1.91 KB
/
app.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
64
const express = require('express')
const app = express()
const PORT = 3000
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
app.use(express.json())
app.post('/user/register', async (req, res) => {
const { username, password } = req.body
try {
const existingUser = await prisma.user.findUnique({
where: { username }
})
if (existingUser) {
return res.status(409).json({ error: '똑같은 이름의 유저가 존재합니다' })
}
const hashedPassword = await bcrypt.hash(password, 10)
const createUser = await prisma.user.create({
data: {
username,
password: hashedPassword
}
})
res.status(201).json(createUser)
} catch (error) {
res.status(500).json({ error: '내부 서버 오류' })
}
})
app.post('/user/login', async (req, res) => {
try {
const { username, password: inputPassword } = req.body
const findUser = await prisma.user.findUnique({ where: { username } })
if(!findUser) {
const err = new Error('잘못된 정보입니다')
err.statusCode = 400
throw err
}
const { id, password: hashedPassword } = findUser
const Validpassword = await bcrypt.compare(inputPassword, hashedPassword)
if(!Validpassword) {
const err = new Error('잘못된 정보입니다')
err.statusCode = 400
throw err
}
const token = jwt.sign({ id }, 'secret_key', { expiresIn: '1h'})
res.status(200).json({ message: 'login success', token })
}
catch (err) {
res.status(err.statusCode).json({ message: err.message})
}
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})