Skip to content

Commit db9ed41

Browse files
committed
Add: Users API + Prisma Modularized
0 parents  commit db9ed41

File tree

16 files changed

+2407
-0
lines changed

16 files changed

+2407
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.env
2+
node_modules

app.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const express = require('express')
2+
const routes = require('./routes')
3+
const logger = require('morgan')('dev')
4+
5+
const app = express()
6+
7+
app.use(express.json())
8+
app.use(logger)
9+
app.use(routes)
10+
11+
app.use((err, req, res, next) => {
12+
const { status, message } = err
13+
console.error(err)
14+
res.status(status || 500).json({ message })
15+
})
16+
17+
module.exports = app

controllers/UserController.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
const { AUTH_TOKEN_SALT } = process.env
2+
const bcrypt = require('bcrypt')
3+
const jwt = require('jsonwebtoken')
4+
const { UserService } = require('../services')
5+
const errorGenerator = require('../utils/errorGenerator')
6+
7+
const signUp = async (req, res, next) => {
8+
try {
9+
const { email, password } = req.body
10+
11+
const hashedPassword = await bcrypt.hash(password, 10)
12+
13+
const foundUser = await UserService.findUser({ email })
14+
15+
if (foundUser) errorGenerator({ statusCode: 409, message: 'duplicated' })
16+
17+
const createdUser = await UserService.createUser({
18+
email,
19+
password: hashedPassword,
20+
})
21+
22+
res.status(201).json({
23+
message: 'user created',
24+
user_id: createdUser.id,
25+
})
26+
} catch (err) {
27+
next(err)
28+
}
29+
}
30+
31+
const logIn = async (req, res, next) => {
32+
try {
33+
const { email, password: inputPassword } = req.body
34+
35+
const foundUser = await UserService.findUser({ email })
36+
37+
if (!foundUser)
38+
errorGenerator({ statusCode: 400, message: 'client input invalid' })
39+
40+
const { id, password: hashedPassword } = foundUser
41+
const isValidPassword = await bcrypt.compare(inputPassword, hashedPassword)
42+
43+
if (!isValidPassword)
44+
errorGenerator({ statusCode: 400, message: 'client input invalid' })
45+
46+
const token = jwt.sign({ id }, AUTH_TOKEN_SALT, { expiresIn: '1h' })
47+
res.status(200).json({ message: 'login success!', token })
48+
} catch (err) {
49+
next(err)
50+
}
51+
}
52+
53+
module.exports = {
54+
logIn,
55+
signUp,
56+
}

controllers/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const UserController = require('./UserController')
2+
3+
module.exports = {
4+
UserController,
5+
}

0 commit comments

Comments
 (0)