From 4255e28f8fa2043fd78e300b2530c4d36b88a51d Mon Sep 17 00:00:00 2001 From: qwdbwp Date: Thu, 24 Nov 2022 23:43:02 +0900 Subject: [PATCH] solved: assignment complete --- src/controller/auth/ctrl.js | 51 ++++++++++++++ src/controller/auth/index.js | 9 +++ src/controller/index.js | 6 ++ src/controller/users/ctrl.js | 103 +++++++++++++++++++++++++++++ src/controller/users/index.js | 14 ++++ src/db.env | 9 +++ src/index.js | 55 +++++++++++++++ src/lib/authentification.js | 1 + src/middleware/authentification.js | 22 ++++++ src/utils/jwt.js | 32 +++++++++ 10 files changed, 302 insertions(+) create mode 100644 src/controller/auth/ctrl.js create mode 100644 src/controller/auth/index.js create mode 100644 src/controller/users/ctrl.js create mode 100644 src/controller/users/index.js create mode 100644 src/db.env create mode 100644 src/middleware/authentification.js create mode 100644 src/utils/jwt.js diff --git a/src/controller/auth/ctrl.js b/src/controller/auth/ctrl.js new file mode 100644 index 0000000..b5df9bb --- /dev/null +++ b/src/controller/auth/ctrl.js @@ -0,0 +1,51 @@ +const { runQuery } = require('../../lib/database'); +const { use } = require('../users'); + +const register = async (req, res) => { + const { username, password, displayname } = req.body; + if (!username || !password || !displayname) { + return res.status(400).send('Bed Request'); + } + + const sql = 'INSERT INTO users (username, password, displayname) VALUES (?, ?, ?)'; + const data = [username, password, displayname]; + + try { + const result = await runQuery(sql, data); + + if (result.affectedRows === 1) { + return res.status(201).send('Created'); + } + } catch (e) { + console.log(e); + return res.status(500).send('Internal Server Error'); + } +}; + +const signIn = async (req, res) => { + const { username, password } = req.body; + + if (!username || !password){ + return res.status(400).send('Bad Request'); + } + + const sql = 'SELECT * FROM users WHERE username = ? AND password = ?'; + const data = [username, password]; + + try { + const result = await runQuery(sql, data); + + if (result.length === 1) { + return res.status(200).send('OK'); + } else { + return res.status(401).send('Unauthorized'); + } + } catch (e) { + return res.status(500).send('Internal Sever Error'); + } +}; + +module.exports = { + register, + signIn, +}; diff --git a/src/controller/auth/index.js b/src/controller/auth/index.js new file mode 100644 index 0000000..253f778 --- /dev/null +++ b/src/controller/auth/index.js @@ -0,0 +1,9 @@ +const { Router } = require('express'); +const { register, signIn } = require('./ctrl'); + +const router = Router(); + +router.post('/register', register); +router.post('/sign-in', signIn); + +module.exports = router; \ No newline at end of file diff --git a/src/controller/index.js b/src/controller/index.js index dc5ff2a..55c6cd5 100644 --- a/src/controller/index.js +++ b/src/controller/index.js @@ -1,4 +1,10 @@ const { Router } = require('express'); +const users = require('./users'); +const auth = require('./auth'); + const router = Router(); +router.use('/auth', auth); +router.use('/users', users); + module.exports = router; diff --git a/src/controller/users/ctrl.js b/src/controller/users/ctrl.js new file mode 100644 index 0000000..8e26b35 --- /dev/null +++ b/src/controller/users/ctrl.js @@ -0,0 +1,103 @@ +const { runQuery } = require('../../lib/database'); + +const allUsers = async (req, res) => { + const sql = 'SELECT * FROM users'; + + try { + const result = await runQuery(sql); + + return res.status(200).send(result); + } catch (e) { + return res.status(500).send('Internal Server Error'); + } +}; + +const getUser = async (req, res) => { + const { id } = req.params; + const sql = 'SELELCT * FROM users WHERE id = ?'; + const data =[id]; + + try { + const result = await runQuery(sql, data); + + if (result.length === 1) { + return res.status(200).send(result[0]); + } else { + return res.status(400).send('Bad Request'); + } + } catch (e) { + return res.status(500).send('Internal Server Error'); + } +}; + +const register = (req, res) => { + const { name, age } = req.body; + obj_list = obj_list.concat({ + id: id++, + name, + age, + }); + + res.send(obj_list); +}; + +const updateUser = (req, res) => { + const { id } = req.params; + const { name, age } = req.body; + + idx = obj_list.findIndex((obj) => obj.id === id); + if (obj_idx === -1){ + res.send('Not Found '); + } else { + obj_list[idx] = { id, name, age }; + res.send(obj_list); + } +}; + +const signIn = (req, res) => { + const { userName, password } = req.body; + const user = datas.find(data => data.userName === userName); + + if (user.password === password){ + const token = jwt.sign(user) + + return res.send({ + status: 200, + token: token + }) + } else { + return res.send({ + status: 400, + message: 'BAD REQUEST', + token: null + }) + } +}; + +const accessAdminPage = (req, res) => { + if (!req.role) { + res.send({ + status: 400, + message: 'BAD REQUEST' + }) + } else if (req.role === 'admin'){ + res.send({ + status: 200, + message: 'SUCCESS' + }) + } else { + res.send({ + status: 401, + message: 'UNAUTHORIZED' + }) + } +}; + +module.exports = { + register, + updateUser, + signIn, + accessAdminPage, + allUsers, + getUser, +}; \ No newline at end of file diff --git a/src/controller/users/index.js b/src/controller/users/index.js new file mode 100644 index 0000000..2784629 --- /dev/null +++ b/src/controller/users/index.js @@ -0,0 +1,14 @@ +const { Router } = require('express'); +const { allUsers, getUser, signIn, register, findByTag, accessAdminPage } = require('./ctrl'); +const { authentification } = require('../../middleware/authentification') + +const router = Router(); + +router.get('/result', findByTag); +router.post('/', register); +router.post('/sign-in', signIn); +router.get('/admin-page', authentification, accessAdminPage); +router.get('/', allUsers); +router.get('/:id', getUser); + +module.exports = router; \ No newline at end of file diff --git a/src/db.env b/src/db.env new file mode 100644 index 0000000..065aa11 --- /dev/null +++ b/src/db.env @@ -0,0 +1,9 @@ +PORT = 4000 + +DB_HOST = localhost +DB_PORT = 3306 +DB_USER = 'bar' +DB_PASS = 'bar' +DB_NAME = 'user' + +JWT_TOKEN=Cw6vgPIc2MPv2WUrw5g7JdbBBtdnAkj8 \ No newline at end of file diff --git a/src/index.js b/src/index.js index 3f55d94..45ea922 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,9 @@ + + const app = require('./app'); require('./env'); +const router = require('./controller'); +app.use('/api', router); const PORT = process.env.PORT || 4000; @@ -7,3 +11,54 @@ app.listen(PORT, () => { console.log(`server is listening on PORT: ${PORT}`); console.log(`http://localhost:${PORT}`); }); + + +/* +- GET: /api/users - DB에 있는 모든 유저들의 닉네임 리스트를 반환합니다. +- GET: /api/users/:id - DB에서 해당 id를 가진 유저 반환합니다. +- GET: /api/users/results - DB에서 해당 문자열을 포함한 닉네임을 가진 유저들을 반환합니다. +- PUT: /api/users/:id - DB에서 해당 id를 가진 유저의 회원정보를 수정합니다. +- DELETE: /api/users/:id - 해당 id를 가진 유저의 회원탈퇴를 수행합니다. +*/ + +app.get('/api/users', (req, res) => { + res.send('모든 유저들의 닉네임 리스트를 반환했습니다.'); +}); + +app.get('/api/users/:id', (req, res) => { + const { id } = req.params; + res.send(id); +}); + +app.get('/api/users/results', (req, res) => { + const { tag } = req.query; + const people = obj_list.filter((obj) => obj.tags.includes(tag)); + + if (people.lenth == 0){ + res.send('존재하지 않습니다.'); + } else { + res.send(people); + } +}) + +app.put('/api/users/:id', (req, res) => { + const { id } = req.params; + const { name, age } = req.body; + idx = obj.list.findIndex((obj) => obj.id == id); + if (ooj_idx === -1){ + res.send('존재하지 않습니다.'); + } else { + obj_list[idx] = { id, name, age }; + res.send(obj_list); + } +}); + +app.delete('/api/users/:id', (req, res) => { + res.send('회원탈퇴가 완료됐습니다.'); +}); + +/* +- POST: /api/auth/register - 회원가입을 수행합니다. +- POST: /api/auth/login - 로그인을 수행합니다. +- GET: /api/auth/logout - 로그아웃을 수행합니다. +*/ diff --git a/src/lib/authentification.js b/src/lib/authentification.js index cebd970..73e279d 100644 --- a/src/lib/authentification.js +++ b/src/lib/authentification.js @@ -1,6 +1,7 @@ const util = require('util'); const crypto = require('crypto'); + const pbkdf2 = util.promisify(crypto.pbkdf2); const randomBytes = util.promisify(crypto.randomBytes); diff --git a/src/middleware/authentification.js b/src/middleware/authentification.js new file mode 100644 index 0000000..e7c5b4a --- /dev/null +++ b/src/middleware/authentification.js @@ -0,0 +1,22 @@ +const jwt = require('../utils/jwt'); + +const authentification = (req, res, next) => { + const { token } = req.body; + + const verify = jwt.verify(token); + if (verify.OK) { + req.id = verify.id; + req.role = verify.role; + + next(); + } else { + res.send({ + status: 400, + message: 'BAD REQUEST', + }) + } +} + +module.exports = { + authentification +} \ No newline at end of file diff --git a/src/utils/jwt.js b/src/utils/jwt.js new file mode 100644 index 0000000..23493fa --- /dev/null +++ b/src/utils/jwt.js @@ -0,0 +1,32 @@ +const jwt = require('jsonwebtoken'); +const SECRET = 'SecretCode' + +module.exports = { + sign: (user) => { + const payload = { + id: user.id, + role: user.role + } + + return jwt.sign(payload, SECRET, { + algorithm: 'HS256', + expiresIn: '7d' + }) + }, + + verify: (token) => { + try { + const decoded = jwt.verify(token, SECRET); + return { + OK: true, + id: decoded.id, + role: decoded.role + } + } catch (e) { + return { + OK: false, + message: err.message + } + } + } +}; \ No newline at end of file