From fb26eb261bd84a01137505343187e2d13f3161b0 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 09:58:13 +0900 Subject: [PATCH 01/47] modify brace-style --- .eslintrc.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.eslintrc.json b/.eslintrc.json index 9a8cffd..38b1208 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -24,6 +24,7 @@ "no-unused-vars": 1, "no-multiple-empty-lines": 0, "space-before-function-paren": 0, - "eol-last": 0 + "eol-last": 0, + "brace-style": ["error", "stroustrup"] } } From ed6604a9ad28eea9bcd904473743814599325205 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 12:50:59 +0900 Subject: [PATCH 02/47] add moment, moment-timezone for time, request for using nh api --- package.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/package.json b/package.json index 10ff71c..d0e7cee 100644 --- a/package.json +++ b/package.json @@ -16,9 +16,12 @@ "express-session": "^1.17.1", "http-errors": "^1.8.0", "jsonwebtoken": "^8.5.1", + "moment": "^2.29.1", + "moment-timezone": "^0.5.32", "morgan": "~1.9.1", "mysql2": "^2.2.5", "nodemon": "^2.0.6", + "request": "^2.88.2", "sequelize": "^6.3.5" }, "devDependencies": { From 302514027601f540855eef23cc1b6f139cf0233b Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 12:52:45 +0900 Subject: [PATCH 03/47] eslint --- models/index.js | 2 +- routes/auth.js | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/models/index.js b/models/index.js index 468205b..bea73a9 100644 --- a/models/index.js +++ b/models/index.js @@ -14,5 +14,5 @@ db.Event = require('./event')(sequelize, Sequelize); db.EventAdmin = require('./eventadmin')(sequelize, Sequelize); db.Guest = require('./guest')(sequelize, Sequelize); -db.Event.hasMany(db.Guest, { foreignKey: { name: 'event_id'} }); +db.Event.hasMany(db.Guest, {foreignKey: {name: 'event_id'}}); module.exports = db; diff --git a/routes/auth.js b/routes/auth.js index 8868bb6..fc409de 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -34,7 +34,8 @@ router.get('/', function(req, res, next) { const session = req.session; if(session.name) { res.json(session.name); - } else{ + } + else{ res.json('login fail'); } }); @@ -50,7 +51,8 @@ router.post('/login', async function(req, res, next) { res.status(404).json({ 'detail': 'No user found.', }); - } else { + } + else { console.log(user.dataValues); const dbPassword = user.dataValues.password; const inputPassword = body.password; @@ -67,7 +69,8 @@ router.post('/login', async function(req, res, next) { token: jwtSignUser(user), user: user, }); - } else { + } + else { console.log('pw incorrect'); res.status(401).json({ auth: false, @@ -75,7 +78,8 @@ router.post('/login', async function(req, res, next) { }); } } - } catch (error) { + } + catch (error) { console.log('Login Error'); next(error); } From 84fb7004df089ba9a367b1c34fd30510f9ac9b8d Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 12:53:10 +0900 Subject: [PATCH 04/47] add event_hash column --- routes/event.js | 137 ++++++++++++++++++++++++++++++------------------ 1 file changed, 85 insertions(+), 52 deletions(-) diff --git a/routes/event.js b/routes/event.js index 7225627..58c6122 100644 --- a/routes/event.js +++ b/routes/event.js @@ -1,23 +1,26 @@ const express = require('express'); const router = express.Router(); +const bcrypt = require('bcrypt'); const {User, Event, EventAdmin, Guest} = require('../models'); const util = require('../utils'); const code = util.code; +const moment = require('moment'); +require('moment-timezone'); masterCheck = async function(userId, eventId) { const check = await Event.findOne({ - where: {user_id: userId, id: eventId} - }); + where: {user_id: userId, id: eventId}, + }); return check !== null; -} +}; guestCheck = async function(userId, eventId) { const check = await Guest.findOne({ - where: {user_id: userId, event_id: eventId} + where: {user_id: userId, event_id: eventId}, }); return check !== null; -} +}; // TO-DO : Solve Option Problem router.options('/', function(req, res) { @@ -48,10 +51,12 @@ router.post('/', async function(req, res, next) { if(adminResult == null) { admin.push({user_id: null, user_phone: eventAdmin[i]}); - } else { + } + else { admin.push({user_id: adminResult.id, user_phone: eventAdmin[i]}); } - } else { + } + else { responseJson.result = code.PHONE_NUMBER_INVALID; responseJson.detail = 'phone number invalid'; res.json(responseJson); @@ -67,17 +72,22 @@ router.post('/', async function(req, res, next) { const responseJson = {}; const body = req.body; try { + moment.tz.setDefault('Asia/Seoul'); + const time = moment().format('YYYY-MM-DD HH:mm:ss'); + const eventHash = bcrypt.hashSync(Math.random().toString(36).slice(2), util.saltRounds); + const result = await Event.create( { + event_hash: eventHash, user_id: res.locals.user.id, category: body.category, title: body.title, location: body.location, body: body.body, invitation_url: body.invitationUrl, - start_datetime: body.startDatetime, + start_datetime: time, end_datetime: body.endDatetime, - is_activate: true, + is_activated: true, }, ); console.dir(result); @@ -86,7 +96,8 @@ router.post('/', async function(req, res, next) { res.locals.admins[i].event_id = eventId; } next(); - } catch(exception) { + } + catch(exception) { console.log(exception); responseJson.result = code.UNKNOWN_ERROR; responseJson.detail = 'unknown error1'; @@ -104,40 +115,51 @@ router.post('/', async function(req, res, next) { responseJson.result = code.SUCCESS; responseJson.detail = 'success'; - } catch(exception) { + } + catch(exception) { console.log(exception); responseJson.result = code.UNKNOWN_ERROR; responseJson.detail = 'unknown error2'; - } finally { + } + finally { res.json(responseJson); } }); -router.put('/', async function(req, res, next) { +router.put('/:id', async function(req, res, next) { const responseJson = {}; const body = req.body; + const userId = req.params.id; + const eventId = body.id; try { - const result = await Event.update( - { - title: body.title, - location: body.location, - body: body.body, - invitation_url: body.invitation_url, - start_datetime: body.startDatetime, - end_datetime: body.endDatetime, - }, - { - where: { - id: body.id, - }}, - ); - responseJson.result = code.SUCCESS; - responseJson.detail = 'success'; - } catch(exception) { + if(await masterCheck(userId, eventId)) { + const result = await Event.update( + { + title: body.title, + location: body.location, + body: body.body, + invitation_url: body.invitation_url, + end_datetime: body.endDatetime, + }, + { + where: { + id: body.id, + }}, + ); + responseJson.result = code.SUCCESS; + responseJson.detail = 'success'; + } + else { + responseJson.result = code.NO_AUTH; + responseJson.detail = 'no auth'; + } + } + catch(exception) { responseJson.result = code.UNKNOWN_ERROR; responseJson.detail = 'unknown error'; - } finally { + } + finally { res.json(responseJson); } }); @@ -155,10 +177,12 @@ router.delete('/:id', async function(req, res, next) { responseJson.result = code.SUCCESS; responseJson.detail = 'success'; - } catch(exception) { + } + catch(exception) { responseJson.result = code.UNKNOWN_ERROR; responseJson.detail = 'unknown error'; - } finally { + } + finally { res.json(responseJson); } }); @@ -166,16 +190,17 @@ router.delete('/:id', async function(req, res, next) { router.get('/', async function(req, res, next) { const responseJson = {}; try { - const is_host = req.query.host; - if(typeof is_host === 'undefined') { + const isHost = req.query.host; + if(typeof isHost === 'undefined') { responseJson.result = code.INVALID_QUERY; responseJson.detail = 'params error'; - } else if(is_host === 'true') { + } + else if(isHost === 'true') { const result = await Event.findAll( { where: {user_id: res.locals.user.id}, order: [ - ['is_activate', 'DESC'], + ['is_activated', 'DESC'], ['end_datetime', 'DESC'], ], }, @@ -183,14 +208,15 @@ router.get('/', async function(req, res, next) { responseJson.result = code.SUCCESS; responseJson.detail = 'success'; responseJson.data = result; - } else { + } + else { const result = await Event.findAll({ include: [{ model: Guest, where: {user_id: res.locals.user.id}, }], order: [ - ['is_activate', 'DESC'], + ['is_activated', 'DESC'], ['end_datetime', 'DESC'], ], }); @@ -198,11 +224,13 @@ router.get('/', async function(req, res, next) { responseJson.detail = 'success'; responseJson.data = result; } - } catch(exception) { + } + catch(exception) { console.log(exception); responseJson.result = code.UNKNOWN_ERROR; responseJson.detail = 'unknown error'; - } finally { + } + finally { res.json(responseJson); } }); @@ -219,11 +247,11 @@ router.get('/:id', async function(req, res, next) { if (result === null) { responseJson.result = code.NO_DATA; responseJson.detail = 'cannot find eventData'; - } else { - + } + else { let haveAuth = result.dataValues.user_id === myId; if(!haveAuth) { - if(await guestCheck(myId,eventId)) { + if(await guestCheck(myId, eventId)) { haveAuth = true; } } @@ -232,7 +260,7 @@ router.get('/:id', async function(req, res, next) { const result2 = await EventAdmin.findAll( { attributes: ['user_phone'], - where: {event_id: eventId} + where: {event_id: eventId}, }, ); data.eventAdmin = result2; @@ -242,14 +270,16 @@ router.get('/:id', async function(req, res, next) { } else { responseJson.result = code.NO_AUTH; - responseJson.detail = 'no_auth' + responseJson.detail = 'no_auth'; } } - } catch(exception) { + } + catch(exception) { responseJson.result = code.UNKNOWN_ERROR; responseJson.detail = 'unknown error'; console.log(exception); - } finally { + } + finally { res.json(responseJson); } }); @@ -275,15 +305,18 @@ router.put('/close/:id', async function(req, res, next) { ); responseJson.result = code.SUCCESS; responseJson.detail = 'success'; - } else { + } + else { responseJson.result = code.NO_AUTH; - responseJson.detail = 'no_auth' + responseJson.detail = 'no_auth'; } - } catch(exception) { + } + catch(exception) { console.log(exception); responseJson.result = code.UNKNOWN_ERROR; responseJson.detail = 'unknown error'; - } finally { + } + finally { res.json(responseJson); } }); From 47d15f584c0076913d82672e173b2f976efcb1dc Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 12:53:50 +0900 Subject: [PATCH 05/47] add saltRounds --- utils.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/utils.js b/utils.js index 78299f1..1414283 100644 --- a/utils.js +++ b/utils.js @@ -16,7 +16,7 @@ value.code = { 'NAME_INVALID': 7, 'NO_DATA': 8, 'INVALID_QUERY': 9, - 'NO_AUTH': 10 + 'NO_AUTH': 10, }; value.phoneNumberCheck = function (phone) { @@ -33,7 +33,8 @@ value.getUser = function (req) { let decoded = ''; try { decoded = jwt.verify(authorization, config.jwtSecret); - } catch (e) { + } + catch (e) { return {detail: 'unauthorized'}; } return {detail: 'success', user: decoded.data}; @@ -42,4 +43,6 @@ value.getUser = function (req) { return {detail: 'no header'}; }; +value.saltRounds = 10; + module.exports = value; From c7bf2ec4f8ddfa7cc15b488de0d13ba9e65fe512 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 13:11:03 +0900 Subject: [PATCH 06/47] add event hash value --- models/event.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/models/event.js b/models/event.js index 3d3035a..6da1c20 100644 --- a/models/event.js +++ b/models/event.js @@ -7,6 +7,10 @@ module.exports = (sequelize, DataTypes) => { autoIncrement: true, primaryKey: true, }, + event_hash: { + type: DataTypes.STRING(100), + allowNull: false, + }, user_id: { type: DataTypes.INTEGER, allowNull: false, From 529d1ccad649c70c4e618d9e32c71843fd125e29 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 13:40:48 +0900 Subject: [PATCH 07/47] in put, add event id parameters, master check method --- routes/event.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/routes/event.js b/routes/event.js index 58c6122..61e3db6 100644 --- a/routes/event.js +++ b/routes/event.js @@ -129,8 +129,8 @@ router.post('/', async function(req, res, next) { router.put('/:id', async function(req, res, next) { const responseJson = {}; const body = req.body; - const userId = req.params.id; - const eventId = body.id; + const userId = res.locals.user.id; + const eventId = req.params.id; try { if(await masterCheck(userId, eventId)) { @@ -144,7 +144,7 @@ router.put('/:id', async function(req, res, next) { }, { where: { - id: body.id, + id: eventId, }}, ); responseJson.result = code.SUCCESS; From aef264a1b7ba9ebe67d562184d3de3ababe077d0 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 13:41:47 +0900 Subject: [PATCH 08/47] =?UTF-8?q?response=20json=20localize,=20=ED=9A=8C?= =?UTF-8?q?=EC=9B=90=EA=B0=80=EC=9E=85=EB=90=9C=20=ED=95=B8=EB=93=9C?= =?UTF-8?q?=ED=8F=B0=EB=B2=88=ED=98=B8=EA=B0=80=20eventadmin=EC=97=90=20?= =?UTF-8?q?=EC=9E=88=EC=9C=BC=EB=A9=B4=20user=5Fid=20update?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- routes/users.js | 49 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/routes/users.js b/routes/users.js index 4279db6..f4bfb25 100644 --- a/routes/users.js +++ b/routes/users.js @@ -1,21 +1,20 @@ const express = require('express'); const router = express.Router(); -const {User} = require('../models'); +const {User, EventAdmin} = require('../models'); const bcrypt = require('bcrypt'); const util = require('../utils.js'); -const saltRounds = 10; const code = util.code; -const responseJson = {}; - /* GET users listing. */ // 핸드폰번호 중복체크 // 회원인지 확인하고 문자 아니면 알림 보낼때 사용 router.get('/overlap/phone', async function(req, res, next) { + const responseJson = {}; if(!util.phoneNumberCheck(req.query.phone_number)) { responseJson.result = code.PHONE_NUMBER_INVALID; responseJson.detail = 'phone number invalid'; - } else { + } + else { const result = await User.findOne( {where: {phone_number: req.query.phone_number}}, ); @@ -23,7 +22,8 @@ router.get('/overlap/phone', async function(req, res, next) { if(result == null) { responseJson.result = code.SUCCESS; responseJson.detail = 'no exist'; - } else { + } + else { responseJson.result = code.PHONE_NUMBER_ALREADY_EXIST; responseJson.detail = 'phone number already exist'; } @@ -33,6 +33,7 @@ router.get('/overlap/phone', async function(req, res, next) { // 아이디 중복체크 router.get('/overlap/username', async function(req, res, next) { + const responseJson = {}; const result = await User.findOne( {where: {username: req.query.username}}, ); @@ -40,7 +41,8 @@ router.get('/overlap/username', async function(req, res, next) { if(result == null) { responseJson.result = code.SUCCESS; responseJson.detail = 'no exist'; - } else { + } + else { responseJson.result = code.USERNAME_ALREADY_EXIST; responseJson.detail = 'username already exist'; } @@ -49,24 +51,47 @@ router.get('/overlap/username', async function(req, res, next) { // 회원가입 router.post('/signup', async function(req, res, next) { + const responseJson = {}; try { if(util.phoneNumberCheck(req.body.phone_number)) { + const bcPw = bcrypt.hashSync(req.body.password, util.saltRounds); const result = await User.create({ username: req.body.username, - password: bcrypt.hashSync(req.body.password, saltRounds), + password: bcPw, name: req.body.name, phone_number: req.body.phone_number, }); responseJson.result = code.SUCCESS; responseJson.detail = 'signup success'; - } else { + + const userId = result.dataValues.id; + const isInvited = await EventAdmin.findOne( + {where: {user_phone: req.body.phone_number}}, + ); + + if(isInvited) { + await EventAdmin.update( + { + user_id: userId, + }, + { + where: { + user_phone: req.body.phone_number, + }, + }, + ); + } + } + else { responseJson.result = code.PHONE_NUMBER_INVALID; responseJson.detail = 'phone number invalid'; } - } catch(exception) { + } + catch(exception) { responseJson.result = code.UNKNOWN_ERROR; - responseJson.detail = exception.errors[0].message; - } finally { + responseJson.detail = 'unknown error'; + } + finally { res.json(responseJson); } }); From 77bac78888fab794d4b4dc1372638951d033b98a Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 14:13:43 +0900 Subject: [PATCH 09/47] modify event_hash in event model to unique --- models/event.js | 1 + 1 file changed, 1 insertion(+) diff --git a/models/event.js b/models/event.js index 6da1c20..60bc849 100644 --- a/models/event.js +++ b/models/event.js @@ -9,6 +9,7 @@ module.exports = (sequelize, DataTypes) => { }, event_hash: { type: DataTypes.STRING(100), + unique: true, allowNull: false, }, user_id: { From 2bdc01e17cffc186c1fcaa218dbb407b54c07536 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 15:48:53 +0900 Subject: [PATCH 10/47] delete start datetime, change end datetime to event datetime --- models/event.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/models/event.js b/models/event.js index 60bc849..b818452 100644 --- a/models/event.js +++ b/models/event.js @@ -37,11 +37,7 @@ module.exports = (sequelize, DataTypes) => { allowNull: true, defaultValue: null, }, - start_datetime: { - type: DataTypes.DATE, - allowNull: false, - }, - end_datetime: { + event_datetime: { type: DataTypes.DATE, allowNull: false, }, From fa63d82f5aa9de80e3350dbe1024628f7a4358e9 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 15:49:17 +0900 Subject: [PATCH 11/47] remove moment, moment-timezone --- package.json | 2 -- routes/event.js | 10 +++------- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index d0e7cee..feefeb3 100644 --- a/package.json +++ b/package.json @@ -16,8 +16,6 @@ "express-session": "^1.17.1", "http-errors": "^1.8.0", "jsonwebtoken": "^8.5.1", - "moment": "^2.29.1", - "moment-timezone": "^0.5.32", "morgan": "~1.9.1", "mysql2": "^2.2.5", "nodemon": "^2.0.6", diff --git a/routes/event.js b/routes/event.js index 61e3db6..579cbdc 100644 --- a/routes/event.js +++ b/routes/event.js @@ -4,8 +4,6 @@ const bcrypt = require('bcrypt'); const {User, Event, EventAdmin, Guest} = require('../models'); const util = require('../utils'); const code = util.code; -const moment = require('moment'); -require('moment-timezone'); masterCheck = async function(userId, eventId) { @@ -72,9 +70,8 @@ router.post('/', async function(req, res, next) { const responseJson = {}; const body = req.body; try { - moment.tz.setDefault('Asia/Seoul'); - const time = moment().format('YYYY-MM-DD HH:mm:ss'); - const eventHash = bcrypt.hashSync(Math.random().toString(36).slice(2), util.saltRounds); + const secretValue = Math.random().toString(36).slice(2) + res.locals.user.id + body.title; + const eventHash = bcrypt.hashSync(secretValue, util.saltRounds); const result = await Event.create( { @@ -85,8 +82,7 @@ router.post('/', async function(req, res, next) { location: body.location, body: body.body, invitation_url: body.invitationUrl, - start_datetime: time, - end_datetime: body.endDatetime, + event_datetime: body.eventDatetime, is_activated: true, }, ); From 2e3a9a147f7cb61a31beabb7f19dfa9cf9d4f085 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 15:54:31 +0900 Subject: [PATCH 12/47] odd in options /*, response event id in create event --- routes/event.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/routes/event.js b/routes/event.js index 579cbdc..ea7eab3 100644 --- a/routes/event.js +++ b/routes/event.js @@ -21,7 +21,7 @@ guestCheck = async function(userId, eventId) { }; // TO-DO : Solve Option Problem -router.options('/', function(req, res) { +router.options('/*', function(req, res) { return res.send({}); }); @@ -86,7 +86,7 @@ router.post('/', async function(req, res, next) { is_activated: true, }, ); - console.dir(result); + res.locals.eventId = result.dataValues.id; const eventId = result.dataValues.id; for(let i = 0; i < res.locals.admins.length; i++) { res.locals.admins[i].event_id = eventId; @@ -111,6 +111,7 @@ router.post('/', async function(req, res, next) { responseJson.result = code.SUCCESS; responseJson.detail = 'success'; + responseJson.data = {id: res.locals.eventId}; } catch(exception) { console.log(exception); From f5dca3c83fefae0f4dc89f20ae83d9f9540218bc Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 30 Nov 2020 16:55:22 +0900 Subject: [PATCH 13/47] modify end_datetime -> event_datetime --- routes/event.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/routes/event.js b/routes/event.js index ea7eab3..1821d55 100644 --- a/routes/event.js +++ b/routes/event.js @@ -136,8 +136,8 @@ router.put('/:id', async function(req, res, next) { title: body.title, location: body.location, body: body.body, - invitation_url: body.invitation_url, - end_datetime: body.endDatetime, + invitation_url: body.invitationUrl, + event_datetime: body.eventDatetime, }, { where: { @@ -198,7 +198,7 @@ router.get('/', async function(req, res, next) { where: {user_id: res.locals.user.id}, order: [ ['is_activated', 'DESC'], - ['end_datetime', 'DESC'], + ['event_datetime', 'DESC'], ], }, ); @@ -214,7 +214,7 @@ router.get('/', async function(req, res, next) { }], order: [ ['is_activated', 'DESC'], - ['end_datetime', 'DESC'], + ['event_datetime', 'DESC'], ], }); responseJson.result = code.SUCCESS; From ec5e8c8529c6698cc7c61631aada30a68cc0a405 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Tue, 1 Dec 2020 14:19:00 +0900 Subject: [PATCH 14/47] add nh api test.js, modify .gitignore --- .gitignore | 1 - test.js | 190 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 test.js diff --git a/.gitignore b/.gitignore index 125b84d..6568237 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,3 @@ node_modules .idea package-lock.json config/config.json -test.js diff --git a/test.js b/test.js new file mode 100644 index 0000000..3fe106f --- /dev/null +++ b/test.js @@ -0,0 +1,190 @@ +const request = require('request'); + +// 기관 고유 번호 +const iscd = '000504'; +const accessToken = '206782edebcb74e51aeb09292b444aa5926e87bcdc2220008e53209d84be0fab'; +// 농협 모계좌 +const nhAccount1 = '3020000002090'; +// 농협 자계좌 +const nhAccount2 = '3020000002092'; +// 상호 금융 계 +const shAccount1 = '3510000002091'; const shRgno1 = '20201130000000520'; +const shAccount2 = '3510000002093'; +const baseURL = 'https://developers.nonghyup.com/'; +const today = '20201130'; // 이건 무조건 오늘 날짜로 해야됨 +const birthday = '19960605'; +// 은행코드 011 농협, 012 농협상호금융 +const bncd = '012'; +// 등록 번호(이것이 있어야 핀어카운트 확인 가능) +const rgno = '20201128000000508'; +const rgno2 = '20201130000000519'; +// 기관 거래 고유 번호, 할 때마다 1씩 증가 시켜줘야함. +const isTuno = '0000023'; // timestamp + user_id +const finAcno = '00820100005040000000000000929'; const shFinAcno = '00820100005040000000000000992'; +const finAcno2 = '00820100005040000000000000983'; + +// request module 기본 요청 방식 +const options = { + url: baseURL, + qs: null, // for GET + body: null, // for POST + json: true, // json으로 보낼경우 true로 해주어야 header값이 json으로 설정된다. +}; + +// post api 공통부분 +const postBody = { + 'ApiNm': '', + 'Tsymd': today, // 오늘 날짜 + 'Trtm': '164011', // 요청 시간 + 'Iscd': iscd, + 'FintechApsno': '001', // 테스트용은 다 001 + 'ApiSvcCd': 'DrawingTransferA', + 'IsTuno': isTuno, + 'AccessToken': accessToken, +}; + +function makeOptions(apiNm, input) { + const ret = options; + ret.url = baseURL + apiNm + '.nh'; + ret.body = input; + ret.body.Header = postBody; + ret.body.Header.ApiNm = apiNm; + ret.url = baseURL + apiNm + '.nh'; + + return ret; +} + +// post request +function pr(opt) { + request.post(opt, function (err, httpResponse, body) { + if (err) { + console.log('ERROR\n', err); + return; + } + console.log(body); + }); +} + +// 핀어카운트 직접발급(핀어카운트 발급만 시키기, 보여주진 않음) +function openFinAccountDirect() { + const apiNm = 'OpenFinAccountDirect'; + const body = { + 'DrtrRgyn': 'Y', + 'BrdtBrno': birthday, + 'Bncd': bncd, + 'Acno': shAccount1, + }; + const ofadOpts = makeOptions(apiNm, body); + + // console.log(ofadOpts); + + pr(ofadOpts); + + // response + // Rgno : 등록번호, 이것을 이용해 핀어카운트를 확인할 수 있다. +} + +// 핀어카운트 직접발급 확인(핀어카운트 확인하기) +function checkOpenFinAccountDirect() { + const apiNm = 'CheckOpenFinAccountDirect'; + const body = { + 'Rgno': shRgno1, + 'BrdtBrno': birthday, + }; + const cofadOpts = makeOptions(apiNm, body); + + // console.log(cofadOpts); + + pr(cofadOpts); + + // response + // FinAcno : 핀어카운트 번호 + // RgsnYmd : 등록 일자 YYYYMMDD +} + +// 예금주 조회 +function inquireDepositorAccountNumber() { + const apiNm = 'InquireDepositorAccountNumber'; + const body = { + 'Bncd': bncd, + 'Acno': nhAccount1, + }; + const idanOpts = makeOptions(apiNm, body); + + console.log(idanOpts); + + pr(idanOpts); + + // response + // Bncd : 은행 코드 + // Acno : 계좌번호 + // Dpnm : 예금주명의 +} + +// 잔액 조회 +function inquireBalance() { + const apiNm = 'InquireBalance'; + const body = { + 'FinAcno': finAcno, + }; + const balanceOpts = makeOptions(apiNm, body); + + pr(balanceOpts); + + // 원장 잔액과 실지급가능액의 차이점 + // https://ko.bccrwp.org/compare/difference-between-ledger-balance-and-available-balance/ + // response + // FinAcno + // Ldbl : 원장 잔액 + // RlpmAbmant : 실 지급 가능액 + // 이하 AI001, AI002 오류 발생시 출력 + // AthrCnfrTckt : 권한 확인 티켓 + // Webrl : 웹 url + // AndInitUrl, AndAppUrl, AndWebUrl : 안드로이드 설치, 앱, 웹 url + // IosInitUrl, IosAppUrl, IosWebUrl : 아이오에스 설치, 앱, 웹 url +} + +// 출금이체 +function drawingTransfer() { + const apiNm = 'DrawingTransfer'; + const body = { + 'FinAcno': shFinAcno, + 'Tram': '100000000', + 'DractOtlt': '출금계좌에 적는 내용', + }; + const transferOpts = makeOptions(apiNm, body); + + pr(transferOpts); + + // response + // FinAcno : 핀어카운트 -> 문서에는 있는데 리턴은 안됨 + // RgsnYmd : 등록일자 +} + +// 입금이체 +function receivedTransferAccountNumber() { + const apiNm = 'ReceivedTransferAccountNumber'; + const body = { + 'Bncd': bncd, + 'Acno': nhAccount2, + 'Tram': '100000000', + 'DractOtlt': '출금계좌에 적는 내용', + 'MractOtlt': '입금계좌에 적는 내용', + }; + const receivedOpts = makeOptions(apiNm, body); + + pr(receivedOpts); + + // response + // 인자 없음 +} + +// test function +// openFinAccountDirect(); +// checkOpenFinAccountDirect(); +// inquireDepositorAccountNumber(); +// inquireBalance(); +// drawingTransfer(); +// receivedTransferAccountNumber(); + +// process : 하객 - 출금이체 - 정컴텍 - 예금주확인 - 입금 - 신랑신부 \ No newline at end of file From 838ab39928167f21ec13874f65e96cc7babdaf76 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Tue, 1 Dec 2020 16:18:27 +0900 Subject: [PATCH 15/47] add crypto module --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index feefeb3..9abf17b 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "bcrypt": "^5.0.0", "cookie-parser": "~1.4.4", "cors": "^2.8.5", + "crypto": "^1.0.1", "debug": "~2.6.9", "dotenv": "^8.2.0", "express": "^4.16.4", From 977b5065324d6b1f6ad5b1e491c707e2fc832301 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Tue, 1 Dec 2020 16:18:43 +0900 Subject: [PATCH 16/47] modify algorithm for event hash value --- routes/event.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/routes/event.js b/routes/event.js index 1821d55..fb3e824 100644 --- a/routes/event.js +++ b/routes/event.js @@ -1,6 +1,6 @@ const express = require('express'); const router = express.Router(); -const bcrypt = require('bcrypt'); +const crypto = require('crypto'); const {User, Event, EventAdmin, Guest} = require('../models'); const util = require('../utils'); const code = util.code; @@ -71,11 +71,10 @@ router.post('/', async function(req, res, next) { const body = req.body; try { const secretValue = Math.random().toString(36).slice(2) + res.locals.user.id + body.title; - const eventHash = bcrypt.hashSync(secretValue, util.saltRounds); - + const encrypt = crypto.createHash('sha256').update(secretValue).digest('hex'); const result = await Event.create( { - event_hash: eventHash, + event_hash: encrypt, user_id: res.locals.user.id, category: body.category, title: body.title, From a8be4324170049d8312255c48eae98772739b221 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Wed, 2 Dec 2020 12:52:37 +0900 Subject: [PATCH 17/47] event_hash -> allow null post/event.event_hash = null create qr code -> create event_hash --- models/event.js | 2 +- routes/event.js | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/models/event.js b/models/event.js index b818452..3e0232c 100644 --- a/models/event.js +++ b/models/event.js @@ -10,7 +10,7 @@ module.exports = (sequelize, DataTypes) => { event_hash: { type: DataTypes.STRING(100), unique: true, - allowNull: false, + allowNull: true, }, user_id: { type: DataTypes.INTEGER, diff --git a/routes/event.js b/routes/event.js index fb3e824..151aec2 100644 --- a/routes/event.js +++ b/routes/event.js @@ -70,11 +70,8 @@ router.post('/', async function(req, res, next) { const responseJson = {}; const body = req.body; try { - const secretValue = Math.random().toString(36).slice(2) + res.locals.user.id + body.title; - const encrypt = crypto.createHash('sha256').update(secretValue).digest('hex'); const result = await Event.create( { - event_hash: encrypt, user_id: res.locals.user.id, category: body.category, title: body.title, From 4dd871602ac541f1ba4b0e57ccaebe9ac47b5a25 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 3 Dec 2020 00:17:37 +0900 Subject: [PATCH 18/47] implement finAccount and transfer --- app.js | 20 +++- config/config.json.sample | 28 +++-- models/breakdown.js | 38 +++++++ models/index.js | 3 +- package.json | 2 +- routes/event.js | 15 --- routes/fin.js | 232 ++++++++++++++++++++++++++++++++++++++ utils.js | 2 + 8 files changed, 313 insertions(+), 27 deletions(-) create mode 100644 models/breakdown.js create mode 100644 routes/fin.js diff --git a/app.js b/app.js index 0135041..32a71e6 100644 --- a/app.js +++ b/app.js @@ -5,6 +5,7 @@ const cookieParser = require('cookie-parser'); const logger = require('morgan'); const session = require('express-session'); const sequelize = require('./models').sequelize; +const util = require('./utils'); const indexRouter = require('./routes/index'); const authRouter = require('./routes/auth'); @@ -13,6 +14,8 @@ const usersRouter = require('./routes/users'); // TODO: not use yet // const breakdownRouter = require('./routes/breakdown'); const eventRouter = require('./routes/event'); +const finRouter = require('./routes/fin'); + // const guestRouter = require('./routes/guest'); // const organizerRouter = require('./routes/organizer'); @@ -47,8 +50,23 @@ app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); app.use('/auth', authRouter); app.use('/users', usersRouter); -// app.use('/breakdown', breakdownRouter); + +//auth check +app.use('/*', function(req, res, next) { + if(req.method === 'options') { + return next(); + } + const result = util.getUser(req); + if(result.user === undefined) { + res.status(401).json('no auth'); + return; + } + res.locals.user = result.user; + next(); +}); app.use('/event', eventRouter); +app.use('/fin', finRouter); +// app.use('/breakdown', breakdownRouter); // app.use('/guest', guestRouter); // app.use('/organizer', organizerRouter); diff --git a/config/config.json.sample b/config/config.json.sample index fb1ab4f..5ed7c5d 100644 --- a/config/config.json.sample +++ b/config/config.json.sample @@ -1,12 +1,22 @@ { - "development": { - "username": "root", - "password": "1234", - "database": "nh_db", - "host": "127.0.0.1", - "dialect": "mysql", - "operatorAliases" : false, - "logging": false, - "jwtSecret": "insert jwt secret key" + "development": { + "dbOptions": { + "username": "root", + "password": "1234", + "database": "nh_db", + "host": "127.0.0.1", + "dialect": "mysql", + "operatorAliases" : false, + "dialectOptions": { + "dateStrings": true, + "typeCast": true + }, + "timezone": "+09:00", + "logging": false + }, + "jwtSecret": "insert jwt secret key", + "iscd": "기관코드", + "accessToken": "액세스 토큰", + "BrdtBrno": "생년월일 or 사업자번호" } } diff --git a/models/breakdown.js b/models/breakdown.js new file mode 100644 index 0000000..a704136 --- /dev/null +++ b/models/breakdown.js @@ -0,0 +1,38 @@ +module.exports = (sequelize, DataTypes) => { + return sequelize.define('breakdown', { + id: { + type: DataTypes.INTEGER, + allowNull: false, + unique: true, + autoIncrement: true, + primaryKey: true, + }, + event_id: { + type: DataTypes.INTEGER, + allowNull: false, + }, + sender_id : { + type: DataTypes.INTEGER, + allowNull: false, + }, + transfer_datetime : { + type: DataTypes.DATE, + allowNull: false, + }, + message: { + type: DataTypes.STRING(45), + allowNull: true, + }, + money: { + type: DataTypes.INTEGER, + allowNull: false, + }, + is_direct_input: { + type: DataTypes.BOOLEAN, + allowNull: false, + }, + }, + { + timestamps: false, + }); +}; diff --git a/models/index.js b/models/index.js index bea73a9..7043925 100644 --- a/models/index.js +++ b/models/index.js @@ -1,7 +1,7 @@ const path = require('path'); const Sequelize = require('sequelize'); const env = process.env.NODE_ENV || 'development'; -const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env]; +const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env]['dbOptions']; const db = {}; @@ -13,6 +13,7 @@ db.User = require('./user')(sequelize, Sequelize); db.Event = require('./event')(sequelize, Sequelize); db.EventAdmin = require('./eventadmin')(sequelize, Sequelize); db.Guest = require('./guest')(sequelize, Sequelize); +db.BreakDown = require('./breakdown')(sequelize, Sequelize); db.Event.hasMany(db.Guest, {foreignKey: {name: 'event_id'}}); module.exports = db; diff --git a/package.json b/package.json index feefeb3..fec2b2f 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "dev-node": "node ./bin/www" }, "dependencies": { + "axios": "^0.21.0", "bcrypt": "^5.0.0", "cookie-parser": "~1.4.4", "cors": "^2.8.5", @@ -19,7 +20,6 @@ "morgan": "~1.9.1", "mysql2": "^2.2.5", "nodemon": "^2.0.6", - "request": "^2.88.2", "sequelize": "^6.3.5" }, "devDependencies": { diff --git a/routes/event.js b/routes/event.js index 1821d55..27e6acb 100644 --- a/routes/event.js +++ b/routes/event.js @@ -20,21 +20,6 @@ guestCheck = async function(userId, eventId) { return check !== null; }; -// TO-DO : Solve Option Problem -router.options('/*', function(req, res) { - return res.send({}); -}); - -router.all('/*', function(req, res, next) { - const result = util.getUser(req); - if(result.user === undefined) { - res.status(401).json('no auth'); - return; - } - res.locals.user = result.user; - next(); -}); - // post1 : check phonenubmer router.post('/', async function(req, res, next) { const responseJson = {}; diff --git a/routes/fin.js b/routes/fin.js new file mode 100644 index 0000000..2d25f89 --- /dev/null +++ b/routes/fin.js @@ -0,0 +1,232 @@ +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const env = process.env.NODE_ENV || 'development'; +const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env]; +const moment = require('moment'); +const axios = require('axios'); + +const {User, Event, BreakDown} = require('../models'); +const util = require('../utils'); +const code = util.code; + + +createBodyHeader = function(apiNm, userId) { + const time = moment().format('YYYYMMDD-HHmmss'); + const tsymd = time.substring(0,8); + const trtm = time.substring(9,15); + const ut = Math.floor(new Date().getTime() / 1000); + const isTuno = ut + userId.toString(); + + const postBodyHeader = { + 'Iscd': config.iscd, + 'FintechApsno': '001', // 테스트용 고정 + 'ApiSvcCd': 'DrawingTransferA', //테스트용 고정 + 'AccessToken': config.accessToken, + }; + + postBodyHeader.ApiNm = apiNm; //API 명 + postBodyHeader.Tsymd= tsymd; //전송일자 + postBodyHeader.Trtm =trtm; //전송시각 + postBodyHeader.IsTuno=isTuno; //기관거래고유번호 + return postBodyHeader; +} + +getNHURL = function(apiNm) { + return 'https://developers.nonghyup.com/' + apiNm + '.nh'; +} + +//NH API OpenFinAccountDirect +router.post('/', async function(req, res, next) { + const responseJson= {}; + try { + const userId = res.locals.user.id; + const apiNm = 'OpenFinAccountDirect'; + const body= { + "DrtrRgyn": "Y", + "BrdtBrno": config.BrdtBrno, + "Bncd": req.body.bncd, + "Acno": req.body.acno + } + body.Header= createBodyHeader(apiNm, userId); + const result = await axios.post(getNHURL(apiNm), body); + if(result.data.Header.Rpcd !== '00000'){ + responseJson.result = code.NH_API_ERROR; + responseJson.detail = result.data.Header.Rsms; + res.json(responseJson); + } + else { + res.locals.Rgno=result.data.Rgno; + next(); + } + } + catch (error) { + responseJson.result = code.NH_API_ERROR; + responseJson.detail = 'nh api( OpenFinAccountDirect ) error'; + res.json(responseJson); + } +}); +//NH API CheckOpenFinAccountDirect +router.post('/', async function(req, res, next) { + const responseJson= {}; + try { + const userId = res.locals.user.id; + const rgno = res.locals.Rgno; + + const apiNm = 'CheckOpenFinAccountDirect' + const body = { + "Rgno": rgno, + "BrdtBrno":config.BrdtBrno + } + body.Header= createBodyHeader(apiNm, userId); + const result = await axios.post(getNHURL(apiNm), body); + if(result.data.Header.Rpcd !== '00000'){ + responseJson.result = code.NH_API_ERROR; + responseJson.detail = reult.data.Header.Rsms; + res.json(responseJson); + } + else { + res.locals.FinAcno = result.data.FinAcno; + next(); + } + } + catch (error) { + responseJson.result = code.NH_API_ERROR; + responseJson.detail = 'nh api (CheckOpenFinAccountDirect) error'; + next(error); + } +}); + +//user table update +router.post('/', async function(req, res, next) { + const responseJson= {}; + try { + const userId = res.locals.user.id; + const finAcno = res.locals.FinAcno; + + const result = await User.update( + { + fin_account: finAcno + }, + { + where: { + id: userId, + } + }); + responseJson.result= code.SUCCESS + responseJson.detail= 'finaccount create success' + res.json(responseJson); + } + catch (error) { + responseJson.result = code.DB_ERROR; + responseJson.detail = 'user table update error'; + res.json(responseJson); + next(error); + } +}); + + +router.post('/transfer', async function(req, res, next) { + const responseJson= {}; + const {event_hash} = req.body; + try { + //get event id from db + const result = await Event.findOne( + {attributes: ['id'], where: {event_hash: event_hash}}, + ); + + if(result === null) { + responseJson.result = code.NO_DATA; + responseJson.detail = "not valid event hash"; + res.json(responseJson); + return; + } + res.locals.eventId = result.dataValues.id; + //get finAcno + const userId = res.locals.user.id; + const result2 = await User.findOne( + {attributes: ['fin_account'], where: {id: userId}}, + ); + + if(result2 === null) { + responseJson.result = code.NO_DATA; + responseJson.detail = "not register fin account"; + res.json(responseJson); + return; + } + res.locals.finAccount = result2.dataValues.fin_account; + next(); + } + catch (error) { + responseJson.result = code.DB_ERROR; + responseJson.detail = 'transfer DB find error'; + res.json(responseJson); + } +}); +//use nh api DrawingTransfer +router.post('/transfer', async function(req, res, next) { + const responseJson= {}; + const {tram} = req.body; + try { + + const userId = res.locals.user.id; + const apiNm = 'DrawingTransfer'; + const body= { + "FinAcno": res.locals.finAccount, + "Tram": tram, + "DractOtlt": "부조금 출금" + } + + body.Header= createBodyHeader(apiNm, userId); + const result = await axios.post(getNHURL(apiNm), body); + if(result.data.Header.Rpcd !== '00000'){ + responseJson.result = code.NH_API_ERROR; + responseJson.detail = result.data.Header.Rsms; + res.json(responseJson); + } + const time = result.data.Header.Tsymd + result.data.Header.Trtm; + res.locals.transferTime = time.replace( + /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, + "$1-$2-$3 $4:$5:$6"); + next(); + } + catch (error) { + responseJson.result = code.NH_API_ERROR; + responseJson.detail = 'nh api( DrawingTransfer ) error'; + res.json(responseJson); + } +}); +//Breakdown db insert +router.post('/transfer', async function(req, res, next) { + const responseJson= {}; + let {tram, message} = req.body; + const userId = res.locals.user.id; + const transferTime= res.locals.transferTime; + const eventId = res.locals.eventId; + //message error avoid + if(message.length > 45) { + message = message.substring(0,45); + } + const data = { + event_id: eventId, + sender_id: userId, + transfer_datetime: transferTime, + message: message, + money: tram, + is_direct_input: false + } + + try { + const result = await BreakDown.create(data); + responseJson.result = code.SUCCESS; + responseJson.detail = 'transfer success'; + res.json(responseJson); + } + catch (error) { + responseJson.result = code.DB_ERROR; + responseJson.detail = 'transfer db insert error'; + responseJson.data = data; + res.json(responseJson); + } +}); +module.exports = router; \ No newline at end of file diff --git a/utils.js b/utils.js index 1414283..7588dbc 100644 --- a/utils.js +++ b/utils.js @@ -17,6 +17,8 @@ value.code = { 'NO_DATA': 8, 'INVALID_QUERY': 9, 'NO_AUTH': 10, + 'NH_API_ERROR': 11, + 'DB_ERROR': 12, }; value.phoneNumberCheck = function (phone) { From 0fd5ba87ddc547156258bf4ddeb3b95e4e953c30 Mon Sep 17 00:00:00 2001 From: hyunjun Date: Thu, 3 Dec 2020 15:40:25 +0900 Subject: [PATCH 19/47] resolve khs review --- models/breakdown.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/models/breakdown.js b/models/breakdown.js index a704136..58c8b9d 100644 --- a/models/breakdown.js +++ b/models/breakdown.js @@ -22,6 +22,7 @@ module.exports = (sequelize, DataTypes) => { message: { type: DataTypes.STRING(45), allowNull: true, + defaultValue: null }, money: { type: DataTypes.INTEGER, @@ -30,6 +31,7 @@ module.exports = (sequelize, DataTypes) => { is_direct_input: { type: DataTypes.BOOLEAN, allowNull: false, + defaultValue: false }, }, { From 2a7853a70a68e875dd4fec3af16078ea250e6fd6 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Thu, 3 Dec 2020 16:36:51 +0900 Subject: [PATCH 20/47] test for fcm --- .gitignore | 2 ++ package.json | 1 + 2 files changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 6568237..bba6876 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ node_modules .idea package-lock.json config/config.json +fcm.js +serviceAccountKey.json \ No newline at end of file diff --git a/package.json b/package.json index feefeb3..f4b44c6 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "dotenv": "^8.2.0", "express": "^4.16.4", "express-session": "^1.17.1", + "firebase-admin": "^9.4.1", "http-errors": "^1.8.0", "jsonwebtoken": "^8.5.1", "morgan": "~1.9.1", From 41ab81af88bc18d50d3683527f287c54f740d050 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Thu, 3 Dec 2020 16:37:11 +0900 Subject: [PATCH 21/47] event_hash allow null, update event_hash after create event --- models/event.js | 2 +- routes/event.js | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/models/event.js b/models/event.js index b818452..3e0232c 100644 --- a/models/event.js +++ b/models/event.js @@ -10,7 +10,7 @@ module.exports = (sequelize, DataTypes) => { event_hash: { type: DataTypes.STRING(100), unique: true, - allowNull: false, + allowNull: true, }, user_id: { type: DataTypes.INTEGER, diff --git a/routes/event.js b/routes/event.js index 1821d55..513e302 100644 --- a/routes/event.js +++ b/routes/event.js @@ -1,6 +1,6 @@ const express = require('express'); const router = express.Router(); -const bcrypt = require('bcrypt'); +const crypto = require('crypto'); const {User, Event, EventAdmin, Guest} = require('../models'); const util = require('../utils'); const code = util.code; @@ -70,12 +70,8 @@ router.post('/', async function(req, res, next) { const responseJson = {}; const body = req.body; try { - const secretValue = Math.random().toString(36).slice(2) + res.locals.user.id + body.title; - const eventHash = bcrypt.hashSync(secretValue, util.saltRounds); - const result = await Event.create( { - event_hash: eventHash, user_id: res.locals.user.id, category: body.category, title: body.title, @@ -91,6 +87,18 @@ router.post('/', async function(req, res, next) { for(let i = 0; i < res.locals.admins.length; i++) { res.locals.admins[i].event_id = eventId; } + + const encrypt = crypto.createHash('sha256').update(eventId + ' ').digest('hex'); + + const updateResult = await Event.update( + { + event_hash: encrypt, + }, + { + where: { + id: eventId, + }}, + ); next(); } catch(exception) { From 75dc431c2aa395030815dd1c44de06a3d0a10502 Mon Sep 17 00:00:00 2001 From: jaypae95 Date: Wed, 2 Dec 2020 23:40:58 -0800 Subject: [PATCH 22/47] modified options string --- app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app.js b/app.js index 32a71e6..9d2a7c5 100644 --- a/app.js +++ b/app.js @@ -53,7 +53,7 @@ app.use('/users', usersRouter); //auth check app.use('/*', function(req, res, next) { - if(req.method === 'options') { + if(req.method === 'OPTIONS') { return next(); } const result = util.getUser(req); From 48da32ea0226057fbe39fc2b0254c384101eb9b9 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Fri, 4 Dec 2020 11:05:51 +0900 Subject: [PATCH 23/47] add user.firebase_token column size 200 for fire base token --- models/user.js | 5 +++++ routes/users.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/models/user.js b/models/user.js index cabcbe2..4e645d7 100644 --- a/models/user.js +++ b/models/user.js @@ -30,6 +30,11 @@ module.exports = (sequelize, DataTypes) => { allowNull: true, unique: true, }, + firebase_token: { + type: DataTypes.STRING(200), + allowNull: true, + unique: true, + }, }, { timestamps: false, diff --git a/routes/users.js b/routes/users.js index f4bfb25..eba67c1 100644 --- a/routes/users.js +++ b/routes/users.js @@ -96,4 +96,33 @@ router.post('/signup', async function(req, res, next) { } }); +router.put('/:id/token', async function(req, res, next) { + const responseJson = {}; + try { + const token = req.body.token; + console.dir(req.body); + const result = User.update( + { + firebase_token: token, + }, + { + where: { + id: req.params.id, + }, + }, + ); + + responseJson.result = code.SUCCESS; + responseJson.detail = 'update firebase token success'; + responseJson.data = result; + } + catch(exception) { + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'unknown error'; + } + finally { + res.json(responseJson); + } +}); + module.exports = router; From 2c3f4811d006caed59d72e5f40d9f52875627925 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Fri, 4 Dec 2020 17:49:18 +0900 Subject: [PATCH 24/47] eslint --- app.js | 2 +- models/breakdown.js | 8 ++-- routes/fin.js | 89 ++++++++++++++++++++++----------------------- 3 files changed, 49 insertions(+), 50 deletions(-) diff --git a/app.js b/app.js index 9d2a7c5..fbf994e 100644 --- a/app.js +++ b/app.js @@ -51,7 +51,7 @@ app.use('/', indexRouter); app.use('/auth', authRouter); app.use('/users', usersRouter); -//auth check +// auth check app.use('/*', function(req, res, next) { if(req.method === 'OPTIONS') { return next(); diff --git a/models/breakdown.js b/models/breakdown.js index 58c8b9d..775fae9 100644 --- a/models/breakdown.js +++ b/models/breakdown.js @@ -11,18 +11,18 @@ module.exports = (sequelize, DataTypes) => { type: DataTypes.INTEGER, allowNull: false, }, - sender_id : { + sender_id: { type: DataTypes.INTEGER, allowNull: false, }, - transfer_datetime : { + transfer_datetime: { type: DataTypes.DATE, allowNull: false, }, message: { type: DataTypes.STRING(45), allowNull: true, - defaultValue: null + defaultValue: null, }, money: { type: DataTypes.INTEGER, @@ -31,7 +31,7 @@ module.exports = (sequelize, DataTypes) => { is_direct_input: { type: DataTypes.BOOLEAN, allowNull: false, - defaultValue: false + defaultValue: false, }, }, { diff --git a/routes/fin.js b/routes/fin.js index 2d25f89..3bb29eb 100644 --- a/routes/fin.js +++ b/routes/fin.js @@ -13,44 +13,44 @@ const code = util.code; createBodyHeader = function(apiNm, userId) { const time = moment().format('YYYYMMDD-HHmmss'); - const tsymd = time.substring(0,8); - const trtm = time.substring(9,15); + const tsymd = time.substring(0, 8); + const trtm = time.substring(9, 15); const ut = Math.floor(new Date().getTime() / 1000); const isTuno = ut + userId.toString(); const postBodyHeader = { 'Iscd': config.iscd, 'FintechApsno': '001', // 테스트용 고정 - 'ApiSvcCd': 'DrawingTransferA', //테스트용 고정 + 'ApiSvcCd': 'DrawingTransferA', // 테스트용 고정 'AccessToken': config.accessToken, }; - postBodyHeader.ApiNm = apiNm; //API 명 - postBodyHeader.Tsymd= tsymd; //전송일자 - postBodyHeader.Trtm =trtm; //전송시각 - postBodyHeader.IsTuno=isTuno; //기관거래고유번호 + postBodyHeader.ApiNm = apiNm; // API 명 + postBodyHeader.Tsymd= tsymd; // 전송일자 + postBodyHeader.Trtm =trtm; // 전송시각 + postBodyHeader.IsTuno=isTuno; // 기관거래고유번호 return postBodyHeader; -} +}; getNHURL = function(apiNm) { return 'https://developers.nonghyup.com/' + apiNm + '.nh'; -} +}; -//NH API OpenFinAccountDirect +// NH API OpenFinAccountDirect router.post('/', async function(req, res, next) { const responseJson= {}; try { const userId = res.locals.user.id; const apiNm = 'OpenFinAccountDirect'; const body= { - "DrtrRgyn": "Y", - "BrdtBrno": config.BrdtBrno, - "Bncd": req.body.bncd, - "Acno": req.body.acno - } + 'DrtrRgyn': 'Y', + 'BrdtBrno': config.BrdtBrno, + 'Bncd': req.body.bncd, + 'Acno': req.body.acno, + }; body.Header= createBodyHeader(apiNm, userId); const result = await axios.post(getNHURL(apiNm), body); - if(result.data.Header.Rpcd !== '00000'){ + if(result.data.Header.Rpcd !== '00000') { responseJson.result = code.NH_API_ERROR; responseJson.detail = result.data.Header.Rsms; res.json(responseJson); @@ -66,21 +66,21 @@ router.post('/', async function(req, res, next) { res.json(responseJson); } }); -//NH API CheckOpenFinAccountDirect +// NH API CheckOpenFinAccountDirect router.post('/', async function(req, res, next) { const responseJson= {}; try { const userId = res.locals.user.id; const rgno = res.locals.Rgno; - const apiNm = 'CheckOpenFinAccountDirect' + const apiNm = 'CheckOpenFinAccountDirect'; const body = { - "Rgno": rgno, - "BrdtBrno":config.BrdtBrno - } + 'Rgno': rgno, + 'BrdtBrno': config.BrdtBrno, + }; body.Header= createBodyHeader(apiNm, userId); const result = await axios.post(getNHURL(apiNm), body); - if(result.data.Header.Rpcd !== '00000'){ + if(result.data.Header.Rpcd !== '00000') { responseJson.result = code.NH_API_ERROR; responseJson.detail = reult.data.Header.Rsms; res.json(responseJson); @@ -97,7 +97,7 @@ router.post('/', async function(req, res, next) { } }); -//user table update +// user table update router.post('/', async function(req, res, next) { const responseJson= {}; try { @@ -106,15 +106,15 @@ router.post('/', async function(req, res, next) { const result = await User.update( { - fin_account: finAcno + fin_account: finAcno, }, { where: { id: userId, - } - }); - responseJson.result= code.SUCCESS - responseJson.detail= 'finaccount create success' + }, + }); + responseJson.result= code.SUCCESS; + responseJson.detail= 'finaccount create success'; res.json(responseJson); } catch (error) { @@ -130,19 +130,19 @@ router.post('/transfer', async function(req, res, next) { const responseJson= {}; const {event_hash} = req.body; try { - //get event id from db + // get event id from db const result = await Event.findOne( {attributes: ['id'], where: {event_hash: event_hash}}, ); if(result === null) { responseJson.result = code.NO_DATA; - responseJson.detail = "not valid event hash"; + responseJson.detail = 'not valid event hash'; res.json(responseJson); return; } res.locals.eventId = result.dataValues.id; - //get finAcno + // get finAcno const userId = res.locals.user.id; const result2 = await User.findOne( {attributes: ['fin_account'], where: {id: userId}}, @@ -150,7 +150,7 @@ router.post('/transfer', async function(req, res, next) { if(result2 === null) { responseJson.result = code.NO_DATA; - responseJson.detail = "not register fin account"; + responseJson.detail = 'not register fin account'; res.json(responseJson); return; } @@ -163,23 +163,22 @@ router.post('/transfer', async function(req, res, next) { res.json(responseJson); } }); -//use nh api DrawingTransfer +// use nh api DrawingTransfer router.post('/transfer', async function(req, res, next) { const responseJson= {}; const {tram} = req.body; try { - const userId = res.locals.user.id; const apiNm = 'DrawingTransfer'; const body= { - "FinAcno": res.locals.finAccount, - "Tram": tram, - "DractOtlt": "부조금 출금" - } + 'FinAcno': res.locals.finAccount, + 'Tram': tram, + 'DractOtlt': '부조금 출금', + }; body.Header= createBodyHeader(apiNm, userId); const result = await axios.post(getNHURL(apiNm), body); - if(result.data.Header.Rpcd !== '00000'){ + if(result.data.Header.Rpcd !== '00000') { responseJson.result = code.NH_API_ERROR; responseJson.detail = result.data.Header.Rsms; res.json(responseJson); @@ -187,7 +186,7 @@ router.post('/transfer', async function(req, res, next) { const time = result.data.Header.Tsymd + result.data.Header.Trtm; res.locals.transferTime = time.replace( /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, - "$1-$2-$3 $4:$5:$6"); + '$1-$2-$3 $4:$5:$6'); next(); } catch (error) { @@ -196,16 +195,16 @@ router.post('/transfer', async function(req, res, next) { res.json(responseJson); } }); -//Breakdown db insert +// Breakdown db insert router.post('/transfer', async function(req, res, next) { const responseJson= {}; let {tram, message} = req.body; const userId = res.locals.user.id; const transferTime= res.locals.transferTime; const eventId = res.locals.eventId; - //message error avoid + // message error avoid if(message.length > 45) { - message = message.substring(0,45); + message = message.substring(0, 45); } const data = { event_id: eventId, @@ -213,8 +212,8 @@ router.post('/transfer', async function(req, res, next) { transfer_datetime: transferTime, message: message, money: tram, - is_direct_input: false - } + is_direct_input: false, + }; try { const result = await BreakDown.create(data); From 2e3dc60f1c798e8a120678099b79b48d74a47d45 Mon Sep 17 00:00:00 2001 From: hyunjun Date: Sat, 5 Dec 2020 15:10:44 +0900 Subject: [PATCH 25/47] =?UTF-8?q?=EC=88=98=EC=A0=95=20=ED=95=84=EC=9A=94?= =?UTF-8?q?=ED=95=9C=20=EB=AA=A9=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/index.js | 1 + routes/event.js | 51 +++++++++++++++++++++++++++++++++++++++++-------- routes/fin.js | 1 + 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/models/index.js b/models/index.js index 7043925..b1dc901 100644 --- a/models/index.js +++ b/models/index.js @@ -16,4 +16,5 @@ db.Guest = require('./guest')(sequelize, Sequelize); db.BreakDown = require('./breakdown')(sequelize, Sequelize); db.Event.hasMany(db.Guest, {foreignKey: {name: 'event_id'}}); +db.Event.hasMany(db.EventAdmin, {foreignKey: {name: 'event_id'}}); module.exports = db; diff --git a/routes/event.js b/routes/event.js index 61dceaf..3672248 100644 --- a/routes/event.js +++ b/routes/event.js @@ -20,6 +20,13 @@ guestCheck = async function(userId, eventId) { return check !== null; }; +adminCheck = async function(userId, eventId) { + const check = await EventAdmin.findOne({ + where: {user_id: userId, event_id: eventId}, + }); + return check !== null; +}; + // post1 : check phonenubmer router.post('/', async function(req, res, next) { const responseJson = {}; @@ -72,9 +79,8 @@ router.post('/', async function(req, res, next) { for(let i = 0; i < res.locals.admins.length; i++) { res.locals.admins[i].event_id = eventId; } - const encrypt = crypto.createHash('sha256').update(eventId + ' ').digest('hex'); - + const updateResult = await Event.update( { event_hash: encrypt, @@ -186,7 +192,7 @@ router.get('/', async function(req, res, next) { responseJson.detail = 'params error'; } else if(isHost === 'true') { - const result = await Event.findAll( + const result1 = await Event.findAll( { where: {user_id: res.locals.user.id}, order: [ @@ -195,6 +201,39 @@ router.get('/', async function(req, res, next) { ], }, ); + const result2 = await Event.findAll({ + include: [{ + model: EventAdmin, + where: {user_id: res.locals.user.id} + }], + order: [ + ['is_activated', 'DESC'], + ['event_datetime', 'DESC'], + ], + }); + const result=[]; + for(let i = 0; i < result1.length; i++) { + result.push(result1[i].dataValues); + } + for(let i = 0; i < result2.length; i++) { + result.push(result2[i].dataValues); + } + result.sort(function(a,b) { + if(a.is_activated >= b.is_activated) { + if(a.event_datetime > b.event_datetime) { + return -1; + } + else if(a.event_datetime === b.event_datetime) { + return 0; + } + else { + return 1; + } + } + else { + return 1; + } + }) responseJson.result = code.SUCCESS; responseJson.detail = 'success'; responseJson.data = result; @@ -240,11 +279,7 @@ router.get('/:id', async function(req, res, next) { } else { let haveAuth = result.dataValues.user_id === myId; - if(!haveAuth) { - if(await guestCheck(myId, eventId)) { - haveAuth = true; - } - } + haveAuth = haveAuth || await adminCheck(myId, eventId) || await guestCheck(myId, eventId); if(haveAuth) { const data = result.dataValues; const result2 = await EventAdmin.findAll( diff --git a/routes/fin.js b/routes/fin.js index 3bb29eb..61a0ce5 100644 --- a/routes/fin.js +++ b/routes/fin.js @@ -219,6 +219,7 @@ router.post('/transfer', async function(req, res, next) { const result = await BreakDown.create(data); responseJson.result = code.SUCCESS; responseJson.detail = 'transfer success'; + responseJson.data = { event_id: eventId}; res.json(responseJson); } catch (error) { From 8cacab076966b95322ac5466085a603096a89507 Mon Sep 17 00:00:00 2001 From: hyunjun Date: Sun, 6 Dec 2020 21:19:39 +0900 Subject: [PATCH 26/47] implement event invite --- routes/event.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/routes/event.js b/routes/event.js index 3672248..337f8c7 100644 --- a/routes/event.js +++ b/routes/event.js @@ -309,8 +309,6 @@ router.get('/:id', async function(req, res, next) { } }); - - // event close router.put('/close/:id', async function(req, res, next) { const responseJson = {}; @@ -346,4 +344,51 @@ router.put('/close/:id', async function(req, res, next) { } }); +router.get('/invite/:hash', async function(req, res, next) { + const responseJson = {}; + const myId = res.locals.user.id; + try { + const hostId = req.query.hostId; + const hash = req.params.hash; + + const result = await Event.findOne({ + attributes: ['id'], + where: {event_hash: hash} + }); + const eventId = result.dataValues.id; + + if (result === null) { + responseJson.result = code.NO_DATA; + responseJson.detail = 'cannot find event_hash'; + } + else { + const hostCheck = await masterCheck(hostId, eventId) || await adminCheck(hostId, eventId); + if(hostCheck) { + const result2 = await Guest.create( + { + user_id: myId, + event_id: eventId, + eventAdmin_id: hostId + }, + ); + responseJson.result = code.SUCCESS; + responseJson.detail = 'success'; + responseJson.data = {event_id : eventId}; + } + else { + responseJson.result = code.NO_AUTH; + responseJson.detail = 'no_auth : hostId is not valid'; + } + } + } + catch(exception) { + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'unknown error'; + console.log(exception); + } + finally { + res.json(responseJson); + } +}); + module.exports = router; From 15adec586eba29c3e9332e9f0d21fc9b8f9bd8cc Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 7 Dec 2020 09:25:19 +0900 Subject: [PATCH 27/47] =?UTF-8?q?=EC=B6=9C=EA=B8=88=ED=95=98=EA=B8=B0(?= =?UTF-8?q?=EC=B6=9C=EA=B8=88=ED=95=9C=EA=B1=B0=20=ED=91=9C=EC=8B=9C?= =?UTF-8?q?=EB=A5=BC=20=EC=96=B4=EB=94=94=EC=97=90=EB=8B=A4=EA=B0=80=3F)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- routes/fin.js | 98 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 93 insertions(+), 5 deletions(-) diff --git a/routes/fin.js b/routes/fin.js index 3bb29eb..5ceb0a8 100644 --- a/routes/fin.js +++ b/routes/fin.js @@ -5,6 +5,7 @@ const env = process.env.NODE_ENV || 'development'; const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env]; const moment = require('moment'); const axios = require('axios'); +const sequelize = require('sequelize'); const {User, Event, BreakDown} = require('../models'); const util = require('../utils'); @@ -76,7 +77,7 @@ router.post('/', async function(req, res, next) { const apiNm = 'CheckOpenFinAccountDirect'; const body = { 'Rgno': rgno, - 'BrdtBrno': config.BrdtBrno, + 'BrdtBrno': config.BrdtBrno, }; body.Header= createBodyHeader(apiNm, userId); const result = await axios.post(getNHURL(apiNm), body); @@ -155,7 +156,7 @@ router.post('/transfer', async function(req, res, next) { return; } res.locals.finAccount = result2.dataValues.fin_account; - next(); + next(); } catch (error) { responseJson.result = code.DB_ERROR; @@ -175,8 +176,8 @@ router.post('/transfer', async function(req, res, next) { 'Tram': tram, 'DractOtlt': '부조금 출금', }; - - body.Header= createBodyHeader(apiNm, userId); + + body.Header= createBodyHeader(apiNm, userId); const result = await axios.post(getNHURL(apiNm), body); if(result.data.Header.Rpcd !== '00000') { responseJson.result = code.NH_API_ERROR; @@ -228,4 +229,91 @@ router.post('/transfer', async function(req, res, next) { res.json(responseJson); } }); -module.exports = router; \ No newline at end of file + +// check event hash +router.post('/receive', async function(req, res, next) { + const responseJson = {}; + const {event_hash} = req.body; + + try { + const result = await Event.findOne( + { + where: { + event_hash: event_hash, + }, + }, + ); + + if(result == null) { + responseJson.result = code.NO_DATA; + responseJson.detail = 'not valid event hash'; + res.json(responseJson); + return; + } + + if(result.dataValues.user_id !== res.locals.user.id) { + responseJson.result = code.NO_AUTH; + responseJson.detail = 'no auth'; + res.json(responseJson); + return; + } + + res.locals.eventId = result.dataValues.id; + res.locals.title = result.dataValues.title; + next(); + } + catch(exception) { + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'Unknown Error'; + res.json(responseJson); + } +}); + +// nh api +router.post('/receive', async function(req, res, next) { + const responseJson = {}; + const {bncd, acno} = req.body; + + try { + const result = await BreakDown.findAll( + { + attributes: [ + 'event_id', + [sequelize.fn('sum', sequelize.col('money')), 'totalMoney'], + ], + group: ['event_id'], + }, + { + where: { + event_id: res.locals.eventId, + is_direct_input: false, + }, + }, + ); + const tram = result[0].dataValues.totalMoney; + + const apiNm = 'ReceivedTransferAccountNumber'; + const body = { + 'Bncd': bncd, + 'Acno': acno, + 'Tram': tram, + 'DractOtlt': res.locals.title + ' 정산금', + 'MractOtlt': res.locals.title + ' 정산금', + }; + + body.Header = createBodyHeader(apiNm, res.locals.user.id); + + const nhResult = await axios.post(getNHURL(apiNm), body); + responseJson.result = code.SUCCESS; + responseJson.detail = 'receive success'; + } + catch(exception) { + responseJson.result = code.NH_API_ERROR; + responseJson.detail = 'nh api( ReceivedTransferAccountNumber ) error'; + } + finally { + res.json(responseJson); + } +}); + +module.exports = router; From a8c4b11a78aa71c3bdf2c2930b0b40430a682f3f Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 7 Dec 2020 09:26:26 +0900 Subject: [PATCH 28/47] =?UTF-8?q?=EB=82=B4=EC=97=AD=EC=A1=B0=ED=9A=8C(?= =?UTF-8?q?=EB=82=B4=EA=B0=80=20=EB=B3=B4=EB=83=88=EB=8D=98=EA=B1=B0,=20?= =?UTF-8?q?=EB=B0=9B=EC=95=98=EB=8D=98=EA=B1=B0,=20=EC=88=98=EA=B8=B0=20?= =?UTF-8?q?=EC=9E=85=EB=A0=A5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- routes/breakdown.js | 178 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 177 insertions(+), 1 deletion(-) diff --git a/routes/breakdown.js b/routes/breakdown.js index 935c3d3..73c7402 100644 --- a/routes/breakdown.js +++ b/routes/breakdown.js @@ -1,4 +1,180 @@ const express = require('express'); const router = express.Router(); +const moment = require('moment'); -module.exports = router; \ No newline at end of file +const {BreakDown, User, Event} = require('../models'); +const util = require('../utils'); +const code = util.code; + +masterCheck = async function(userId, eventId) { + const check = await Event.findOne({ + where: {user_id: userId, id: eventId}, + }); + return check !== null; +}; + +router.get('/event/:eventId', async function(req, res, next) { + const responseJson = {}; + const eventId = req.params.eventId; + if(!masterCheck(res.locals.user.id, eventId)) { + responseJson.result = code.NO_AUTH; + responseJson.detail = 'no auth'; + res.json(responseJson); + return; + } + + try { + const result = await User.findAll( + { + include: [ + { + model: BreakDown, + where: { + event_id: eventId, + sender_name: null, + }, + attributes: ['id', 'transfer_datetime', 'message', 'money'], + }, + ], + attributes: ['name'], + }, + ); + const list = []; + + for(let i = 0; i < result.length; i++) { + const {name, breakdowns} = result[i].dataValues; + for(let j = 0; j < breakdowns.length; j++) { + const temp = {}; + temp.id = breakdowns[j].id; + temp.name = name; + temp.money = breakdowns[j].money; + temp.message = breakdowns[j].message; + temp.transfer_datetime = breakdowns[j].transfer_datetime; + + list.push(temp); + } + } + + const result2 = await BreakDown.findAll( + { + where: { + event_id: eventId, + sender_id: 0, + }, + attributes: ['id', 'sender_name', 'transfer_datetime', 'message', 'money'], + }, + ); + + for(let i = 0; i < result2.length; i++) { + const temp = {}; + const {id, sender_name, transfer_datetime, message, money} = result2[i].dataValues; + + temp.id = id; + temp.name = sender_name; + temp.transfer_datetime = transfer_datetime; + temp.message = message; + temp.money = money; + temp.isDirectInput = true; + + list.push(temp); + } + + console.log(list); + responseJson.result = code.SUCCESS; + responseJson.detail = 'success'; + responseJson.data = list; + } + catch(exception) { + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'unknown error'; + } + finally { + res.json(responseJson); + } +}); + +router.get('/sender', async function(req, res, next) { + const responseJson = {}; + const userId = res.locals.user.id; + + try { + const result = await Event.findAll( + { + include: [ + { + model: BreakDown, + where: { + sender_id: userId, + }, + attributes: ['transfer_datetime', 'message', 'money'], + }, + ], + attributes: ['title'], + }, + ); + + const list = []; + + for(let i = 0; i < result.length; i++) { + const {breakdowns} = result[i].dataValues; + for(let j = 0; j < breakdowns.length; j++) { + const temp = {}; + const {transfer_datetime, message, money} = breakdowns[j]; + temp.title = result[i].dataValues.title; + temp.transfer_datetime = transfer_datetime; + temp.message = message; + temp.money = money; + + list.push(temp); + } + } + console.log(list); + responseJson.result = code.SUCCESS; + responseJson.detail = 'success'; + responseJson.data = list; + } + catch(exception) { + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'unknown error'; + } + finally { + res.json(responseJson); + } +}); + +router.post('/', async function(req, res, next) { + const responseJson = {}; + const {name, eventId, money} = req.body; + if(!masterCheck(res.locals.user.id, eventId)) { + responseJson.result = code.NO_AUTH; + responseJson.detail = 'no auth'; + res.json(responseJson); + return; + } + + try { + const transferTime = moment().format('YYYY-MM-DD HH:mm:ss'); + const data = { + event_id: Number(eventId), + sender_name: name, + transfer_datetime: transferTime, + money: Number(money), + is_direct_input: true, + }; + + const result = await BreakDown.create(data); + + responseJson.result = code.SUCCESS; + responseJson.detail = 'breakdown insert success'; + } + catch(exception) { + console.log(exception); + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'unknown error'; + } + finally { + res.json(responseJson); + } +}); + +module.exports = router; From e0db1b02b4ec4da44c8172a4ab216ff0cd6d6d8f Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 7 Dec 2020 09:27:15 +0900 Subject: [PATCH 29/47] =?UTF-8?q?foreign=20key=20=EC=84=A4=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/index.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/models/index.js b/models/index.js index 7043925..69d6220 100644 --- a/models/index.js +++ b/models/index.js @@ -16,4 +16,6 @@ db.Guest = require('./guest')(sequelize, Sequelize); db.BreakDown = require('./breakdown')(sequelize, Sequelize); db.Event.hasMany(db.Guest, {foreignKey: {name: 'event_id'}}); +db.Event.hasMany(db.BreakDown, {foreignKey: {name: 'event_id'}}); +db.User.hasMany(db.BreakDown, {foreignKey: {name: 'sender_id'}}); module.exports = db; From 78e42e9718b6b9a41ed6aad1a64eb934b1a0daaf Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 7 Dec 2020 09:28:08 +0900 Subject: [PATCH 30/47] =?UTF-8?q?sender=20id=20default=20value=20=EC=84=A4?= =?UTF-8?q?=EC=A0=95,=20sender=5Fname=20column=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/breakdown.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/models/breakdown.js b/models/breakdown.js index 775fae9..a47af32 100644 --- a/models/breakdown.js +++ b/models/breakdown.js @@ -14,6 +14,11 @@ module.exports = (sequelize, DataTypes) => { sender_id: { type: DataTypes.INTEGER, allowNull: false, + defaultValue: 0, + }, + sender_name: { + type: DataTypes.STRING(20), + allowNull: true, }, transfer_datetime: { type: DataTypes.DATE, From ee893034965d70fe4fe76da413e19f0fcbd868e4 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 7 Dec 2020 09:28:28 +0900 Subject: [PATCH 31/47] =?UTF-8?q?breakdown=20=EB=B4=89=EC=9D=B8=ED=95=B4?= =?UTF-8?q?=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app.js b/app.js index fbf994e..c6587b0 100644 --- a/app.js +++ b/app.js @@ -12,7 +12,7 @@ const authRouter = require('./routes/auth'); const usersRouter = require('./routes/users'); // TODO: not use yet -// const breakdownRouter = require('./routes/breakdown'); +const breakdownRouter = require('./routes/breakdown'); const eventRouter = require('./routes/event'); const finRouter = require('./routes/fin'); @@ -66,7 +66,7 @@ app.use('/*', function(req, res, next) { }); app.use('/event', eventRouter); app.use('/fin', finRouter); -// app.use('/breakdown', breakdownRouter); +app.use('/breakdown', breakdownRouter); // app.use('/guest', guestRouter); // app.use('/organizer', organizerRouter); From a1b320705aa5534f254b0d2130abe580a0735faa Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 7 Dec 2020 12:27:46 +0900 Subject: [PATCH 32/47] add send fcm function in utils.js, add serviceAccountKey for fcm, update gitignore --- .gitignore | 1 - serviceAccountKey.json | 12 ++++++++++++ utils.js | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 serviceAccountKey.json diff --git a/.gitignore b/.gitignore index bba6876..b59c203 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,3 @@ node_modules package-lock.json config/config.json fcm.js -serviceAccountKey.json \ No newline at end of file diff --git a/serviceAccountKey.json b/serviceAccountKey.json new file mode 100644 index 0000000..cbdf617 --- /dev/null +++ b/serviceAccountKey.json @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "kkotgil-bdb2e", + "private_key_id": "64e10e3692c1efb732d456a0650a45e0a92ed22e", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCQdKA47mB2vEs\nAXxOtWcAxZMjzaBNLXs5vMoAThwWndfbmtJIfLSRznyUpsLvJd90/MyHOaOH5WtV\npOYA6OBmTxbuwphgyoQrgIJ1pOFeuZ0SzWcPkwGO5Ak+Nzurnad+x1xbF+zhxLar\n0kKiU+G5NF3YWXgIBcHTNOh/NpEGJB1PgbYLzf+YzVzGG1RmxV7sbMJDoNU4zHUR\nDP/jci61VSyjpM2YeiWubmPKtlgGAeyNzy+slEMVbClaViNugogyQRjKdEEZmfQx\niPuerM1VBmOwjy1/enzc2iKtICzIr4ZlGNDjeimm7L7gZcnaqc5iHqFIQ2bRr/Ja\ncg07Zx4PAgMBAAECggEAVGRTJrKIG316C+OjVPBjDMdI2qOQ8iaBo748RbCpbDvr\nlJiopVwj+DosDkp6YnniH8lZs5+bR0Uogb8POzLwlhHjBRweJeKlU97TDnfwfv4F\nWq9IiFAVu7WevFwzfKWTqDTFD0AQJa8XqwK/9xSY+iRhZsXLqzSRFYglP2r9yxvv\nvncVj10+Hez0uDXL+8eyek6uBHZ9CwUUQgbiC1i5IqUNYszj8cddXBpjixWmKSnc\n/ft+w+hZYiczWyGP8CYPDPbLCILKbCTGvfMkcZkhEPLPSZVcgJRWf9cHjTDUn/wv\n8MlcxzU55GrV7lateOxKdhCU0ODlemg5YGjfUElTqQKBgQD128SeuLeCcbQFqbMG\nzqgSzn6aoaaOb3L5ZxYLXiQKLWBCubrsDROqarwrUnCaid7jja3XJdNEcjknNfBP\nOUF3QnqJEPz6YR1ivVTFf5WmmjXa0SrJ9UrziaJLTjX21RLuCiWKARdaHxlsi/ot\nZWPGUTdfEfww0mVmvHtX5mY91wKBgQDKRSanrHk9+1dpU35O1G+6hdoec4A0Pdic\nUwwtx9uHZKsGtvO7w/QokytaIAK5hp7kFUBT/t13zT4UzQrGw4/UVquwxRIrA5u8\n8YqQ9JQF5ZMUmuzo4ixFlh5lfyC3850HA2Sy7MexnV8WBcaTKPhC0mq6aPl7LLkg\n7qxWivNqiQKBgQCJWBsP2/rQCTrbCwDy5ZFo6Cg7s+A6o7Hj952N/io98TlcLStp\n4KhCxFuYC/bRrgFwt14M2ZmbHAAnkm9Lop2axO11EqNwL75dwYzQw8RTDMTXF5BC\nwB/9yr56ORfWaxOnHM35uUBVXRgz1kKNB53kVMyM9Jwgnfh9mv+AjDpDgwKBgCpT\ngh1AODbCK658rEeuqJqte9E3djJ4ZqV/s2K5GbUhWbCUBDjcbnE3KrE3VZqhEwrD\nb6yj/pAdQMp1hbXGIojagh8BfiXGIYbOPKLMq1T4j2iWatDo0z7UhRPUIHKd5dQb\n36yZY8hFGCqxlrYgsqK5CWBsqxgdabf8ec+6T+mRAoGBANhU6058zymeZTvdDUVr\niw1UXGLqfDcJvD451pEBQfO4RsKyTeZPIaQigsZiP9IlpdM6V9mQcHoysC5pFwIQ\ns+2+Oyfk0COJI4ZpwM2KIZyXETnHNSEhXBCfLRdH5neXVZEDteR4TBeeR3bEA4ZA\n8EaTZIpWw7tpOszUHI91KVA9\n-----END PRIVATE KEY-----\n", + "client_email": "firebase-adminsdk-cn82p@kkotgil-bdb2e.iam.gserviceaccount.com", + "client_id": "110341119686318549709", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-cn82p%40kkotgil-bdb2e.iam.gserviceaccount.com" +} diff --git a/utils.js b/utils.js index 7588dbc..48960ee 100644 --- a/utils.js +++ b/utils.js @@ -2,8 +2,16 @@ const path = require('path'); const env = process.env.NODE_ENV || 'development'; const config = require(path.join(__dirname, '.', 'config', 'config.json'))[env]; const jwt = require('jsonwebtoken'); +const admin = require('firebase-admin'); +const serviceAccount = require('./serviceAccountKey'); const value = {}; + +admin.initializeApp({ + credential: admin.credential.cert(serviceAccount), + databaseURL: 'https://kkotgil-bdb2e.firebaseio.com' +}); + value.code = { 'UNKNOWN_ERROR': -1, 'SUCCESS': 0, @@ -47,4 +55,31 @@ value.getUser = function (req) { value.saltRounds = 10; +value.sendFcm = async function(title, body, link, fbTokenList) { + const fcmMessage = { + data: { + title: title, + body: body, + link: link, + }, + tokens: fbTokenList, + }; + try { + const result = await admin.messaging().sendMulticast(fcmMessage); + + for(let i = 0; i < result.responses.length; i++) { + if(!result.responses[i].success) { + console.log(result.responses[i].error); + } + } + console.log('Send FCM Success'); + + return value.code.SUCCESS; + } + catch(exception) { + console.log(exception); + return value.code.UNKNOWN_ERROR; + } +}; + module.exports = value; From 71ec2fed056b7a5a2ed54f194606ff0fd0196a38 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Mon, 7 Dec 2020 20:33:14 +0900 Subject: [PATCH 33/47] error modify --- routes/breakdown.js | 1 + routes/event.js | 12 ++++++------ routes/fin.js | 14 ++++++++------ utils.js | 2 +- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/routes/breakdown.js b/routes/breakdown.js index 73c7402..df4a58b 100644 --- a/routes/breakdown.js +++ b/routes/breakdown.js @@ -50,6 +50,7 @@ router.get('/event/:eventId', async function(req, res, next) { temp.money = breakdowns[j].money; temp.message = breakdowns[j].message; temp.transfer_datetime = breakdowns[j].transfer_datetime; + temp.isDirectInput = false; list.push(temp); } diff --git a/routes/event.js b/routes/event.js index 337f8c7..61746f5 100644 --- a/routes/event.js +++ b/routes/event.js @@ -204,7 +204,7 @@ router.get('/', async function(req, res, next) { const result2 = await Event.findAll({ include: [{ model: EventAdmin, - where: {user_id: res.locals.user.id} + where: {user_id: res.locals.user.id}, }], order: [ ['is_activated', 'DESC'], @@ -218,7 +218,7 @@ router.get('/', async function(req, res, next) { for(let i = 0; i < result2.length; i++) { result.push(result2[i].dataValues); } - result.sort(function(a,b) { + result.sort(function(a, b) { if(a.is_activated >= b.is_activated) { if(a.event_datetime > b.event_datetime) { return -1; @@ -233,7 +233,7 @@ router.get('/', async function(req, res, next) { else { return 1; } - }) + }); responseJson.result = code.SUCCESS; responseJson.detail = 'success'; responseJson.data = result; @@ -353,7 +353,7 @@ router.get('/invite/:hash', async function(req, res, next) { const result = await Event.findOne({ attributes: ['id'], - where: {event_hash: hash} + where: {event_hash: hash}, }); const eventId = result.dataValues.id; @@ -368,12 +368,12 @@ router.get('/invite/:hash', async function(req, res, next) { { user_id: myId, event_id: eventId, - eventAdmin_id: hostId + eventAdmin_id: hostId, }, ); responseJson.result = code.SUCCESS; responseJson.detail = 'success'; - responseJson.data = {event_id : eventId}; + responseJson.data = {event_id: eventId}; } else { responseJson.result = code.NO_AUTH; diff --git a/routes/fin.js b/routes/fin.js index f2135f2..fe0f855 100644 --- a/routes/fin.js +++ b/routes/fin.js @@ -184,11 +184,13 @@ router.post('/transfer', async function(req, res, next) { responseJson.detail = result.data.Header.Rsms; res.json(responseJson); } - const time = result.data.Header.Tsymd + result.data.Header.Trtm; - res.locals.transferTime = time.replace( - /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, - '$1-$2-$3 $4:$5:$6'); - next(); + else { + const time = result.data.Header.Tsymd + result.data.Header.Trtm; + res.locals.transferTime = time.replace( + /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, + '$1-$2-$3 $4:$5:$6'); + next(); + } } catch (error) { responseJson.result = code.NH_API_ERROR; @@ -220,7 +222,7 @@ router.post('/transfer', async function(req, res, next) { const result = await BreakDown.create(data); responseJson.result = code.SUCCESS; responseJson.detail = 'transfer success'; - responseJson.data = { event_id: eventId}; + responseJson.data = {event_id: eventId}; res.json(responseJson); } catch (error) { diff --git a/utils.js b/utils.js index 48960ee..445812e 100644 --- a/utils.js +++ b/utils.js @@ -9,7 +9,7 @@ const value = {}; admin.initializeApp({ credential: admin.credential.cert(serviceAccount), - databaseURL: 'https://kkotgil-bdb2e.firebaseio.com' + databaseURL: 'https://kkotgil-bdb2e.firebaseio.com', }); value.code = { From 77029fdd285be713651a3c0124d8077ee1381ea1 Mon Sep 17 00:00:00 2001 From: hyunjun Date: Tue, 8 Dec 2020 12:03:20 +0900 Subject: [PATCH 34/47] =?UTF-8?q?=EC=88=98=EC=A0=95=EC=82=AC=ED=95=AD=202,?= =?UTF-8?q?3=EB=B2=88=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- routes/auth.js | 2 +- routes/event.js | 19 ++++++++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/routes/auth.js b/routes/auth.js index fc409de..21e022c 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -44,7 +44,7 @@ router.get('/', function(req, res, next) { router.post('/login', async function(req, res, next) { try { const {body} = req; - const user = await User.findOne({attributes: ['id', 'password'], where: {username: body.username}}); + const user = await User.findOne({attributes: ['id', 'password', 'fin_account','name'], where: {username: body.username}}); if(user === null) { console.log('cannot find user'); diff --git a/routes/event.js b/routes/event.js index 61746f5..1cd8c33 100644 --- a/routes/event.js +++ b/routes/event.js @@ -277,11 +277,20 @@ router.get('/:id', async function(req, res, next) { responseJson.result = code.NO_DATA; responseJson.detail = 'cannot find eventData'; } - else { - let haveAuth = result.dataValues.user_id === myId; - haveAuth = haveAuth || await adminCheck(myId, eventId) || await guestCheck(myId, eventId); - if(haveAuth) { - const data = result.dataValues; + else { + const data = result.dataValues; + if(result.dataValues.user_id === myId) { + data.userType = 'master'; + } + else { + if(await adminCheck(myId, eventId)) { + data.userType = 'admin' + } + else if(await guestCheck(myId, eventId)) { + data.userType = 'guest' + } + } + if(typeof data.userType !== 'undefined') { const result2 = await EventAdmin.findAll( { attributes: ['user_phone'], From 73c5f563dd92fff5f51da082d5fe7793eeee149d Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Tue, 8 Dec 2020 17:13:38 +0900 Subject: [PATCH 35/47] add 'is received' --- models/event.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/models/event.js b/models/event.js index 3e0232c..6ce3de2 100644 --- a/models/event.js +++ b/models/event.js @@ -45,6 +45,11 @@ module.exports = (sequelize, DataTypes) => { type: DataTypes.BOOLEAN, allowNull: false, }, + is_received: { + type: DataTypes.BOOLEAN, + allowNull: false, + defaultValue: false, + }, }, { timestamps: false, From 2f6aafaff05cf4744df7df9676dc97196a78489d Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Tue, 8 Dec 2020 17:17:52 +0900 Subject: [PATCH 36/47] add send fcm function --- routes/breakdown.js | 39 +++++++++++++++++++++-- routes/event.js | 76 ++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 106 insertions(+), 9 deletions(-) diff --git a/routes/breakdown.js b/routes/breakdown.js index df4a58b..7ef1baf 100644 --- a/routes/breakdown.js +++ b/routes/breakdown.js @@ -16,7 +16,7 @@ masterCheck = async function(userId, eventId) { router.get('/event/:eventId', async function(req, res, next) { const responseJson = {}; const eventId = req.params.eventId; - if(!masterCheck(res.locals.user.id, eventId)) { + if(!await masterCheck(res.locals.user.id, eventId)) { responseJson.result = code.NO_AUTH; responseJson.detail = 'no auth'; res.json(responseJson); @@ -146,7 +146,7 @@ router.get('/sender', async function(req, res, next) { router.post('/', async function(req, res, next) { const responseJson = {}; const {name, eventId, money} = req.body; - if(!masterCheck(res.locals.user.id, eventId)) { + if(!await masterCheck(res.locals.user.id, eventId)) { responseJson.result = code.NO_AUTH; responseJson.detail = 'no auth'; res.json(responseJson); @@ -178,4 +178,39 @@ router.post('/', async function(req, res, next) { } }); +router.delete('/:id/:eventId', async function(req, res, next) { + const responseJson = {}; + if(!await masterCheck(res.locals.user.id, req.params.eventId)) { + responseJson.result = code.NO_AUTH; + responseJson.detail = 'no auth'; + res.json(responseJson); + return; + } + try { + const result = await BreakDown.destroy( + { + where: { + id: req.params.id, + is_direct_input: true, + }, + }, + ); + if(result === 0) { + responseJson.result = code.NO_DATA; + responseJson.detail = 'no direct input, or no data'; + } + else if(result === 1) { + responseJson.result = code.SUCCESS; + responseJson.detail = 'success'; + } + } + catch(exception) { + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'unknown error'; + } + finally { + res.json(responseJson); + } +}); + module.exports = router; diff --git a/routes/event.js b/routes/event.js index 61746f5..1114054 100644 --- a/routes/event.js +++ b/routes/event.js @@ -74,13 +74,16 @@ router.post('/', async function(req, res, next) { is_activated: true, }, ); - res.locals.eventId = result.dataValues.id; const eventId = result.dataValues.id; + res.locals.eventId = eventId; + res.locals.title = result.dataValues.title; + res.locals.eventDatetime = result.dataValues.event_datetime; + for(let i = 0; i < res.locals.admins.length; i++) { res.locals.admins[i].event_id = eventId; } const encrypt = crypto.createHash('sha256').update(eventId + ' ').digest('hex'); - + const updateResult = await Event.update( { event_hash: encrypt, @@ -108,6 +111,65 @@ router.post('/', async function(req, res, next) { try { const result = await EventAdmin.bulkCreate(admins); + const userAdmin = []; + const noUserAdmin = []; + + for(let i = 0; i < result.length; i++) { + const temp = result[i].dataValues; + if(temp.user_id === null) { + noUserAdmin.push(temp.user_phone); + } + else if(temp.user_id !== res.locals.user.id) { + userAdmin.push(temp.user_id); + } + } + const eventAdmins = { + user: userAdmin, + noUser: noUserAdmin, + }; + + res.locals.adminIds = eventAdmins; + + next(); + } + catch(exception) { + console.log(exception); + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'unknown error2'; + res.json(responseJson); + } +}); + +// sendFcm or sms +router.post('/', async function(req, res, next) { + const responseJson = {}; + const adminIds = res.locals.adminIds; + console.log(adminIds); + try { + const result = await User.findAll( + { + where: { + id: adminIds.user, + }, + attributes: ['id', 'phone_number', 'firebase_token'], + }, + ); + + const fbTokens = []; + for(let i = 0; i < result.length; i++) { + const temp = result[i].dataValues.firebase_token; + fbTokens.push(temp); + } + + const fcm = await util.sendFcm( + res.locals.title, + res.locals.title + '의 관리자로 초대되었습니다.\n' + '시간 : ' + res.locals.eventDatetime + '\n', + '서버주소/event/' + res.locals.eventId, + fbTokens, + ); + + // TODO : admins.noUser = 회원가입 안된 사람들 문자로 + responseJson.result = code.SUCCESS; responseJson.detail = 'success'; responseJson.data = {id: res.locals.eventId}; @@ -115,7 +177,7 @@ router.post('/', async function(req, res, next) { catch(exception) { console.log(exception); responseJson.result = code.UNKNOWN_ERROR; - responseJson.detail = 'unknown error2'; + responseJson.detail = 'unknown error3'; } finally { res.json(responseJson); @@ -189,7 +251,7 @@ router.get('/', async function(req, res, next) { const isHost = req.query.host; if(typeof isHost === 'undefined') { responseJson.result = code.INVALID_QUERY; - responseJson.detail = 'params error'; + responseJson.detail = 'params error'; } else if(isHost === 'true') { const result1 = await Event.findAll( @@ -250,7 +312,7 @@ router.get('/', async function(req, res, next) { ], }); responseJson.result = code.SUCCESS; - responseJson.detail = 'success'; + responseJson.detail = 'success'; responseJson.data = result; } } @@ -290,7 +352,7 @@ router.get('/:id', async function(req, res, next) { ); data.eventAdmin = result2; responseJson.result = code.SUCCESS; - responseJson.detail = 'success'; + responseJson.detail = 'success'; responseJson.data = data; } else { @@ -312,7 +374,7 @@ router.get('/:id', async function(req, res, next) { // event close router.put('/close/:id', async function(req, res, next) { const responseJson = {}; - const eventId = req.params.id; + const eventId = req.params.id; const myId = res.locals.user.id; try { if(await masterCheck(myId, eventId)) { From e2f8a22d5c86a102348086bd9fdfcd3b34f4d89a Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Tue, 8 Dec 2020 17:18:17 +0900 Subject: [PATCH 37/47] update event model when received money --- routes/fin.js | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/routes/fin.js b/routes/fin.js index fe0f855..7678c09 100644 --- a/routes/fin.js +++ b/routes/fin.js @@ -254,6 +254,14 @@ router.post('/receive', async function(req, res, next) { return; } + console.log(result); + if(result.dataValues.is_received) { + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'already received'; + res.json(responseJson); + return; + } + if(result.dataValues.user_id !== res.locals.user.id) { responseJson.result = code.NO_AUTH; responseJson.detail = 'no auth'; @@ -307,12 +315,38 @@ router.post('/receive', async function(req, res, next) { body.Header = createBodyHeader(apiNm, res.locals.user.id); const nhResult = await axios.post(getNHURL(apiNm), body); - responseJson.result = code.SUCCESS; - responseJson.detail = 'receive success'; + + next(); } catch(exception) { responseJson.result = code.NH_API_ERROR; responseJson.detail = 'nh api( ReceivedTransferAccountNumber ) error'; + res.json(responseJson); + } +}); + +// update event's is_received +router.post('/receive', async function(req, res, next) { + const responseJson = {}; + + try { + const result = await Event.update( + { + is_received: true, + }, + { + where: { + id: res.locals.eventId, + }, + }, + ); + + responseJson.result = code.SUCCESS; + responseJson.detail = 'receive success'; + } + catch(exception) { + responseJson.result = code.DB_ERROR; + responseJson.detail = 'db update error'; } finally { res.json(responseJson); From 4684ed9d51f78304dda6c9e250c36df7b8743df0 Mon Sep 17 00:00:00 2001 From: jaypae95 Date: Tue, 8 Dec 2020 00:29:45 -0800 Subject: [PATCH 38/47] add service account key sample and delelte original file --- serviceAccountKey.json | 12 ------------ serviceAccountKey.json.sample | 12 ++++++++++++ 2 files changed, 12 insertions(+), 12 deletions(-) delete mode 100644 serviceAccountKey.json create mode 100644 serviceAccountKey.json.sample diff --git a/serviceAccountKey.json b/serviceAccountKey.json deleted file mode 100644 index cbdf617..0000000 --- a/serviceAccountKey.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "type": "service_account", - "project_id": "kkotgil-bdb2e", - "private_key_id": "64e10e3692c1efb732d456a0650a45e0a92ed22e", - "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCQdKA47mB2vEs\nAXxOtWcAxZMjzaBNLXs5vMoAThwWndfbmtJIfLSRznyUpsLvJd90/MyHOaOH5WtV\npOYA6OBmTxbuwphgyoQrgIJ1pOFeuZ0SzWcPkwGO5Ak+Nzurnad+x1xbF+zhxLar\n0kKiU+G5NF3YWXgIBcHTNOh/NpEGJB1PgbYLzf+YzVzGG1RmxV7sbMJDoNU4zHUR\nDP/jci61VSyjpM2YeiWubmPKtlgGAeyNzy+slEMVbClaViNugogyQRjKdEEZmfQx\niPuerM1VBmOwjy1/enzc2iKtICzIr4ZlGNDjeimm7L7gZcnaqc5iHqFIQ2bRr/Ja\ncg07Zx4PAgMBAAECggEAVGRTJrKIG316C+OjVPBjDMdI2qOQ8iaBo748RbCpbDvr\nlJiopVwj+DosDkp6YnniH8lZs5+bR0Uogb8POzLwlhHjBRweJeKlU97TDnfwfv4F\nWq9IiFAVu7WevFwzfKWTqDTFD0AQJa8XqwK/9xSY+iRhZsXLqzSRFYglP2r9yxvv\nvncVj10+Hez0uDXL+8eyek6uBHZ9CwUUQgbiC1i5IqUNYszj8cddXBpjixWmKSnc\n/ft+w+hZYiczWyGP8CYPDPbLCILKbCTGvfMkcZkhEPLPSZVcgJRWf9cHjTDUn/wv\n8MlcxzU55GrV7lateOxKdhCU0ODlemg5YGjfUElTqQKBgQD128SeuLeCcbQFqbMG\nzqgSzn6aoaaOb3L5ZxYLXiQKLWBCubrsDROqarwrUnCaid7jja3XJdNEcjknNfBP\nOUF3QnqJEPz6YR1ivVTFf5WmmjXa0SrJ9UrziaJLTjX21RLuCiWKARdaHxlsi/ot\nZWPGUTdfEfww0mVmvHtX5mY91wKBgQDKRSanrHk9+1dpU35O1G+6hdoec4A0Pdic\nUwwtx9uHZKsGtvO7w/QokytaIAK5hp7kFUBT/t13zT4UzQrGw4/UVquwxRIrA5u8\n8YqQ9JQF5ZMUmuzo4ixFlh5lfyC3850HA2Sy7MexnV8WBcaTKPhC0mq6aPl7LLkg\n7qxWivNqiQKBgQCJWBsP2/rQCTrbCwDy5ZFo6Cg7s+A6o7Hj952N/io98TlcLStp\n4KhCxFuYC/bRrgFwt14M2ZmbHAAnkm9Lop2axO11EqNwL75dwYzQw8RTDMTXF5BC\nwB/9yr56ORfWaxOnHM35uUBVXRgz1kKNB53kVMyM9Jwgnfh9mv+AjDpDgwKBgCpT\ngh1AODbCK658rEeuqJqte9E3djJ4ZqV/s2K5GbUhWbCUBDjcbnE3KrE3VZqhEwrD\nb6yj/pAdQMp1hbXGIojagh8BfiXGIYbOPKLMq1T4j2iWatDo0z7UhRPUIHKd5dQb\n36yZY8hFGCqxlrYgsqK5CWBsqxgdabf8ec+6T+mRAoGBANhU6058zymeZTvdDUVr\niw1UXGLqfDcJvD451pEBQfO4RsKyTeZPIaQigsZiP9IlpdM6V9mQcHoysC5pFwIQ\ns+2+Oyfk0COJI4ZpwM2KIZyXETnHNSEhXBCfLRdH5neXVZEDteR4TBeeR3bEA4ZA\n8EaTZIpWw7tpOszUHI91KVA9\n-----END PRIVATE KEY-----\n", - "client_email": "firebase-adminsdk-cn82p@kkotgil-bdb2e.iam.gserviceaccount.com", - "client_id": "110341119686318549709", - "auth_uri": "https://accounts.google.com/o/oauth2/auth", - "token_uri": "https://oauth2.googleapis.com/token", - "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", - "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-cn82p%40kkotgil-bdb2e.iam.gserviceaccount.com" -} diff --git a/serviceAccountKey.json.sample b/serviceAccountKey.json.sample new file mode 100644 index 0000000..7a52732 --- /dev/null +++ b/serviceAccountKey.json.sample @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "insert project_id", + "private_key_id": "insert private key id", + "private_key": "insert private key", + "client_email": "insert client email", + "client_id": "insert clien id", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "insert client x509 cert url" +} From b217eaa4fe5f2f30f1e30dc806646ebb62a5ed60 Mon Sep 17 00:00:00 2001 From: jaypae95 Date: Tue, 8 Dec 2020 00:30:16 -0800 Subject: [PATCH 39/47] add file to gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index b59c203..ea750e1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ node_modules package-lock.json config/config.json fcm.js +serviceAccountKey.json From 3bff059aba95c6730283f7987fc3d76ff6243f62 Mon Sep 17 00:00:00 2001 From: jaypae95 Date: Tue, 8 Dec 2020 03:53:32 -0800 Subject: [PATCH 40/47] return fin account info while success --- routes/fin.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/routes/fin.js b/routes/fin.js index fe0f855..8f43f98 100644 --- a/routes/fin.js +++ b/routes/fin.js @@ -116,6 +116,9 @@ router.post('/', async function(req, res, next) { }); responseJson.result= code.SUCCESS; responseJson.detail= 'finaccount create success'; + responseJson.data = { + fin_account: finAcno + } res.json(responseJson); } catch (error) { From b453aa709fa4fde2c59d7a20fd980234f9fa61cf Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Tue, 8 Dec 2020 20:57:53 +0900 Subject: [PATCH 41/47] add delete --- routes/breakdown.js | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/routes/breakdown.js b/routes/breakdown.js index 7ef1baf..7858844 100644 --- a/routes/breakdown.js +++ b/routes/breakdown.js @@ -178,16 +178,29 @@ router.post('/', async function(req, res, next) { } }); -router.delete('/:id/:eventId', async function(req, res, next) { +router.delete('/:id', async function(req, res, next) { const responseJson = {}; - if(!await masterCheck(res.locals.user.id, req.params.eventId)) { - responseJson.result = code.NO_AUTH; - responseJson.detail = 'no auth'; - res.json(responseJson); - return; - } + try { - const result = await BreakDown.destroy( + const result = await BreakDown.findOne( + { + where: { + id: req.params.id, + }, + attributes: ['id', 'event_id'], + }, + ); + + const eventId = result.dataValues.event_id; + + if(!await masterCheck(res.locals.user.id, eventId)) { + responseJson.result = code.NO_AUTH; + responseJson.detail = 'no auth'; + res.json(responseJson); + return; + } + + const result2 = await BreakDown.destroy( { where: { id: req.params.id, @@ -195,14 +208,18 @@ router.delete('/:id/:eventId', async function(req, res, next) { }, }, ); - if(result === 0) { + if(result2 === 0) { responseJson.result = code.NO_DATA; responseJson.detail = 'no direct input, or no data'; } - else if(result === 1) { + else if(result2 === 1) { responseJson.result = code.SUCCESS; responseJson.detail = 'success'; } + else { + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'success'; + } } catch(exception) { responseJson.result = code.UNKNOWN_ERROR; From e768ec27f90d28345a787cfb7c9e0678aaee47a5 Mon Sep 17 00:00:00 2001 From: jaypae95 Date: Tue, 8 Dec 2020 05:04:17 -0800 Subject: [PATCH 42/47] HOTFIX fixed err --- routes/fin.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/routes/fin.js b/routes/fin.js index 8f43f98..409a550 100644 --- a/routes/fin.js +++ b/routes/fin.js @@ -16,7 +16,7 @@ createBodyHeader = function(apiNm, userId) { const time = moment().format('YYYYMMDD-HHmmss'); const tsymd = time.substring(0, 8); const trtm = time.substring(9, 15); - const ut = Math.floor(new Date().getTime() / 1000); + const ut = Math.floor(new Date().getTime()); const isTuno = ut + userId.toString(); const postBodyHeader = { @@ -83,7 +83,7 @@ router.post('/', async function(req, res, next) { const result = await axios.post(getNHURL(apiNm), body); if(result.data.Header.Rpcd !== '00000') { responseJson.result = code.NH_API_ERROR; - responseJson.detail = reult.data.Header.Rsms; + responseJson.detail = result.data.Header.Rsms; res.json(responseJson); } else { @@ -94,7 +94,7 @@ router.post('/', async function(req, res, next) { catch (error) { responseJson.result = code.NH_API_ERROR; responseJson.detail = 'nh api (CheckOpenFinAccountDirect) error'; - next(error); + res.json(responseJson); } }); @@ -125,7 +125,6 @@ router.post('/', async function(req, res, next) { responseJson.result = code.DB_ERROR; responseJson.detail = 'user table update error'; res.json(responseJson); - next(error); } }); From 4d2a8994783c06f9a97a22a29e2a9649106887a7 Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Wed, 9 Dec 2020 10:07:35 +0900 Subject: [PATCH 43/47] if no firebase token, go to no User --- routes/event.js | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/routes/event.js b/routes/event.js index 41a27f4..c547562 100644 --- a/routes/event.js +++ b/routes/event.js @@ -144,7 +144,6 @@ router.post('/', async function(req, res, next) { router.post('/', async function(req, res, next) { const responseJson = {}; const adminIds = res.locals.adminIds; - console.log(adminIds); try { const result = await User.findAll( { @@ -158,15 +157,22 @@ router.post('/', async function(req, res, next) { const fbTokens = []; for(let i = 0; i < result.length; i++) { const temp = result[i].dataValues.firebase_token; - fbTokens.push(temp); + if(temp != null) { + fbTokens.push(temp); + } + else { + adminIds.noUser.push(result[i].dataValues.phone_number); + } } - const fcm = await util.sendFcm( - res.locals.title, - res.locals.title + '의 관리자로 초대되었습니다.\n' + '시간 : ' + res.locals.eventDatetime + '\n', - '서버주소/event/' + res.locals.eventId, - fbTokens, - ); + if(fbTokens.length !== 0) { + const fcm = await util.sendFcm( + res.locals.title, + res.locals.title + '의 관리자로 초대되었습니다.\n' + '시간 : ' + res.locals.eventDatetime + '\n', + '서버주소/event/' + res.locals.eventId, + fbTokens, + ); + } // TODO : admins.noUser = 회원가입 안된 사람들 문자로 @@ -339,10 +345,10 @@ router.get('/:id', async function(req, res, next) { responseJson.result = code.NO_DATA; responseJson.detail = 'cannot find eventData'; } - else { + else { const data = result.dataValues; if(result.dataValues.user_id === myId) { - data.userType = 'master'; + data.userType = 'master'; } else { if(await adminCheck(myId, eventId)) { From 0683aea27780fafb8f531790c2b24ff33b58f81f Mon Sep 17 00:00:00 2001 From: KHS-kr Date: Wed, 9 Dec 2020 17:46:54 +0900 Subject: [PATCH 44/47] put event add category --- routes/event.js | 1 + 1 file changed, 1 insertion(+) diff --git a/routes/event.js b/routes/event.js index c547562..d07c2bb 100644 --- a/routes/event.js +++ b/routes/event.js @@ -200,6 +200,7 @@ router.put('/:id', async function(req, res, next) { if(await masterCheck(userId, eventId)) { const result = await Event.update( { + category: body.category, title: body.title, location: body.location, body: body.body, From f63863287852eb51d3d727fb722f10ea3ff08092 Mon Sep 17 00:00:00 2001 From: hyunjun Date: Wed, 9 Dec 2020 17:54:32 +0900 Subject: [PATCH 45/47] event invite add user type --- routes/event.js | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/routes/event.js b/routes/event.js index d07c2bb..3b7dc14 100644 --- a/routes/event.js +++ b/routes/event.js @@ -430,28 +430,42 @@ router.get('/invite/:hash', async function(req, res, next) { const hash = req.params.hash; const result = await Event.findOne({ - attributes: ['id'], + attributes: ['id', 'user_id'], where: {event_hash: hash}, }); - const eventId = result.dataValues.id; if (result === null) { responseJson.result = code.NO_DATA; responseJson.detail = 'cannot find event_hash'; } else { - const hostCheck = await masterCheck(hostId, eventId) || await adminCheck(hostId, eventId); + const eventId = result.dataValues.id; + const hostCheck = result.dataValues.user_id == hostId || await adminCheck(hostId, eventId); if(hostCheck) { - const result2 = await Guest.create( - { - user_id: myId, - event_id: eventId, - eventAdmin_id: hostId, - }, - ); + const data = {event_id: eventId}; + if(result.dataValues.user_id == myId) { + data.userType = 'master'; + } + else { + if(await adminCheck(myId, eventId)) { + data.userType = 'admin' + } + else { + data.userType = 'guest' + } + } + if(data.userType === 'guest') { + const result2 = await Guest.findOrCreate({ + where:{ + user_id: myId, + event_id: eventId, + eventAdmin_id: hostId, + } + }); + } responseJson.result = code.SUCCESS; responseJson.detail = 'success'; - responseJson.data = {event_id: eventId}; + responseJson.data = data; } else { responseJson.result = code.NO_AUTH; From 67d771c539c5ef4cd169780bbf469c9bb729340a Mon Sep 17 00:00:00 2001 From: hyunjun Date: Wed, 9 Dec 2020 20:28:52 +0900 Subject: [PATCH 46/47] implement transaction --- routes/event.js | 116 ++++++++++++++++++++++++++++++++++++++++++------ routes/users.js | 14 ++++-- 2 files changed, 113 insertions(+), 17 deletions(-) diff --git a/routes/event.js b/routes/event.js index 3b7dc14..7d43efd 100644 --- a/routes/event.js +++ b/routes/event.js @@ -1,7 +1,7 @@ const express = require('express'); const router = express.Router(); const crypto = require('crypto'); -const {User, Event, EventAdmin, Guest} = require('../models'); +const {sequelize, User, Event, EventAdmin, Guest} = require('../models'); const util = require('../utils'); const code = util.code; @@ -57,6 +57,85 @@ router.post('/', async function(req, res, next) { next(); }); + +// post2 : event insert +router.post('/', async function(req, res, next) { + const responseJson = {}; + const body = req.body; + const myId = res.locals.user.id; + const admins = res.locals.admins; + let transaction = await sequelize.transaction(); + try { + const result = await Event.create( + { + user_id: myId, + category: body.category, + title: body.title, + location: body.location, + body: body.body, + invitation_url: body.invitationUrl, + event_datetime: body.eventDatetime, + is_activated: true, + }, + { transaction } + ); + const eventId = result.dataValues.id; + res.locals.eventId = eventId; + res.locals.title = result.dataValues.title; + res.locals.eventDatetime = result.dataValues.event_datetime; + + for(let i = 0; i < admins.length; i++) { + admins[i].event_id = eventId; + } + const encrypt = crypto.createHash('sha256').update(eventId + ' ').digest('hex'); + const updateResult = await Event.update( + { + event_hash: encrypt, + }, + { + where: { + id: eventId, + }, + transaction + }, + ); + + //event admin insert + const result2 = await EventAdmin.bulkCreate(admins, { transaction }); + + const userAdmin = []; + const noUserAdmin = []; + + for(let i = 0; i < result2.length; i++) { + const temp = result2[i].dataValues; + if(temp.user_id === null) { + noUserAdmin.push(temp.user_phone); + } + else if(temp.user_id !== myId) { + userAdmin.push(temp.user_id); + } + } + const eventAdmins = { + user: userAdmin, + noUser: noUserAdmin, + }; + + res.locals.adminIds = eventAdmins; + await transaction.commit(); + next(); + } + catch(exception) { + console.log(exception); + if (transaction) { + await transaction.rollback(); + } + responseJson.result = code.UNKNOWN_ERROR; + responseJson.detail = 'event create db error'; + res.json(responseJson); + } +}); + +/* // post2 : event insert router.post('/', async function(req, res, next) { const responseJson = {}; @@ -139,7 +218,7 @@ router.post('/', async function(req, res, next) { res.json(responseJson); } }); - +*/ // sendFcm or sms router.post('/', async function(req, res, next) { const responseJson = {}; @@ -231,21 +310,32 @@ router.put('/:id', async function(req, res, next) { router.delete('/:id', async function(req, res, next) { const responseJson = {}; + const eventId = req.params.id; + const myId = res.locals.user.id; + let transaction = await sequelize.transaction(); try { - const result = await Event.destroy( - {where: {id: req.params.id}}, - ); - - const adminResult = await EventAdmin.destroy( - {where: {event_id: req.params.id}}, - ); - - responseJson.result = code.SUCCESS; - responseJson.detail = 'success'; + if(await masterCheck(myId, eventId)) { + const result = await Event.destroy( + {where: {id: eventId}, transaction}, + ); + const adminResult = await EventAdmin.destroy( + {where: {event_id: eventId}, transaction}, + ); + await transaction.commit(); + responseJson.result = code.SUCCESS; + responseJson.detail = 'success'; + } + else { + responseJson.result = code.NO_AUTH; + responseJson.detail = 'no auth'; + } } catch(exception) { + if (transaction) { + await transaction.rollback(); + } responseJson.result = code.UNKNOWN_ERROR; - responseJson.detail = 'unknown error'; + responseJson.detail = 'event delete error'; } finally { res.json(responseJson); diff --git a/routes/users.js b/routes/users.js index eba67c1..e497f97 100644 --- a/routes/users.js +++ b/routes/users.js @@ -1,6 +1,6 @@ const express = require('express'); const router = express.Router(); -const {User, EventAdmin} = require('../models'); +const {sequelize, User, EventAdmin} = require('../models'); const bcrypt = require('bcrypt'); const util = require('../utils.js'); const code = util.code; @@ -52,6 +52,7 @@ router.get('/overlap/username', async function(req, res, next) { // 회원가입 router.post('/signup', async function(req, res, next) { const responseJson = {}; + let transaction = await sequelize.transaction(); try { if(util.phoneNumberCheck(req.body.phone_number)) { const bcPw = bcrypt.hashSync(req.body.password, util.saltRounds); @@ -60,7 +61,7 @@ router.post('/signup', async function(req, res, next) { password: bcPw, name: req.body.name, phone_number: req.body.phone_number, - }); + }, {transaction}); responseJson.result = code.SUCCESS; responseJson.detail = 'signup success'; @@ -78,9 +79,11 @@ router.post('/signup', async function(req, res, next) { where: { user_phone: req.body.phone_number, }, - }, + transaction + } ); } + await transaction.commit(); } else { responseJson.result = code.PHONE_NUMBER_INVALID; @@ -88,8 +91,11 @@ router.post('/signup', async function(req, res, next) { } } catch(exception) { + if (transaction) { + await transaction.rollback(); + } responseJson.result = code.UNKNOWN_ERROR; - responseJson.detail = 'unknown error'; + responseJson.detail = 'sign up error'; } finally { res.json(responseJson); From 5ad7b382afb88f1ed20affbd9daf13cffb933126 Mon Sep 17 00:00:00 2001 From: hyunjun Date: Wed, 9 Dec 2020 20:30:53 +0900 Subject: [PATCH 47/47] delete comment --- routes/event.js | 84 ------------------------------------------------- 1 file changed, 84 deletions(-) diff --git a/routes/event.js b/routes/event.js index 7d43efd..5a38bb5 100644 --- a/routes/event.js +++ b/routes/event.js @@ -135,90 +135,6 @@ router.post('/', async function(req, res, next) { } }); -/* -// post2 : event insert -router.post('/', async function(req, res, next) { - const responseJson = {}; - const body = req.body; - try { - const result = await Event.create( - { - user_id: res.locals.user.id, - category: body.category, - title: body.title, - location: body.location, - body: body.body, - invitation_url: body.invitationUrl, - event_datetime: body.eventDatetime, - is_activated: true, - }, - ); - const eventId = result.dataValues.id; - res.locals.eventId = eventId; - res.locals.title = result.dataValues.title; - res.locals.eventDatetime = result.dataValues.event_datetime; - - for(let i = 0; i < res.locals.admins.length; i++) { - res.locals.admins[i].event_id = eventId; - } - const encrypt = crypto.createHash('sha256').update(eventId + ' ').digest('hex'); - - const updateResult = await Event.update( - { - event_hash: encrypt, - }, - { - where: { - id: eventId, - }}, - ); - next(); - } - catch(exception) { - console.log(exception); - responseJson.result = code.UNKNOWN_ERROR; - responseJson.detail = 'unknown error1'; - res.json(responseJson); - } -}); - -// post3 : eventadmin insert -router.post('/', async function(req, res, next) { - const responseJson = {}; - const admins = res.locals.admins; - - try { - const result = await EventAdmin.bulkCreate(admins); - - const userAdmin = []; - const noUserAdmin = []; - - for(let i = 0; i < result.length; i++) { - const temp = result[i].dataValues; - if(temp.user_id === null) { - noUserAdmin.push(temp.user_phone); - } - else if(temp.user_id !== res.locals.user.id) { - userAdmin.push(temp.user_id); - } - } - const eventAdmins = { - user: userAdmin, - noUser: noUserAdmin, - }; - - res.locals.adminIds = eventAdmins; - - next(); - } - catch(exception) { - console.log(exception); - responseJson.result = code.UNKNOWN_ERROR; - responseJson.detail = 'unknown error2'; - res.json(responseJson); - } -}); -*/ // sendFcm or sms router.post('/', async function(req, res, next) { const responseJson = {};