박권수

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

{
"extends": "eslint:recommended",
"rules": {
"semi": ["warn", "never"],
"quotes": ["warn", "single"],
"no-console": ["off"]
},
"parserOptions": {
"ecmaVersion": 9
},
"env": {
"es6": true,
"node": true,
"browser": true,
"amd": true
},
"globals": {
"$": true,
"require": true,
"process": true
},
"root": true
}
\ No newline at end of file
......@@ -2,6 +2,7 @@
const User = require('../../models/user');
const Joi = require('joi');
exports.register = async(ctx) => {
const { userId, password, passwordCheck } = ctx.request.body;
......@@ -49,7 +50,7 @@ exports.login = async(ctx) => {
}
const user = await User.findByUserId(userId);
if(!user) {
if(!user || !user.userTypeCd) {
ctx.stauts = 401;
return;
}
......
......@@ -2,6 +2,7 @@
const Bottle = require('../../models/bottle');
const Hub = require('../../models/hub');
const Medicine = require('../../models/medicine');
const User = require('../../models/user');
const Mqtt = require('../../lib/MqttModule');
const jwt = require('jsonwebtoken');
......@@ -14,6 +15,12 @@ exports.bottleConnect = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { bottleId, hubId } = ctx.request.body;
const isExistBottle = await Bottle.findByBottleId(bottleId);
......@@ -62,6 +69,12 @@ exports.bottleDisconnect = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { bottleId } = ctx.params;
const bottle = await Bottle.findByBottleId(bottleId);
......@@ -97,6 +110,12 @@ exports.lookupInfo = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { bottleId } = ctx.params;
const isBottleExist = await Bottle.findByBottleId(bottleId);
......@@ -133,6 +152,12 @@ exports.setMedicine = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { bottleId } = ctx.params;
const { medicineId, dosage } = ctx.request.body;
......@@ -173,6 +198,12 @@ exports.getBottleList = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { hubId } = ctx.params;
const hub = await Hub.findByHubId(hubId);
......
//허브(Mqtt Broker)등록 및 삭제
const Hub = require('../../models/hub');
const User = require('../../models/user');
const Mqtt = require('../../lib/MqttModule');
const DataProcess = require('../../lib/DataProcess');
const jwt = require('jsonwebtoken');
......@@ -12,6 +13,12 @@ exports.hubConnect = async (ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { hubId, host, port } = ctx.request.body;
const isExistHub = await Hub.findByHubId(hubId);
......@@ -47,6 +54,12 @@ exports.getHubList = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const hubList = await Hub.find({ userId });
if(!hubList || !hubList.length) {
ctx.status = 404;
......@@ -65,6 +78,12 @@ exports.hubDisconnect = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { hubId } = ctx.params;
const hub = await Hub.findByHubId(hubId);
......
const Router = require('koa-router');
const userCtrl = require('./user.ctrl');
const user = new Router();
/**
* 현재 유저 정보 조회
* request parameter : token
* url : http://localhost:4000/api/user
* return : Object User
*/
user.get('/', userCtrl.myInfo);
/**
* 현재 유저의 타입에 따라 요청 유저 정보 조회(의사 : 환자, 관리자 : 모든 유저)
* request parameter : token
* url : http://localhost:4000/api/user/:reqUserId
* return : status
*/
user.get('/:reqUserId', userCtrl.getUserDetail);
/**
* 현재 유저의 타입에 따라 요청 유저 정보 수정(의사 : 환자, 관리자 : 모든 유저)
* request parameter : token
* url : http://localhost:4000/api/user/:reqUserId
* return : status
*/
user.patch('/:reqUserId', userCtrl.updateReqUser);
//유저에 관련된 Api
const User = require('../../models/user')
const Bottle = require('../../models/bottle')
const Hub = require('../../models/hub')
const jwt = require('jsonwebtoken')
exports.myInfo = async ctx => {
const token = ctx.req.headers.authorization
if (!token || !token.length) {
ctx.status = 401
return
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET)
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
let result = {
myInfo : user,
myDoctor : null,
patientList : [],
userList : [],
};
if (user.userTypeCd === 'NORMAL') {
const doctor = await User.findById(user.doctorId);
result.myDoctor = doctor;
} else if (user.userTypeCd === 'DOCTOR') {
const patientList = await User.findAllByDoctorId(user.userId);
result.patientList = patientList;
} else if (user.userTypeCd === 'MANAGER') {
const userList = await User.find();
result.userList = userList;
}
ctx.status = 200;
ctx.body = result;
}
exports.getUserDetail = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user) {
ctx.status = 403;
return;
} else if (user.userTypeCd === 'NORMAL') {
ctx.status = 403;
return;
}
let result = {
reqUser : user,
reqUserBottleList : [],
};
if (user.userTypeCd === 'DOCTOR') {
const { reqUserId } = ctx.params;
const reqUser = await User.findById(reqUserId);
if (!reqUser) {
ctx.status = 404;
return;
}
if(reqUser.doctorId !== user.userId) {
ctx.status = 403;
return;
}
const reqUserHubList = await Hub.findAllByUserId(reqUserId);
if(reqUserHubList && reqUserHubList.length) {
const reqUserBottleList = [];
await Promise.all(reqUserHubList.forEach(async hub => {
const bottle = await Bottle.findAllByHubId(hub.hubId);
reqUserBottleList.push(...bottle);
}));
result.reqUserBottleList = reqUserBottleList;
}
}
ctx.status = 200;
ctx.body = result;
};
exports.updateReqUser = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user) {
ctx.status = 403;
return;
}
if (user.userTypeCd === 'MANAGER') {
const { useYn } = ctx.request.body;
const { reqUserId } = ctx.params;
const reqUser = await User.findById(reqUserId);
if(!reqUser) {
ctx.status = 404;
return;
}
await reqUser.setUseYn(useYn);
await reqUser.save();
return;
}
ctx.status = 200;
}
\ No newline at end of file
const mqtt = require('mqtt');
const clientList = [];
const mqtt = require('mqtt')
const clientList = []
exports.mqttOn = async (hosting, func) => {
const filterIndex = clientList.findIndex(client => {
return (client.options.clientId === hosting.clientId
&& client.options.host === hosting.host
&& client.options.port === hosting.port)
});
})
if(filterIndex === -1) {
const client = mqtt.connect(hosting);
clientList.push(client);
const client = mqtt.connect(hosting)
clientList.push(client)
client.on('connect', () => {
console.log(`Hub connected: `, client.connected);
});
client.on('message', async (topic, message, packet) => {
const result = await func(topic, message.toString());
console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m');
this.mqttPublishMessage(client, result);
});
console.log('Hub connected: ', client.connected)
})
client.on('message', async (topic, message) => {
const result = await func(topic, message.toString())
console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m')
this.mqttPublishMessage(client, result)
})
return client;
return client
}
return clientList[filterIndex];
};
return clientList[filterIndex]
}
exports.mqttSubscribe = (client, topic) => {
client.subscribe(topic);
};
client.subscribe(topic)
}
exports.mqttPublishMessage = (client, { topic, message }) => {
client.publish(topic, message, () => {
console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m');
});
};
console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m')
})
}
exports.mqttUnsubscribe = (client, topic) => {
client.unsubscribe(topic, () => {
console.log('unsubscribe', topic);
});
};
console.log('unsubscribe', topic)
})
}
exports.mqttOff = (hosting) => {
const filterIndex = clientList.findIndex(client => {
return (client.options.clientId === hosting.clientId
&& client.options.host === hosting.host
&& client.options.port === hosting.port)
});
})
if(filterIndex !== -1) {
clientList[filterIndex].end();
clientList.splice(filterIndex, 1);
clientList[filterIndex].end()
clientList.splice(filterIndex, 1)
}
}
\ No newline at end of file
......
......@@ -7,16 +7,19 @@ const BottleSchema = new Schema ({
temperature : { type : Number, default : 0 },
humidity : { type : Number, default : 0 },
balance : { type : Number, default : 0 },
recentOpen : { type : Date, default : Date.now },
medicineId : { type : Number, default : null, },
hubId : Number,
dosage : { type : Number, default : 0 }
dosage : { type : Number, default : 0 },
hubId : { type : Number, ref : 'Hub' },
})
BottleSchema.statics.findByBottleId = function(bottleId) {
return this.findOne({ bottleId });
};
BottleSchema.statics.findAllByHubId = function(hubId) {
return this.find({ hubId });
};
BottleSchema.methods.getBottleId = function() {
return this.bottleId;
};
......@@ -49,4 +52,12 @@ BottleSchema.methods.getHubId = function() {
return this.hubId;
};
BottleSchema.methods.setMedicineId = function(medicineId) {
this.medicineId = medicineId;
};
BottleSchema.statics.setDosage = function(dosage) {
this.dosage = dosage;
};
module.exports = mongoose.model('Bottle', BottleSchema);
\ No newline at end of file
......
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TakeMedicineHistorySchema = new Schema ({
takeDate : {
type : Date,
required : true,
default : Date.now,
},
medicineId : {
type : Number,
ref : 'Medicine',
required : true,
},
bottleId : {
type : Number,
ref : 'Bottle',
required : true,
},
});
TakeMedicineHistorySchema.statics.findByBottleId = async function(bottleId) {
return this.find({ bottleId });
};
TakeMedicineHistorySchema.statics.findByBottleIdAndMedicineId = async function(bottleId, medicineId) {
return this.find({ bottleId, medicineId });
};
module.export = mongoose.model("TakeMedicineHist", TakeMedicineHistorySchema);
\ No newline at end of file
......@@ -5,13 +5,17 @@ const Schema = mongoose.Schema;
const HubSchema = new Schema ({
hubId : { type : Number, required : true, unique : true },
hosting : { type : Object, default : null },
userId : { type : String, default : null },
userId : { type : String, default : null, ref : 'User' },
});
HubSchema.statics.findByHubId = function(hubId) {
return this.findOne({ hubId })
};
HubSchema.statics.findAllByUserId = function(userId) {
return this.find({ userId });
};
HubSchema.methods.setHubHost = function(hosting) {
this.hosting = hosting;
};
......
......@@ -5,9 +5,9 @@ const Schema = mongoose.Schema;
const MedicineSchema = new Schema ({
medicineId : { type : Number, required : true, unique : true },
name : { type : String, required : true },
company : String,
company : { type : String, required : true },
target : { type : String, required : true },
dosage : { type : String, required : true },
dosageInfo : { type : String, required : true },
warn : { type : String, required : true },
antiEffect : { type : String, required : true }
})
......
......@@ -4,9 +4,12 @@ const jwt = require('jsonwebtoken');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userId : { type: String, require : true, unique : true, lowercase : true },
hashedPassword : { type : String, default : null }
const UserSchema = new Schema ({
userId : { type: String, required : true, unique : true, lowercase : true },
hashedPassword : { type : String, required : true },
userTypeCd : { type : String, required : true, default : 'NORMAL' },
doctorId : { type : String, default : null },
useYn : { type : Boolean, default : true },
});
UserSchema.methods.setPassword = async function(password) {
......@@ -19,10 +22,22 @@ UserSchema.methods.checkPassword = async function(password) {
return result;
};
UserSchema.methods.setUseYn = async function(useYn) {
this.useYn = useYn;
}
UserSchema.statics.findByUserId = async function(userId) {
return this.findOne({ userId });
};
UserSchema.statics.findAllByDoctorId = async function(doctorId) {
return this.find({ doctorId });
};
UserSchema.statics.findAllByUserTypeCd = async function(userTypeCd) {
return this.find({ userTypeCd });
};
UserSchema.methods.generateToken = function() {
const token = jwt.sign (
{
......