박권수

feat. User Model, History add / Api Modify / ...etc

1 +{
2 + "extends": "eslint:recommended",
3 + "rules": {
4 + "semi": ["warn", "never"],
5 + "quotes": ["warn", "single"],
6 + "no-console": ["off"]
7 + },
8 + "parserOptions": {
9 + "ecmaVersion": 9
10 + },
11 + "env": {
12 + "es6": true,
13 + "node": true,
14 + "browser": true,
15 + "amd": true
16 + },
17 + "globals": {
18 + "$": true,
19 + "require": true,
20 + "process": true
21 + },
22 + "root": true
23 +}
...\ No newline at end of file ...\ No newline at end of file
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
2 const User = require('../../models/user'); 2 const User = require('../../models/user');
3 const Joi = require('joi'); 3 const Joi = require('joi');
4 4
5 +
5 exports.register = async(ctx) => { 6 exports.register = async(ctx) => {
6 const { userId, password, passwordCheck } = ctx.request.body; 7 const { userId, password, passwordCheck } = ctx.request.body;
7 8
...@@ -49,7 +50,7 @@ exports.login = async(ctx) => { ...@@ -49,7 +50,7 @@ exports.login = async(ctx) => {
49 } 50 }
50 51
51 const user = await User.findByUserId(userId); 52 const user = await User.findByUserId(userId);
52 - if(!user) { 53 + if(!user || !user.userTypeCd) {
53 ctx.stauts = 401; 54 ctx.stauts = 401;
54 return; 55 return;
55 } 56 }
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
2 const Bottle = require('../../models/bottle'); 2 const Bottle = require('../../models/bottle');
3 const Hub = require('../../models/hub'); 3 const Hub = require('../../models/hub');
4 const Medicine = require('../../models/medicine'); 4 const Medicine = require('../../models/medicine');
5 +const User = require('../../models/user');
5 const Mqtt = require('../../lib/MqttModule'); 6 const Mqtt = require('../../lib/MqttModule');
6 const jwt = require('jsonwebtoken'); 7 const jwt = require('jsonwebtoken');
7 8
...@@ -14,6 +15,12 @@ exports.bottleConnect = async(ctx) => { ...@@ -14,6 +15,12 @@ exports.bottleConnect = async(ctx) => {
14 } 15 }
15 16
16 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 17 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
18 + const user = await User.findById(userId);
19 + if(!user || !user.userTypeCd) {
20 + ctx.status = 403;
21 + return;
22 + }
23 +
17 const { bottleId, hubId } = ctx.request.body; 24 const { bottleId, hubId } = ctx.request.body;
18 25
19 const isExistBottle = await Bottle.findByBottleId(bottleId); 26 const isExistBottle = await Bottle.findByBottleId(bottleId);
...@@ -62,6 +69,12 @@ exports.bottleDisconnect = async(ctx) => { ...@@ -62,6 +69,12 @@ exports.bottleDisconnect = async(ctx) => {
62 } 69 }
63 70
64 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 71 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
72 + const user = await User.findById(userId);
73 + if(!user || !user.userTypeCd) {
74 + ctx.status = 403;
75 + return;
76 + }
77 +
65 const { bottleId } = ctx.params; 78 const { bottleId } = ctx.params;
66 79
67 const bottle = await Bottle.findByBottleId(bottleId); 80 const bottle = await Bottle.findByBottleId(bottleId);
...@@ -97,6 +110,12 @@ exports.lookupInfo = async(ctx) => { ...@@ -97,6 +110,12 @@ exports.lookupInfo = async(ctx) => {
97 } 110 }
98 111
99 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 112 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
113 + const user = await User.findById(userId);
114 + if(!user || !user.userTypeCd) {
115 + ctx.status = 403;
116 + return;
117 + }
118 +
100 const { bottleId } = ctx.params; 119 const { bottleId } = ctx.params;
101 120
102 const isBottleExist = await Bottle.findByBottleId(bottleId); 121 const isBottleExist = await Bottle.findByBottleId(bottleId);
...@@ -133,6 +152,12 @@ exports.setMedicine = async(ctx) => { ...@@ -133,6 +152,12 @@ exports.setMedicine = async(ctx) => {
133 } 152 }
134 153
135 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 154 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
155 + const user = await User.findById(userId);
156 + if(!user || !user.userTypeCd) {
157 + ctx.status = 403;
158 + return;
159 + }
160 +
136 const { bottleId } = ctx.params; 161 const { bottleId } = ctx.params;
137 const { medicineId, dosage } = ctx.request.body; 162 const { medicineId, dosage } = ctx.request.body;
138 163
...@@ -173,6 +198,12 @@ exports.getBottleList = async(ctx) => { ...@@ -173,6 +198,12 @@ exports.getBottleList = async(ctx) => {
173 } 198 }
174 199
175 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 200 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
201 + const user = await User.findById(userId);
202 + if(!user || !user.userTypeCd) {
203 + ctx.status = 403;
204 + return;
205 + }
206 +
176 const { hubId } = ctx.params; 207 const { hubId } = ctx.params;
177 208
178 const hub = await Hub.findByHubId(hubId); 209 const hub = await Hub.findByHubId(hubId);
......
1 //허브(Mqtt Broker)등록 및 삭제 1 //허브(Mqtt Broker)등록 및 삭제
2 const Hub = require('../../models/hub'); 2 const Hub = require('../../models/hub');
3 +const User = require('../../models/user');
3 const Mqtt = require('../../lib/MqttModule'); 4 const Mqtt = require('../../lib/MqttModule');
4 const DataProcess = require('../../lib/DataProcess'); 5 const DataProcess = require('../../lib/DataProcess');
5 const jwt = require('jsonwebtoken'); 6 const jwt = require('jsonwebtoken');
...@@ -12,6 +13,12 @@ exports.hubConnect = async (ctx) => { ...@@ -12,6 +13,12 @@ exports.hubConnect = async (ctx) => {
12 } 13 }
13 14
14 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 15 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
16 + const user = await User.findById(userId);
17 + if(!user || !user.userTypeCd) {
18 + ctx.status = 403;
19 + return;
20 + }
21 +
15 const { hubId, host, port } = ctx.request.body; 22 const { hubId, host, port } = ctx.request.body;
16 23
17 const isExistHub = await Hub.findByHubId(hubId); 24 const isExistHub = await Hub.findByHubId(hubId);
...@@ -47,6 +54,12 @@ exports.getHubList = async(ctx) => { ...@@ -47,6 +54,12 @@ exports.getHubList = async(ctx) => {
47 } 54 }
48 55
49 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 56 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
57 + const user = await User.findById(userId);
58 + if(!user || !user.userTypeCd) {
59 + ctx.status = 403;
60 + return;
61 + }
62 +
50 const hubList = await Hub.find({ userId }); 63 const hubList = await Hub.find({ userId });
51 if(!hubList || !hubList.length) { 64 if(!hubList || !hubList.length) {
52 ctx.status = 404; 65 ctx.status = 404;
...@@ -65,6 +78,12 @@ exports.hubDisconnect = async(ctx) => { ...@@ -65,6 +78,12 @@ exports.hubDisconnect = async(ctx) => {
65 } 78 }
66 79
67 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 80 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
81 + const user = await User.findById(userId);
82 + if(!user || !user.userTypeCd) {
83 + ctx.status = 403;
84 + return;
85 + }
86 +
68 const { hubId } = ctx.params; 87 const { hubId } = ctx.params;
69 88
70 const hub = await Hub.findByHubId(hubId); 89 const hub = await Hub.findByHubId(hubId);
......
1 +const Router = require('koa-router');
2 +const userCtrl = require('./user.ctrl');
3 +
4 +const user = new Router();
5 +
6 +/**
7 + * 현재 유저 정보 조회
8 + * request parameter : token
9 + * url : http://localhost:4000/api/user
10 + * return : Object User
11 + */
12 +user.get('/', userCtrl.myInfo);
13 +
14 +/**
15 + * 현재 유저의 타입에 따라 요청 유저 정보 조회(의사 : 환자, 관리자 : 모든 유저)
16 + * request parameter : token
17 + * url : http://localhost:4000/api/user/:reqUserId
18 + * return : status
19 + */
20 + user.get('/:reqUserId', userCtrl.getUserDetail);
21 +
22 + /**
23 + * 현재 유저의 타입에 따라 요청 유저 정보 수정(의사 : 환자, 관리자 : 모든 유저)
24 + * request parameter : token
25 + * url : http://localhost:4000/api/user/:reqUserId
26 + * return : status
27 + */
28 +user.patch('/:reqUserId', userCtrl.updateReqUser);
29 +
1 +//유저에 관련된 Api
2 +const User = require('../../models/user')
3 +const Bottle = require('../../models/bottle')
4 +const Hub = require('../../models/hub')
5 +const jwt = require('jsonwebtoken')
6 +
7 +
8 +exports.myInfo = async ctx => {
9 + const token = ctx.req.headers.authorization
10 + if (!token || !token.length) {
11 + ctx.status = 401
12 + return
13 + }
14 +
15 + const { userId } = jwt.verify(token, process.env.JWT_SECRET)
16 + const user = await User.findById(userId);
17 + if(!user || !user.userTypeCd) {
18 + ctx.status = 403;
19 + return;
20 + }
21 +
22 + let result = {
23 + myInfo : user,
24 + myDoctor : null,
25 + patientList : [],
26 + userList : [],
27 + };
28 +
29 + if (user.userTypeCd === 'NORMAL') {
30 + const doctor = await User.findById(user.doctorId);
31 + result.myDoctor = doctor;
32 +
33 + } else if (user.userTypeCd === 'DOCTOR') {
34 + const patientList = await User.findAllByDoctorId(user.userId);
35 + result.patientList = patientList;
36 +
37 + } else if (user.userTypeCd === 'MANAGER') {
38 + const userList = await User.find();
39 + result.userList = userList;
40 + }
41 +
42 + ctx.status = 200;
43 + ctx.body = result;
44 +}
45 +
46 +exports.getUserDetail = async ctx => {
47 + const token = ctx.req.headers.authorization;
48 + if (!token || !token.length) {
49 + ctx.status = 401;
50 + return;
51 + }
52 +
53 + const { userId } = jwt.verify(token, process.env.JWT_SECRET);
54 + const user = await User.findById(userId);
55 + if(!user) {
56 + ctx.status = 403;
57 + return;
58 + } else if (user.userTypeCd === 'NORMAL') {
59 + ctx.status = 403;
60 + return;
61 + }
62 +
63 + let result = {
64 + reqUser : user,
65 + reqUserBottleList : [],
66 + };
67 +
68 + if (user.userTypeCd === 'DOCTOR') {
69 + const { reqUserId } = ctx.params;
70 + const reqUser = await User.findById(reqUserId);
71 + if (!reqUser) {
72 + ctx.status = 404;
73 + return;
74 + }
75 + if(reqUser.doctorId !== user.userId) {
76 + ctx.status = 403;
77 + return;
78 + }
79 +
80 + const reqUserHubList = await Hub.findAllByUserId(reqUserId);
81 + if(reqUserHubList && reqUserHubList.length) {
82 + const reqUserBottleList = [];
83 +
84 + await Promise.all(reqUserHubList.forEach(async hub => {
85 + const bottle = await Bottle.findAllByHubId(hub.hubId);
86 + reqUserBottleList.push(...bottle);
87 + }));
88 +
89 + result.reqUserBottleList = reqUserBottleList;
90 + }
91 +
92 + }
93 +
94 + ctx.status = 200;
95 + ctx.body = result;
96 +
97 +};
98 +
99 +exports.updateReqUser = async ctx => {
100 + const token = ctx.req.headers.authorization;
101 + if (!token || !token.length) {
102 + ctx.status = 401;
103 + return;
104 + }
105 +
106 + const { userId } = jwt.verify(token, process.env.JWT_SECRET);
107 + const user = await User.findById(userId);
108 + if(!user) {
109 + ctx.status = 403;
110 + return;
111 + }
112 +
113 + if (user.userTypeCd === 'MANAGER') {
114 + const { useYn } = ctx.request.body;
115 + const { reqUserId } = ctx.params;
116 +
117 + const reqUser = await User.findById(reqUserId);
118 + if(!reqUser) {
119 + ctx.status = 404;
120 + return;
121 + }
122 +
123 + await reqUser.setUseYn(useYn);
124 + await reqUser.save();
125 +
126 + return;
127 + }
128 +
129 + ctx.status = 200;
130 +
131 +}
...\ No newline at end of file ...\ No newline at end of file
1 -const mqtt = require('mqtt'); 1 +const mqtt = require('mqtt')
2 -const clientList = []; 2 +const clientList = []
3 3
4 exports.mqttOn = async (hosting, func) => { 4 exports.mqttOn = async (hosting, func) => {
5 const filterIndex = clientList.findIndex(client => { 5 const filterIndex = clientList.findIndex(client => {
6 return (client.options.clientId === hosting.clientId 6 return (client.options.clientId === hosting.clientId
7 && client.options.host === hosting.host 7 && client.options.host === hosting.host
8 && client.options.port === hosting.port) 8 && client.options.port === hosting.port)
9 - }); 9 + })
10 10
11 if(filterIndex === -1) { 11 if(filterIndex === -1) {
12 - const client = mqtt.connect(hosting); 12 + const client = mqtt.connect(hosting)
13 - clientList.push(client); 13 + clientList.push(client)
14 14
15 client.on('connect', () => { 15 client.on('connect', () => {
16 - console.log(`Hub connected: `, client.connected); 16 + console.log('Hub connected: ', client.connected)
17 - }); 17 + })
18 18
19 - client.on('message', async (topic, message, packet) => { 19 + client.on('message', async (topic, message) => {
20 - const result = await func(topic, message.toString()); 20 + const result = await func(topic, message.toString())
21 - console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m'); 21 + console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m')
22 - this.mqttPublishMessage(client, result); 22 + this.mqttPublishMessage(client, result)
23 - }); 23 + })
24 24
25 - return client; 25 + return client
26 } 26 }
27 27
28 - return clientList[filterIndex]; 28 + return clientList[filterIndex]
29 -}; 29 +}
30 30
31 exports.mqttSubscribe = (client, topic) => { 31 exports.mqttSubscribe = (client, topic) => {
32 - client.subscribe(topic); 32 + client.subscribe(topic)
33 -}; 33 +}
34 34
35 exports.mqttPublishMessage = (client, { topic, message }) => { 35 exports.mqttPublishMessage = (client, { topic, message }) => {
36 client.publish(topic, message, () => { 36 client.publish(topic, message, () => {
37 - console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m'); 37 + console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m')
38 - }); 38 + })
39 -}; 39 +}
40 40
41 exports.mqttUnsubscribe = (client, topic) => { 41 exports.mqttUnsubscribe = (client, topic) => {
42 client.unsubscribe(topic, () => { 42 client.unsubscribe(topic, () => {
43 - console.log('unsubscribe', topic); 43 + console.log('unsubscribe', topic)
44 - }); 44 + })
45 -}; 45 +}
46 46
47 exports.mqttOff = (hosting) => { 47 exports.mqttOff = (hosting) => {
48 const filterIndex = clientList.findIndex(client => { 48 const filterIndex = clientList.findIndex(client => {
49 return (client.options.clientId === hosting.clientId 49 return (client.options.clientId === hosting.clientId
50 && client.options.host === hosting.host 50 && client.options.host === hosting.host
51 && client.options.port === hosting.port) 51 && client.options.port === hosting.port)
52 - }); 52 + })
53 53
54 if(filterIndex !== -1) { 54 if(filterIndex !== -1) {
55 - clientList[filterIndex].end(); 55 + clientList[filterIndex].end()
56 - clientList.splice(filterIndex, 1); 56 + clientList.splice(filterIndex, 1)
57 } 57 }
58 } 58 }
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -7,16 +7,19 @@ const BottleSchema = new Schema ({ ...@@ -7,16 +7,19 @@ const BottleSchema = new Schema ({
7 temperature : { type : Number, default : 0 }, 7 temperature : { type : Number, default : 0 },
8 humidity : { type : Number, default : 0 }, 8 humidity : { type : Number, default : 0 },
9 balance : { type : Number, default : 0 }, 9 balance : { type : Number, default : 0 },
10 - recentOpen : { type : Date, default : Date.now },
11 medicineId : { type : Number, default : null, }, 10 medicineId : { type : Number, default : null, },
12 - hubId : Number, 11 + dosage : { type : Number, default : 0 },
13 - dosage : { type : Number, default : 0 } 12 + hubId : { type : Number, ref : 'Hub' },
14 }) 13 })
15 14
16 BottleSchema.statics.findByBottleId = function(bottleId) { 15 BottleSchema.statics.findByBottleId = function(bottleId) {
17 return this.findOne({ bottleId }); 16 return this.findOne({ bottleId });
18 }; 17 };
19 18
19 +BottleSchema.statics.findAllByHubId = function(hubId) {
20 + return this.find({ hubId });
21 +};
22 +
20 BottleSchema.methods.getBottleId = function() { 23 BottleSchema.methods.getBottleId = function() {
21 return this.bottleId; 24 return this.bottleId;
22 }; 25 };
...@@ -49,4 +52,12 @@ BottleSchema.methods.getHubId = function() { ...@@ -49,4 +52,12 @@ BottleSchema.methods.getHubId = function() {
49 return this.hubId; 52 return this.hubId;
50 }; 53 };
51 54
55 +BottleSchema.methods.setMedicineId = function(medicineId) {
56 + this.medicineId = medicineId;
57 +};
58 +
59 +BottleSchema.statics.setDosage = function(dosage) {
60 + this.dosage = dosage;
61 +};
62 +
52 module.exports = mongoose.model('Bottle', BottleSchema); 63 module.exports = mongoose.model('Bottle', BottleSchema);
...\ No newline at end of file ...\ No newline at end of file
......
1 +const mongoose = require('mongoose');
2 +
3 +const Schema = mongoose.Schema;
4 +
5 +const TakeMedicineHistorySchema = new Schema ({
6 + takeDate : {
7 + type : Date,
8 + required : true,
9 + default : Date.now,
10 + },
11 + medicineId : {
12 + type : Number,
13 + ref : 'Medicine',
14 + required : true,
15 + },
16 + bottleId : {
17 + type : Number,
18 + ref : 'Bottle',
19 + required : true,
20 + },
21 +});
22 +
23 +TakeMedicineHistorySchema.statics.findByBottleId = async function(bottleId) {
24 + return this.find({ bottleId });
25 +};
26 +
27 +TakeMedicineHistorySchema.statics.findByBottleIdAndMedicineId = async function(bottleId, medicineId) {
28 + return this.find({ bottleId, medicineId });
29 +};
30 +
31 +
32 +module.export = mongoose.model("TakeMedicineHist", TakeMedicineHistorySchema);
...\ No newline at end of file ...\ No newline at end of file
...@@ -5,13 +5,17 @@ const Schema = mongoose.Schema; ...@@ -5,13 +5,17 @@ const Schema = mongoose.Schema;
5 const HubSchema = new Schema ({ 5 const HubSchema = new Schema ({
6 hubId : { type : Number, required : true, unique : true }, 6 hubId : { type : Number, required : true, unique : true },
7 hosting : { type : Object, default : null }, 7 hosting : { type : Object, default : null },
8 - userId : { type : String, default : null }, 8 + userId : { type : String, default : null, ref : 'User' },
9 }); 9 });
10 10
11 HubSchema.statics.findByHubId = function(hubId) { 11 HubSchema.statics.findByHubId = function(hubId) {
12 return this.findOne({ hubId }) 12 return this.findOne({ hubId })
13 }; 13 };
14 14
15 +HubSchema.statics.findAllByUserId = function(userId) {
16 + return this.find({ userId });
17 +};
18 +
15 HubSchema.methods.setHubHost = function(hosting) { 19 HubSchema.methods.setHubHost = function(hosting) {
16 this.hosting = hosting; 20 this.hosting = hosting;
17 }; 21 };
......
...@@ -5,9 +5,9 @@ const Schema = mongoose.Schema; ...@@ -5,9 +5,9 @@ const Schema = mongoose.Schema;
5 const MedicineSchema = new Schema ({ 5 const MedicineSchema = new Schema ({
6 medicineId : { type : Number, required : true, unique : true }, 6 medicineId : { type : Number, required : true, unique : true },
7 name : { type : String, required : true }, 7 name : { type : String, required : true },
8 - company : String, 8 + company : { type : String, required : true },
9 target : { type : String, required : true }, 9 target : { type : String, required : true },
10 - dosage : { type : String, required : true }, 10 + dosageInfo : { type : String, required : true },
11 warn : { type : String, required : true }, 11 warn : { type : String, required : true },
12 antiEffect : { type : String, required : true } 12 antiEffect : { type : String, required : true }
13 }) 13 })
......
...@@ -4,9 +4,12 @@ const jwt = require('jsonwebtoken'); ...@@ -4,9 +4,12 @@ const jwt = require('jsonwebtoken');
4 4
5 const Schema = mongoose.Schema; 5 const Schema = mongoose.Schema;
6 6
7 -const UserSchema = new Schema({ 7 +const UserSchema = new Schema ({
8 - userId : { type: String, require : true, unique : true, lowercase : true }, 8 + userId : { type: String, required : true, unique : true, lowercase : true },
9 - hashedPassword : { type : String, default : null } 9 + hashedPassword : { type : String, required : true },
10 + userTypeCd : { type : String, required : true, default : 'NORMAL' },
11 + doctorId : { type : String, default : null },
12 + useYn : { type : Boolean, default : true },
10 }); 13 });
11 14
12 UserSchema.methods.setPassword = async function(password) { 15 UserSchema.methods.setPassword = async function(password) {
...@@ -19,10 +22,22 @@ UserSchema.methods.checkPassword = async function(password) { ...@@ -19,10 +22,22 @@ UserSchema.methods.checkPassword = async function(password) {
19 return result; 22 return result;
20 }; 23 };
21 24
25 +UserSchema.methods.setUseYn = async function(useYn) {
26 + this.useYn = useYn;
27 +}
28 +
22 UserSchema.statics.findByUserId = async function(userId) { 29 UserSchema.statics.findByUserId = async function(userId) {
23 return this.findOne({ userId }); 30 return this.findOne({ userId });
24 }; 31 };
25 32
33 +UserSchema.statics.findAllByDoctorId = async function(doctorId) {
34 + return this.find({ doctorId });
35 +};
36 +
37 +UserSchema.statics.findAllByUserTypeCd = async function(userTypeCd) {
38 + return this.find({ userTypeCd });
39 +};
40 +
26 UserSchema.methods.generateToken = function() { 41 UserSchema.methods.generateToken = function() {
27 const token = jwt.sign ( 42 const token = jwt.sign (
28 { 43 {
......