2017-07-05 17:47:51 +08:00
|
|
|
import yapi from '../yapi.js'
|
2017-07-10 11:56:53 +08:00
|
|
|
import projectModel from '../models/project.js'
|
2017-07-11 12:12:43 +08:00
|
|
|
import userModel from '../models/user.js'
|
|
|
|
const jwt = require('jsonwebtoken');
|
|
|
|
|
|
|
|
|
2017-07-05 17:47:51 +08:00
|
|
|
class baseController{
|
|
|
|
constructor(ctx){
|
2017-07-11 12:12:43 +08:00
|
|
|
|
|
|
|
}
|
2017-07-10 11:11:35 +08:00
|
|
|
|
2017-07-11 12:12:43 +08:00
|
|
|
async init(ctx){
|
|
|
|
this.$user = null;
|
|
|
|
if(ctx.path === '/user/login' || ctx.path === '/user/reg' || ctx.path === '/user/status'){
|
|
|
|
this.$auth = true;
|
|
|
|
}else{
|
|
|
|
await this.checkLogin(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2017-07-10 11:11:35 +08:00
|
|
|
|
2017-07-11 12:12:43 +08:00
|
|
|
getUid(ctx){
|
|
|
|
return this.$uid;
|
2017-07-05 17:47:51 +08:00
|
|
|
}
|
|
|
|
|
2017-07-11 12:12:43 +08:00
|
|
|
async checkLogin(ctx){
|
|
|
|
let token = ctx.cookies.get('_yapi_token');
|
|
|
|
let uid = ctx.cookies.get('_yapi_uid');
|
|
|
|
try{
|
|
|
|
if(!token || !uid) return false;
|
|
|
|
let userInst = yapi.getInst(userModel); //创建user实体
|
|
|
|
let result = await userInst.findById(uid);
|
|
|
|
let decoded = jwt.verify(token, result.passsalt)
|
|
|
|
if(decoded.uid == uid){
|
|
|
|
this.$uid = uid;
|
|
|
|
this.$auth = true;
|
|
|
|
console.log(11111)
|
|
|
|
this.$user = result;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}catch(e){
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2017-07-05 17:47:51 +08:00
|
|
|
}
|
|
|
|
|
2017-07-11 12:12:43 +08:00
|
|
|
async getLoginStatus(ctx){
|
|
|
|
if(await this.checkLogin(ctx) === true){
|
|
|
|
return ctx.body = yapi.commons.resReturn(yapi.commons.fieldSelect(this.$user,['_id','username','email', 'up_time', 'add_time']));
|
|
|
|
}
|
|
|
|
return ctx.body = yapi.commons.resReturn(null, 400 , 'Please login.');
|
2017-07-06 20:55:02 +08:00
|
|
|
|
2017-07-05 17:47:51 +08:00
|
|
|
}
|
2017-07-06 19:21:54 +08:00
|
|
|
|
|
|
|
getRole(){
|
|
|
|
return 'admin'
|
|
|
|
}
|
2017-07-10 11:56:53 +08:00
|
|
|
|
|
|
|
async jungeProjectAuth(id){
|
|
|
|
let model = yapi.getInst(projectModel);
|
|
|
|
if(this.getRole() === 'admin') return true;
|
|
|
|
if(!id) return false;
|
|
|
|
let result = await model.get(id);
|
|
|
|
if(result.uid === this.getUid()){
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
async jungeMemberAuth(id, member_uid){
|
|
|
|
let model = yapi.getInst(projectModel);
|
|
|
|
if(this.getRole() === 'admin') return true;
|
|
|
|
if(!id || !member_uid) return false;
|
|
|
|
let result = await model.checkMemberRepeat(id, member_uid);
|
|
|
|
if(result > 0){
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
2017-07-05 17:47:51 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = baseController
|