fork from bc4552c5a8
This commit is contained in:
317
server/controllers/base.js
Normal file
317
server/controllers/base.js
Normal file
@@ -0,0 +1,317 @@
|
||||
const yapi = require('../yapi.js');
|
||||
const projectModel = require('../models/project.js');
|
||||
const userModel = require('../models/user.js');
|
||||
const interfaceModel = require('../models/interface.js');
|
||||
const groupModel = require('../models/group.js');
|
||||
const tokenModel = require('../models/token.js');
|
||||
const _ = require('underscore');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const {parseToken} = require('../utils/token')
|
||||
|
||||
class baseController {
|
||||
constructor(ctx) {
|
||||
this.ctx = ctx;
|
||||
//网站上线后,role对象key是不能修改的,value可以修改
|
||||
this.roles = {
|
||||
admin: 'Admin',
|
||||
member: '网站会员'
|
||||
};
|
||||
}
|
||||
|
||||
async init(ctx) {
|
||||
this.$user = null;
|
||||
this.tokenModel = yapi.getInst(tokenModel);
|
||||
this.projectModel = yapi.getInst(projectModel);
|
||||
let ignoreRouter = [
|
||||
'/api/user/login_by_token',
|
||||
'/api/user/login',
|
||||
'/api/user/reg',
|
||||
'/api/user/status',
|
||||
'/api/user/logout',
|
||||
'/api/user/avatar',
|
||||
'/api/user/login_by_ldap'
|
||||
];
|
||||
if (ignoreRouter.indexOf(ctx.path) > -1) {
|
||||
this.$auth = true;
|
||||
} else {
|
||||
await this.checkLogin(ctx);
|
||||
}
|
||||
|
||||
let openApiRouter = [
|
||||
'/api/open/run_auto_test',
|
||||
'/api/open/import_data',
|
||||
'/api/interface/add',
|
||||
'/api/interface/save',
|
||||
'/api/interface/up',
|
||||
'/api/interface/get',
|
||||
'/api/interface/list',
|
||||
'/api/interface/list_menu',
|
||||
'/api/interface/add_cat',
|
||||
'/api/interface/getCatMenu',
|
||||
'/api/interface/list_cat',
|
||||
'/api/project/get',
|
||||
'/api/plugin/export',
|
||||
'/api/project/up',
|
||||
'/api/plugin/exportSwagger'
|
||||
];
|
||||
|
||||
let params = Object.assign({}, ctx.query, ctx.request.body);
|
||||
let token = params.token;
|
||||
|
||||
// 如果前缀是 /api/open,执行 parse token 逻辑
|
||||
if (token && typeof token === 'string' && (openApiRouter.indexOf(ctx.path) > -1 || ctx.path.indexOf('/api/open/') === 0 )) {
|
||||
|
||||
let tokens = parseToken(token)
|
||||
|
||||
const oldTokenUid = '999999'
|
||||
|
||||
let tokenUid = oldTokenUid;
|
||||
|
||||
if(!tokens){
|
||||
let checkId = await this.getProjectIdByToken(token);
|
||||
if(!checkId)return;
|
||||
}else{
|
||||
token = tokens.projectToken;
|
||||
tokenUid = tokens.uid;
|
||||
}
|
||||
|
||||
// if (this.$auth) {
|
||||
// ctx.params.project_id = await this.getProjectIdByToken(token);
|
||||
|
||||
// if (!ctx.params.project_id) {
|
||||
// return (this.$tokenAuth = false);
|
||||
// }
|
||||
// return (this.$tokenAuth = true);
|
||||
// }
|
||||
|
||||
let checkId = await this.getProjectIdByToken(token);
|
||||
if(!checkId){
|
||||
ctx.body = yapi.commons.resReturn(null, 42014, 'token 无效');
|
||||
}
|
||||
let projectData = await this.projectModel.get(checkId);
|
||||
if (projectData) {
|
||||
ctx.query.pid = checkId; // 兼容:/api/plugin/export
|
||||
ctx.params.project_id = checkId;
|
||||
this.$tokenAuth = true;
|
||||
this.$uid = tokenUid;
|
||||
let result;
|
||||
if(tokenUid === oldTokenUid){
|
||||
result = {
|
||||
_id: tokenUid,
|
||||
role: 'member',
|
||||
username: 'system'
|
||||
}
|
||||
}else{
|
||||
let userInst = yapi.getInst(userModel); //创建user实体
|
||||
result = await userInst.findById(tokenUid);
|
||||
}
|
||||
|
||||
this.$user = result;
|
||||
this.$auth = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getProjectIdByToken(token) {
|
||||
let projectId = await this.tokenModel.findId(token);
|
||||
if (projectId) {
|
||||
return projectId.toObject().project_id;
|
||||
}
|
||||
}
|
||||
|
||||
getUid() {
|
||||
return parseInt(this.$uid, 10);
|
||||
}
|
||||
|
||||
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);
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let decoded;
|
||||
try {
|
||||
decoded = jwt.verify(token, result.passsalt);
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (decoded.uid == uid) {
|
||||
this.$uid = uid;
|
||||
this.$auth = true;
|
||||
this.$user = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (e) {
|
||||
yapi.commons.log(e, 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async checkRegister() {
|
||||
// console.log('config', yapi.WEBCONFIG);
|
||||
if (yapi.WEBCONFIG.closeRegister) {
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
async checkLDAP() {
|
||||
// console.log('config', yapi.WEBCONFIG);
|
||||
if (!yapi.WEBCONFIG.ldapLogin) {
|
||||
return false;
|
||||
} else {
|
||||
return yapi.WEBCONFIG.ldapLogin.enable || false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param {*} ctx
|
||||
*/
|
||||
|
||||
async getLoginStatus(ctx) {
|
||||
let body;
|
||||
if ((await this.checkLogin(ctx)) === true) {
|
||||
let result = yapi.commons.fieldSelect(this.$user, [
|
||||
'_id',
|
||||
'username',
|
||||
'email',
|
||||
'up_time',
|
||||
'add_time',
|
||||
'role',
|
||||
'type',
|
||||
'study'
|
||||
]);
|
||||
body = yapi.commons.resReturn(result);
|
||||
} else {
|
||||
body = yapi.commons.resReturn(null, 40011, '请登录...');
|
||||
}
|
||||
|
||||
body.ladp = await this.checkLDAP();
|
||||
body.canRegister = await this.checkRegister();
|
||||
ctx.body = body;
|
||||
}
|
||||
|
||||
getRole() {
|
||||
return this.$user.role;
|
||||
}
|
||||
|
||||
getUsername() {
|
||||
return this.$user.username;
|
||||
}
|
||||
|
||||
getEmail() {
|
||||
return this.$user.email;
|
||||
}
|
||||
|
||||
async getProjectRole(id, type) {
|
||||
let result = {};
|
||||
try {
|
||||
if (this.getRole() === 'admin') {
|
||||
return 'admin';
|
||||
}
|
||||
if (type === 'interface') {
|
||||
let interfaceInst = yapi.getInst(interfaceModel);
|
||||
let interfaceData = await interfaceInst.get(id);
|
||||
result.interfaceData = interfaceData;
|
||||
// 项目创建者相当于 owner
|
||||
if (interfaceData.uid === this.getUid()) {
|
||||
return 'owner';
|
||||
}
|
||||
type = 'project';
|
||||
id = interfaceData.project_id;
|
||||
}
|
||||
|
||||
if (type === 'project') {
|
||||
let projectInst = yapi.getInst(projectModel);
|
||||
let projectData = await projectInst.get(id);
|
||||
if (projectData.uid === this.getUid()) {
|
||||
// 建立项目的人
|
||||
return 'owner';
|
||||
}
|
||||
let memberData = _.find(projectData.members, m => {
|
||||
if (m && m.uid === this.getUid()) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
if (memberData && memberData.role) {
|
||||
if (memberData.role === 'owner') {
|
||||
return 'owner';
|
||||
} else if (memberData.role === 'dev') {
|
||||
return 'dev';
|
||||
} else {
|
||||
return 'guest';
|
||||
}
|
||||
}
|
||||
type = 'group';
|
||||
id = projectData.group_id;
|
||||
}
|
||||
|
||||
if (type === 'group') {
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
let groupData = await groupInst.get(id);
|
||||
// 建立分组的人
|
||||
if (groupData.uid === this.getUid()) {
|
||||
return 'owner';
|
||||
}
|
||||
|
||||
let groupMemberData = _.find(groupData.members, m => {
|
||||
if (m.uid === this.getUid()) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
if (groupMemberData && groupMemberData.role) {
|
||||
if (groupMemberData.role === 'owner') {
|
||||
return 'owner';
|
||||
} else if (groupMemberData.role === 'dev') {
|
||||
return 'dev';
|
||||
} else {
|
||||
return 'guest';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 'member';
|
||||
} catch (e) {
|
||||
yapi.commons.log(e, 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 身份验证
|
||||
* @param {*} id type对应的id
|
||||
* @param {*} type enum[interface, project, group]
|
||||
* @param {*} action enum[ danger, edit, view ] danger只有owner或管理员才能操作,edit只要是dev或以上就能执行
|
||||
*/
|
||||
async checkAuth(id, type, action) {
|
||||
let role = await this.getProjectRole(id, type);
|
||||
|
||||
if (action === 'danger') {
|
||||
if (role === 'admin' || role === 'owner') {
|
||||
return true;
|
||||
}
|
||||
} else if (action === 'edit') {
|
||||
if (role === 'admin' || role === 'owner' || role === 'dev') {
|
||||
return true;
|
||||
}
|
||||
} else if (action === 'view') {
|
||||
if (role === 'admin' || role === 'owner' || role === 'dev' || role === 'guest') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = baseController;
|
||||
135
server/controllers/follow.js
Normal file
135
server/controllers/follow.js
Normal file
@@ -0,0 +1,135 @@
|
||||
const yapi = require('../yapi.js');
|
||||
const baseController = require('./base.js');
|
||||
const followModel = require('../models/follow');
|
||||
const projectModel = require('../models/project');
|
||||
|
||||
class followController extends baseController {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
this.Model = yapi.getInst(followModel);
|
||||
this.projectModel = yapi.getInst(projectModel);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取关注项目列表
|
||||
* @interface /follow/list
|
||||
* @method GET
|
||||
* @category follow
|
||||
* @foldnumber 10
|
||||
* @param {Number} [page] 分页页码
|
||||
* @param {Number} [limit] 分页大小
|
||||
* @returns {Object}
|
||||
* @example /follow/list
|
||||
*/
|
||||
|
||||
async list(ctx) {
|
||||
let uid = this.getUid();
|
||||
// 关注列表暂时不分页 page & limit 为分页配置
|
||||
// page = ctx.request.query.page || 1,
|
||||
// limit = ctx.request.query.limit || 10;
|
||||
|
||||
if (!uid) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '用户id不能为空'));
|
||||
}
|
||||
|
||||
try {
|
||||
let result = await this.Model.list(uid);
|
||||
|
||||
ctx.body = yapi.commons.resReturn({
|
||||
list: result
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消关注
|
||||
* @interface /follow/del
|
||||
* @method POST
|
||||
* @category follow
|
||||
* @foldnumber 10
|
||||
* @param {Number} projectid
|
||||
* @returns {Object}
|
||||
* @example /follow/del
|
||||
*/
|
||||
|
||||
async del(ctx) {
|
||||
let params = ctx.request.body,
|
||||
uid = this.getUid();
|
||||
|
||||
if (!params.projectid) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
|
||||
}
|
||||
|
||||
let checkRepeat = await this.Model.checkProjectRepeat(uid, params.projectid);
|
||||
|
||||
if (checkRepeat == 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, '项目未关注'));
|
||||
}
|
||||
|
||||
try {
|
||||
let result = await this.Model.del(params.projectid, this.getUid());
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加关注
|
||||
* @interface /follow/add
|
||||
* @method GET
|
||||
* @category follow
|
||||
* @foldnumber 10
|
||||
* @param {Number} projectid 项目id
|
||||
* @param {String} projectname 项目名
|
||||
* @param {String} icon 项目icon
|
||||
* @returns {Object}
|
||||
* @example /follow/add
|
||||
*/
|
||||
|
||||
async add(ctx) {
|
||||
let params = ctx.request.body;
|
||||
params = yapi.commons.handleParams(params, {
|
||||
projectid: 'number'
|
||||
});
|
||||
|
||||
let uid = this.getUid();
|
||||
|
||||
if (!params.projectid) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
|
||||
}
|
||||
|
||||
let checkRepeat = await this.Model.checkProjectRepeat(uid, params.projectid);
|
||||
|
||||
if (checkRepeat) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, '项目已关注'));
|
||||
}
|
||||
|
||||
try {
|
||||
let project = await this.projectModel.get(params.projectid);
|
||||
let data = {
|
||||
uid: uid,
|
||||
projectid: params.projectid,
|
||||
projectname: project.name,
|
||||
icon: project.icon,
|
||||
color: project.color
|
||||
};
|
||||
let result = await this.Model.save(data);
|
||||
result = yapi.commons.fieldSelect(result, [
|
||||
'_id',
|
||||
'uid',
|
||||
'projectid',
|
||||
'projectname',
|
||||
'icon',
|
||||
'color'
|
||||
]);
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = followController;
|
||||
534
server/controllers/group.js
Normal file
534
server/controllers/group.js
Normal file
@@ -0,0 +1,534 @@
|
||||
const groupModel = require('../models/group.js');
|
||||
const yapi = require('../yapi.js');
|
||||
const baseController = require('./base.js');
|
||||
const projectModel = require('../models/project.js');
|
||||
const userModel = require('../models/user.js');
|
||||
const interfaceModel = require('../models/interface.js');
|
||||
const interfaceColModel = require('../models/interfaceCol.js');
|
||||
const interfaceCaseModel = require('../models/interfaceCase.js');
|
||||
const _ = require('underscore')
|
||||
|
||||
const rolename = {
|
||||
owner: '组长',
|
||||
dev: '开发者',
|
||||
guest: '访客'
|
||||
};
|
||||
|
||||
class groupController extends baseController {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
|
||||
const id = 'number';
|
||||
const group_name = {
|
||||
type: 'string',
|
||||
minLength: 1
|
||||
};
|
||||
|
||||
const group_desc = 'string';
|
||||
const role = {
|
||||
type: 'string',
|
||||
enum: ['owner', 'dev', 'guest']
|
||||
};
|
||||
|
||||
const member_uids = {
|
||||
type: 'array',
|
||||
items: 'number',
|
||||
minItems: 1
|
||||
};
|
||||
|
||||
this.schemaMap = {
|
||||
get: {
|
||||
'*id': id
|
||||
},
|
||||
add: {
|
||||
'*group_name': group_name,
|
||||
group_desc: group_desc,
|
||||
owner_uids: ['number']
|
||||
},
|
||||
addMember: {
|
||||
'*id': id,
|
||||
role: role,
|
||||
'*member_uids': member_uids
|
||||
},
|
||||
changeMemberRole: {
|
||||
'*member_uid': 'number',
|
||||
'*id': id,
|
||||
role: role
|
||||
},
|
||||
getMemberList: {
|
||||
'*id': id
|
||||
},
|
||||
delMember: {
|
||||
'*id': id,
|
||||
'*member_uid': 'number'
|
||||
},
|
||||
del: {
|
||||
'*id': id
|
||||
},
|
||||
up: {
|
||||
'*id': id,
|
||||
'*group_name': group_name,
|
||||
group_desc: group_desc,
|
||||
custom_field1: {
|
||||
name: 'string',
|
||||
enable: 'boolen'
|
||||
},
|
||||
custom_field2: {
|
||||
name: 'string',
|
||||
enable: 'boolen'
|
||||
},
|
||||
custom_field3: {
|
||||
name: 'string',
|
||||
enable: 'boolen'
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询项目分组
|
||||
* @interface /group/get
|
||||
* @method GET
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @param {String} id 项目分组ID
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async get(ctx) {
|
||||
let params = ctx.params;
|
||||
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
let result = await groupInst.getGroupById(params.id);
|
||||
if (result) {
|
||||
result = result.toObject();
|
||||
let role = await this.getProjectRole(params.id, 'group');
|
||||
result.role = role;
|
||||
if (result.type === 'private') {
|
||||
result.group_name = '个人空间';
|
||||
}
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加项目分组
|
||||
* @interface /group/add
|
||||
* @method POST
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @param {String} group_name 项目分组名称,不能为空
|
||||
* @param {String} [group_desc] 项目分组描述
|
||||
* @param {String} [owner_uids] 组长[uid]
|
||||
* @returns {Object}
|
||||
* @example ./api/group/add.json
|
||||
*/
|
||||
async add(ctx) {
|
||||
let params = ctx.params;
|
||||
|
||||
// 新版每个人都有权限添加分组
|
||||
|
||||
// if (this.getRole() !== 'admin') {
|
||||
// return (ctx.body = yapi.commons.resReturn(null, 401, '没有权限'));
|
||||
// }
|
||||
|
||||
let owners = [];
|
||||
|
||||
if(params.owner_uids.length === 0){
|
||||
params.owner_uids.push(
|
||||
this.getUid()
|
||||
)
|
||||
}
|
||||
|
||||
if (params.owner_uids) {
|
||||
for (let i = 0, len = params.owner_uids.length; i < len; i++) {
|
||||
let id = params.owner_uids[i];
|
||||
let groupUserdata = await this.getUserdata(id, 'owner');
|
||||
if (groupUserdata) {
|
||||
owners.push(groupUserdata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
|
||||
let checkRepeat = await groupInst.checkRepeat(params.group_name);
|
||||
|
||||
if (checkRepeat > 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, '项目分组名已存在'));
|
||||
}
|
||||
|
||||
let data = {
|
||||
group_name: params.group_name,
|
||||
group_desc: params.group_desc,
|
||||
uid: this.getUid(),
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time(),
|
||||
members: owners
|
||||
};
|
||||
|
||||
let result = await groupInst.save(data);
|
||||
result = yapi.commons.fieldSelect(result, [
|
||||
'_id',
|
||||
'group_name',
|
||||
'group_desc',
|
||||
'uid',
|
||||
'members',
|
||||
'type'
|
||||
]);
|
||||
let username = this.getUsername();
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 新增了分组 <a href="/group/${
|
||||
result._id
|
||||
}">${params.group_name}</a>`,
|
||||
type: 'group',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: result._id
|
||||
});
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户数据
|
||||
* @param uid
|
||||
* @param role
|
||||
* @returns {Promise.<*>}
|
||||
*/
|
||||
|
||||
async getUserdata(uid, role) {
|
||||
role = role || 'dev';
|
||||
let userInst = yapi.getInst(userModel);
|
||||
let userData = await userInst.findById(uid);
|
||||
if (!userData) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
_role: userData.role,
|
||||
role: role,
|
||||
uid: userData._id,
|
||||
username: userData.username,
|
||||
email: userData.email
|
||||
};
|
||||
}
|
||||
|
||||
async getMyGroup(ctx){
|
||||
var groupInst = yapi.getInst(groupModel);
|
||||
let privateGroup = await groupInst.getByPrivateUid(this.getUid());
|
||||
if (!privateGroup) {
|
||||
privateGroup = await groupInst.save({
|
||||
uid: this.getUid(),
|
||||
group_name: 'User-' + this.getUid(),
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time(),
|
||||
type: 'private'
|
||||
});
|
||||
}
|
||||
if(privateGroup){
|
||||
ctx.body = yapi.commons.resReturn(privateGroup)
|
||||
}else{
|
||||
ctx.body = yapi.commons.resReturn(null)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加项目分组成员
|
||||
* @interface /group/add_member
|
||||
* @method POST
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @param {String} id 项目分组id
|
||||
* @param {String} member_uids 项目分组成员[uid]
|
||||
* @param {String} role 成员角色,owner or dev or guest
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async addMember(ctx) {
|
||||
let params = ctx.params;
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
|
||||
params.role = ['owner', 'dev', 'guest'].find(v => v === params.role) || 'dev';
|
||||
let add_members = [];
|
||||
let exist_members = [];
|
||||
let no_members = [];
|
||||
for (let i = 0, len = params.member_uids.length; i < len; i++) {
|
||||
let id = params.member_uids[i];
|
||||
let check = await groupInst.checkMemberRepeat(params.id, id);
|
||||
let userdata = await this.getUserdata(id, params.role);
|
||||
if (check > 0) {
|
||||
exist_members.push(userdata);
|
||||
} else if (!userdata) {
|
||||
no_members.push(id);
|
||||
} else {
|
||||
userdata.role !== 'admin' && add_members.push(userdata);
|
||||
delete userdata._role;
|
||||
}
|
||||
}
|
||||
|
||||
let result = await groupInst.addMember(params.id, add_members);
|
||||
let username = this.getUsername();
|
||||
if (add_members.length) {
|
||||
let members = add_members.map(item => {
|
||||
return `<a href = "/user/profile/${item.uid}">${item.username}</a>`;
|
||||
});
|
||||
members = members.join('、');
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 新增了分组成员 ${members} 为 ${
|
||||
rolename[params.role]
|
||||
}`,
|
||||
type: 'group',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: params.id
|
||||
});
|
||||
}
|
||||
ctx.body = yapi.commons.resReturn({
|
||||
result,
|
||||
add_members,
|
||||
exist_members,
|
||||
no_members
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改项目分组成员角色
|
||||
* @interface /group/change_member_role
|
||||
* @method POST
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @param {String} id 项目分组id
|
||||
* @param {String} member_uid 项目分组成员uid
|
||||
* @param {String} role 权限 ['owner'|'dev']
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async changeMemberRole(ctx) {
|
||||
let params = ctx.request.body;
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
|
||||
var check = await groupInst.checkMemberRepeat(params.id, params.member_uid);
|
||||
if (check === 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '分组成员不存在'));
|
||||
}
|
||||
if ((await this.checkAuth(params.id, 'group', 'danger')) !== true) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
|
||||
}
|
||||
|
||||
params.role = ['owner', 'dev', 'guest'].find(v => v === params.role) || 'dev';
|
||||
|
||||
let result = await groupInst.changeMemberRole(params.id, params.member_uid, params.role);
|
||||
let username = this.getUsername();
|
||||
|
||||
let groupUserdata = await this.getUserdata(params.member_uid, params.role);
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 更改了分组成员 <a href="/user/profile/${
|
||||
params.member_uid
|
||||
}">${groupUserdata ? groupUserdata.username : ''}</a> 的权限为 "${rolename[params.role]}"`,
|
||||
type: 'group',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: params.id
|
||||
});
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有项目成员
|
||||
* @interface /group/get_member_list
|
||||
* @method GET
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @param {String} id 项目分组id
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async getMemberList(ctx) {
|
||||
let params = ctx.params;
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
let group = await groupInst.get(params.id);
|
||||
ctx.body = yapi.commons.resReturn(group.members);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除项目成员
|
||||
* @interface /group/del_member
|
||||
* @method POST
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @param {String} id 项目分组id
|
||||
* @param {String} member_uid 项目分组成员uid
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async delMember(ctx) {
|
||||
let params = ctx.params;
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
var check = await groupInst.checkMemberRepeat(params.id, params.member_uid);
|
||||
if (check === 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '分组成员不存在'));
|
||||
}
|
||||
if ((await this.checkAuth(params.id, 'group', 'danger')) !== true) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
|
||||
}
|
||||
|
||||
let result = await groupInst.delMember(params.id, params.member_uid);
|
||||
let username = this.getUsername();
|
||||
|
||||
let groupUserdata = await this.getUserdata(params.member_uid, params.role);
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 删除了分组成员 <a href="/user/profile/${
|
||||
params.member_uid
|
||||
}">${groupUserdata ? groupUserdata.username : ''}</a>`,
|
||||
type: 'group',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: params.id
|
||||
});
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目分组列表
|
||||
* @interface /group/list
|
||||
* @method get
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @returns {Object}
|
||||
* @example ./api/group/list.json
|
||||
*/
|
||||
async list(ctx) {
|
||||
var groupInst = yapi.getInst(groupModel);
|
||||
let projectInst = yapi.getInst(projectModel);
|
||||
|
||||
let privateGroup = await groupInst.getByPrivateUid(this.getUid());
|
||||
let newResult = [];
|
||||
|
||||
if (!privateGroup) {
|
||||
privateGroup = await groupInst.save({
|
||||
uid: this.getUid(),
|
||||
group_name: 'User-' + this.getUid(),
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time(),
|
||||
type: 'private'
|
||||
});
|
||||
}
|
||||
|
||||
if(this.getRole() === 'admin'){
|
||||
let result = await groupInst.list();
|
||||
if(result && result.length > 0 ){
|
||||
for (let i = 0; i < result.length; i++){
|
||||
result[i] = result[i].toObject();
|
||||
newResult.unshift(result[i])
|
||||
}
|
||||
}
|
||||
}else{
|
||||
let result = await groupInst.getAuthList(this.getUid());
|
||||
if(result && result.length > 0 ){
|
||||
for (let i = 0; i < result.length; i++){
|
||||
result[i] = result[i].toObject();
|
||||
newResult.unshift(result[i])
|
||||
}
|
||||
}
|
||||
|
||||
const groupIds = newResult.map(item=> item._id);
|
||||
const newGroupIds = [];
|
||||
|
||||
let groupByProject = await projectInst.getAuthList(this.getUid());
|
||||
if(groupByProject && groupByProject.length > 0){
|
||||
groupByProject.forEach( _data=>{
|
||||
const _temp = [...groupIds, ...newGroupIds];
|
||||
if(!_.find(_temp, id=> id === _data.group_id)){
|
||||
newGroupIds.push(_data.group_id)
|
||||
}
|
||||
})
|
||||
}
|
||||
let newData = await groupInst.findByGroups(newGroupIds)
|
||||
newData.forEach(_data=>{
|
||||
_data = _data.toObject();
|
||||
newResult.push(_data);
|
||||
})
|
||||
}
|
||||
if (privateGroup) {
|
||||
privateGroup = privateGroup.toObject();
|
||||
privateGroup.group_name = '个人空间';
|
||||
privateGroup.role = 'owner';
|
||||
newResult.unshift(privateGroup);
|
||||
}
|
||||
|
||||
ctx.body = yapi.commons.resReturn(newResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除项目分组
|
||||
* @interface /group/del
|
||||
* @method post
|
||||
* @param {String} id 项目分组id
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @returns {Object}
|
||||
* @example ./api/group/del.json
|
||||
*/
|
||||
async del(ctx) {
|
||||
if (this.getRole() !== 'admin') {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, '没有权限'));
|
||||
}
|
||||
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
let projectInst = yapi.getInst(projectModel);
|
||||
let interfaceInst = yapi.getInst(interfaceModel);
|
||||
let interfaceColInst = yapi.getInst(interfaceColModel);
|
||||
let interfaceCaseInst = yapi.getInst(interfaceCaseModel);
|
||||
let id = ctx.params.id;
|
||||
|
||||
let projectList = await projectInst.list(id, true);
|
||||
projectList.forEach(async p => {
|
||||
await interfaceInst.delByProjectId(p._id);
|
||||
await interfaceCaseInst.delByProjectId(p._id);
|
||||
await interfaceColInst.delByProjectId(p._id);
|
||||
});
|
||||
if (projectList.length > 0) {
|
||||
await projectInst.delByGroupid(id);
|
||||
}
|
||||
|
||||
let result = await groupInst.del(id);
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新项目分组
|
||||
* @interface /group/up
|
||||
* @method post
|
||||
* @param {String} id 项目分组id
|
||||
* @param {String} group_name 项目分组名称
|
||||
* @param {String} group_desc 项目分组描述
|
||||
* @category group
|
||||
* @foldnumber 10
|
||||
* @returns {Object}
|
||||
* @example ./api/group/up.json
|
||||
*/
|
||||
async up(ctx) {
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
let params = ctx.params;
|
||||
|
||||
if ((await this.checkAuth(params.id, 'group', 'danger')) !== true) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
|
||||
}
|
||||
|
||||
let result = await groupInst.up(params.id, params);
|
||||
let username = this.getUsername();
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 更新了 <a href="/group/${
|
||||
params.id
|
||||
}">${params.group_name}</a> 分组`,
|
||||
type: 'group',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: params.id
|
||||
});
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = groupController;
|
||||
1286
server/controllers/interface.js
Normal file
1286
server/controllers/interface.js
Normal file
File diff suppressed because it is too large
Load Diff
876
server/controllers/interfaceCol.js
Normal file
876
server/controllers/interfaceCol.js
Normal file
@@ -0,0 +1,876 @@
|
||||
const interfaceColModel = require('../models/interfaceCol.js');
|
||||
const interfaceCaseModel = require('../models/interfaceCase.js');
|
||||
const interfaceModel = require('../models/interface.js');
|
||||
const projectModel = require('../models/project.js');
|
||||
const baseController = require('./base.js');
|
||||
const yapi = require('../yapi.js');
|
||||
const _ = require('underscore');
|
||||
|
||||
class interfaceColController extends baseController {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
this.colModel = yapi.getInst(interfaceColModel);
|
||||
this.caseModel = yapi.getInst(interfaceCaseModel);
|
||||
this.interfaceModel = yapi.getInst(interfaceModel);
|
||||
this.projectModel = yapi.getInst(projectModel);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有接口集
|
||||
* @interface /col/list
|
||||
* @method GET
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {String} project_id email名称,不能为空
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async list(ctx) {
|
||||
try {
|
||||
let id = ctx.query.project_id;
|
||||
let project = await this.projectModel.getBaseInfo(id);
|
||||
if (project.project_type === 'private') {
|
||||
if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
|
||||
}
|
||||
}
|
||||
let result = await this.colModel.list(id);
|
||||
result = result.sort((a, b) => {
|
||||
return a.index - b.index;
|
||||
});
|
||||
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
result[i] = result[i].toObject();
|
||||
let caseList = await this.caseModel.list(result[i]._id);
|
||||
|
||||
for(let j=0; j< caseList.length; j++){
|
||||
let item = caseList[j].toObject();
|
||||
let interfaceData = await this.interfaceModel.getBaseinfo(item.interface_id);
|
||||
item.path = interfaceData.path;
|
||||
caseList[j] = item;
|
||||
}
|
||||
|
||||
caseList = caseList.sort((a, b) => {
|
||||
return a.index - b.index;
|
||||
});
|
||||
result[i].caseList = caseList;
|
||||
|
||||
}
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加接口集
|
||||
* @interface /col/add_col
|
||||
* @method POST
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {Number} project_id
|
||||
* @param {String} name
|
||||
* @param {String} desc
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async addCol(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
params = yapi.commons.handleParams(params, {
|
||||
name: 'string',
|
||||
project_id: 'number',
|
||||
desc: 'string'
|
||||
});
|
||||
|
||||
if (!params.project_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
|
||||
}
|
||||
if (!params.name) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '名称不能为空'));
|
||||
}
|
||||
|
||||
let auth = await this.checkAuth(params.project_id, 'project', 'edit');
|
||||
if (!auth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
|
||||
}
|
||||
|
||||
let result = await this.colModel.save({
|
||||
name: params.name,
|
||||
project_id: params.project_id,
|
||||
desc: params.desc,
|
||||
uid: this.getUid(),
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time()
|
||||
});
|
||||
let username = this.getUsername();
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 添加了接口集 <a href="/project/${
|
||||
params.project_id
|
||||
}/interface/col/${result._id}">${params.name}</a>`,
|
||||
type: 'project',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: params.project_id
|
||||
});
|
||||
// this.projectModel.up(params.project_id,{up_time: new Date().getTime()}).then();
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个接口集下的所有的测试用例
|
||||
* @interface /col/case_list
|
||||
* @method GET
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {String} col_id 接口集id
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async getCaseList(ctx) {
|
||||
try {
|
||||
let id = ctx.query.col_id;
|
||||
if (!id || id == 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 407, 'col_id不能为空'));
|
||||
}
|
||||
|
||||
let colData = await this.colModel.get(id);
|
||||
let project = await this.projectModel.getBaseInfo(colData.project_id);
|
||||
if (project.project_type === 'private') {
|
||||
if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
|
||||
}
|
||||
}
|
||||
|
||||
ctx.body = await yapi.commons.getCaseList(id);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个接口集下的所有的测试用例的环境变量
|
||||
* @interface /col/case_env_list
|
||||
* @method GET
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {String} col_id 接口集id
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async getCaseEnvList(ctx) {
|
||||
try {
|
||||
let id = ctx.query.col_id;
|
||||
if (!id || id == 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 407, 'col_id不能为空'));
|
||||
}
|
||||
|
||||
let colData = await this.colModel.get(id);
|
||||
let project = await this.projectModel.getBaseInfo(colData.project_id);
|
||||
if (project.project_type === 'private') {
|
||||
if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
|
||||
}
|
||||
}
|
||||
|
||||
// 通过col_id 找到 caseList
|
||||
let projectList = await this.caseModel.list(id, 'project_id');
|
||||
// 对projectList 进行去重处理
|
||||
projectList = this.unique(projectList, 'project_id');
|
||||
|
||||
// 遍历projectList 找到项目和env
|
||||
let projectEnvList = [];
|
||||
for (let i = 0; i < projectList.length; i++) {
|
||||
let result = await this.projectModel.getBaseInfo(projectList[i], 'name env');
|
||||
projectEnvList.push(result);
|
||||
}
|
||||
ctx.body = yapi.commons.resReturn(projectEnvList);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
requestParamsToObj(arr) {
|
||||
if (!arr || !Array.isArray(arr) || arr.length === 0) {
|
||||
return {};
|
||||
}
|
||||
let obj = {};
|
||||
arr.forEach(item => {
|
||||
obj[item.name] = '';
|
||||
});
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个接口集下的所有的测试用例
|
||||
* @interface /col/case_list_by_var_params
|
||||
* @method GET
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {String} col_id 接口集id
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async getCaseListByVariableParams(ctx) {
|
||||
try {
|
||||
let id = ctx.query.col_id;
|
||||
if (!id || id == 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 407, 'col_id不能为空'));
|
||||
}
|
||||
let resultList = await this.caseModel.list(id, 'all');
|
||||
if (resultList.length === 0) {
|
||||
return (ctx.body = yapi.commons.resReturn([]));
|
||||
}
|
||||
let project = await this.projectModel.getBaseInfo(resultList[0].project_id);
|
||||
|
||||
if (project.project_type === 'private') {
|
||||
if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
|
||||
}
|
||||
}
|
||||
|
||||
for (let index = 0; index < resultList.length; index++) {
|
||||
let result = resultList[index].toObject();
|
||||
let item = {},
|
||||
body,
|
||||
query,
|
||||
bodyParams,
|
||||
pathParams;
|
||||
let data = await this.interfaceModel.get(result.interface_id);
|
||||
if (!data) {
|
||||
await this.caseModel.del(result._id);
|
||||
continue;
|
||||
}
|
||||
item._id = result._id;
|
||||
item.casename = result.casename;
|
||||
body = yapi.commons.json_parse(data.res_body);
|
||||
body = typeof body === 'object' ? body : {};
|
||||
if (data.res_body_is_json_schema) {
|
||||
body = yapi.commons.schemaToJson(body, {
|
||||
alwaysFakeOptionals: true
|
||||
});
|
||||
}
|
||||
item.body = Object.assign({}, body);
|
||||
query = this.requestParamsToObj(data.req_query);
|
||||
pathParams = this.requestParamsToObj(data.req_params);
|
||||
if (data.req_body_type === 'form') {
|
||||
bodyParams = this.requestParamsToObj(data.req_body_form);
|
||||
} else {
|
||||
bodyParams = yapi.commons.json_parse(data.req_body_other);
|
||||
if (data.req_body_is_json_schema) {
|
||||
bodyParams = yapi.commons.schemaToJson(bodyParams, {
|
||||
alwaysFakeOptionals: true
|
||||
});
|
||||
}
|
||||
bodyParams = typeof bodyParams === 'object' ? bodyParams : {};
|
||||
}
|
||||
item.params = Object.assign(pathParams, query, bodyParams);
|
||||
item.index = result.index;
|
||||
resultList[index] = item;
|
||||
}
|
||||
|
||||
ctx.body = yapi.commons.resReturn(resultList);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加一个测试用例
|
||||
* @interface /col/add_case
|
||||
* @method POST
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {String} casename
|
||||
* @param {Number} col_id
|
||||
* @param {Number} project_id
|
||||
* @param {String} domain
|
||||
* @param {String} path
|
||||
* @param {String} method
|
||||
* @param {Object} req_query
|
||||
* @param {Object} req_headers
|
||||
* @param {String} req_body_type
|
||||
* @param {Array} req_body_form
|
||||
* @param {String} req_body_other
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async addCase(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
params = yapi.commons.handleParams(params, {
|
||||
casename: 'string',
|
||||
project_id: 'number',
|
||||
col_id: 'number',
|
||||
interface_id: 'number',
|
||||
case_env: 'string'
|
||||
});
|
||||
|
||||
if (!params.project_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
|
||||
}
|
||||
|
||||
if (!params.interface_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '接口id不能为空'));
|
||||
}
|
||||
|
||||
let auth = await this.checkAuth(params.project_id, 'project', 'edit');
|
||||
if (!auth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
|
||||
}
|
||||
|
||||
if (!params.col_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '接口集id不能为空'));
|
||||
}
|
||||
|
||||
if (!params.casename) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '用例名称不能为空'));
|
||||
}
|
||||
|
||||
params.uid = this.getUid();
|
||||
params.index = 0;
|
||||
params.add_time = yapi.commons.time();
|
||||
params.up_time = yapi.commons.time();
|
||||
let result = await this.caseModel.save(params);
|
||||
let username = this.getUsername();
|
||||
|
||||
this.colModel.get(params.col_id).then(col => {
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 在接口集 <a href="/project/${
|
||||
params.project_id
|
||||
}/interface/col/${params.col_id}">${col.name}</a> 下添加了测试用例 <a href="/project/${
|
||||
params.project_id
|
||||
}/interface/case/${result._id}">${params.casename}</a>`,
|
||||
type: 'project',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: params.project_id
|
||||
});
|
||||
});
|
||||
this.projectModel.up(params.project_id, { up_time: new Date().getTime() }).then();
|
||||
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async addCaseList(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
params = yapi.commons.handleParams(params, {
|
||||
project_id: 'number',
|
||||
col_id: 'number'
|
||||
});
|
||||
if (!params.interface_list || !Array.isArray(params.interface_list)) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'interface_list 参数有误'));
|
||||
}
|
||||
|
||||
if (!params.project_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
|
||||
}
|
||||
|
||||
let auth = await this.checkAuth(params.project_id, 'project', 'edit');
|
||||
if (!auth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
|
||||
}
|
||||
|
||||
if (!params.col_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '接口集id不能为空'));
|
||||
}
|
||||
|
||||
let data = {
|
||||
uid: this.getUid(),
|
||||
index: 0,
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time(),
|
||||
project_id: params.project_id,
|
||||
col_id: params.col_id
|
||||
};
|
||||
|
||||
for (let i = 0; i < params.interface_list.length; i++) {
|
||||
let interfaceData = await this.interfaceModel.get(params.interface_list[i]);
|
||||
data.interface_id = params.interface_list[i];
|
||||
data.casename = interfaceData.title;
|
||||
|
||||
// 处理json schema 解析
|
||||
if (
|
||||
interfaceData.req_body_type === 'json' &&
|
||||
interfaceData.req_body_other &&
|
||||
interfaceData.req_body_is_json_schema
|
||||
) {
|
||||
let req_body_other = yapi.commons.json_parse(interfaceData.req_body_other);
|
||||
req_body_other = yapi.commons.schemaToJson(req_body_other, {
|
||||
alwaysFakeOptionals: true
|
||||
});
|
||||
|
||||
data.req_body_other = JSON.stringify(req_body_other);
|
||||
} else {
|
||||
data.req_body_other = interfaceData.req_body_other;
|
||||
}
|
||||
|
||||
data.req_body_type = interfaceData.req_body_type;
|
||||
let caseResultData = await this.caseModel.save(data);
|
||||
let username = this.getUsername();
|
||||
this.colModel.get(params.col_id).then(col => {
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 在接口集 <a href="/project/${
|
||||
params.project_id
|
||||
}/interface/col/${params.col_id}">${col.name}</a> 下导入了测试用例 <a href="/project/${
|
||||
params.project_id
|
||||
}/interface/case/${caseResultData._id}">${data.casename}</a>`,
|
||||
type: 'project',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: params.project_id
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
this.projectModel.up(params.project_id, { up_time: new Date().getTime() }).then();
|
||||
|
||||
ctx.body = yapi.commons.resReturn('ok');
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async cloneCaseList(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
params = yapi.commons.handleParams(params, {
|
||||
project_id: 'number',
|
||||
col_id: 'number',
|
||||
new_col_id: 'number'
|
||||
});
|
||||
|
||||
const { project_id, col_id, new_col_id } = params;
|
||||
|
||||
if (!project_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
|
||||
}
|
||||
|
||||
let auth = await this.checkAuth(params.project_id, 'project', 'edit');
|
||||
|
||||
if (!auth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
|
||||
}
|
||||
|
||||
if (!col_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '被克隆的接口集id不能为空'));
|
||||
}
|
||||
|
||||
if (!new_col_id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '克隆的接口集id不能为空'));
|
||||
}
|
||||
|
||||
let oldColCaselistData = await this.caseModel.list(col_id, 'all');
|
||||
|
||||
oldColCaselistData = oldColCaselistData.sort((a, b) => {
|
||||
return a.index - b.index;
|
||||
});
|
||||
|
||||
const newCaseList = [];
|
||||
const oldCaseObj = {};
|
||||
let obj = {};
|
||||
|
||||
const handleTypeParams = (data, name) => {
|
||||
let res = data[name];
|
||||
const type = Object.prototype.toString.call(res);
|
||||
if (type === '[object Array]' && res.length) {
|
||||
res = JSON.stringify(res);
|
||||
try {
|
||||
res = JSON.parse(handleReplaceStr(res));
|
||||
} catch (e) {
|
||||
console.log('e ->', e);
|
||||
}
|
||||
} else if (type === '[object String]' && data[name]) {
|
||||
res = handleReplaceStr(res);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
const handleReplaceStr = str => {
|
||||
if (str.indexOf('$') !== -1) {
|
||||
str = str.replace(/\$\.([0-9]+)\./g, function(match, p1) {
|
||||
p1 = p1.toString();
|
||||
return `$.${newCaseList[oldCaseObj[p1]]}.` || '';
|
||||
});
|
||||
}
|
||||
return str;
|
||||
};
|
||||
|
||||
// 处理数据里面的$id;
|
||||
const handleParams = data => {
|
||||
data.col_id = new_col_id;
|
||||
delete data._id;
|
||||
delete data.add_time;
|
||||
delete data.up_time;
|
||||
delete data.__v;
|
||||
data.req_body_other = handleTypeParams(data, 'req_body_other');
|
||||
data.req_query = handleTypeParams(data, 'req_query');
|
||||
data.req_params = handleTypeParams(data, 'req_params');
|
||||
data.req_body_form = handleTypeParams(data, 'req_body_form');
|
||||
return data;
|
||||
};
|
||||
|
||||
for (let i = 0; i < oldColCaselistData.length; i++) {
|
||||
obj = oldColCaselistData[i].toObject();
|
||||
// 将被克隆的id和位置绑定
|
||||
oldCaseObj[obj._id] = i;
|
||||
let caseData = handleParams(obj);
|
||||
let newCase = await this.caseModel.save(caseData);
|
||||
newCaseList.push(newCase._id);
|
||||
}
|
||||
|
||||
this.projectModel.up(params.project_id, { up_time: new Date().getTime() }).then();
|
||||
ctx.body = yapi.commons.resReturn('ok');
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新一个测试用例
|
||||
* @interface /col/up_case
|
||||
* @method POST
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {number} id
|
||||
* @param {String} casename
|
||||
* @param {String} domain
|
||||
* @param {String} path
|
||||
* @param {String} method
|
||||
* @param {Object} req_query
|
||||
* @param {Object} req_headers
|
||||
* @param {String} req_body_type
|
||||
* @param {Array} req_body_form
|
||||
* @param {String} req_body_other
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async upCase(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
params = yapi.commons.handleParams(params, {
|
||||
id: 'number',
|
||||
casename: 'string'
|
||||
});
|
||||
|
||||
if (!params.id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '用例id不能为空'));
|
||||
}
|
||||
|
||||
// if (!params.casename) {
|
||||
// return (ctx.body = yapi.commons.resReturn(null, 400, '用例名称不能为空'));
|
||||
// }
|
||||
|
||||
let caseData = await this.caseModel.get(params.id);
|
||||
let auth = await this.checkAuth(caseData.project_id, 'project', 'edit');
|
||||
if (!auth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
|
||||
}
|
||||
|
||||
params.uid = this.getUid();
|
||||
|
||||
//不允许修改接口id和项目id
|
||||
delete params.interface_id;
|
||||
delete params.project_id;
|
||||
let result = await this.caseModel.up(params.id, params);
|
||||
let username = this.getUsername();
|
||||
this.colModel.get(caseData.col_id).then(col => {
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 在接口集 <a href="/project/${
|
||||
caseData.project_id
|
||||
}/interface/col/${caseData.col_id}">${col.name}</a> 更新了测试用例 <a href="/project/${
|
||||
caseData.project_id
|
||||
}/interface/case/${params.id}">${params.casename || caseData.casename}</a>`,
|
||||
type: 'project',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: caseData.project_id
|
||||
});
|
||||
});
|
||||
|
||||
this.projectModel.up(caseData.project_id, { up_time: new Date().getTime() }).then();
|
||||
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个测试用例详情
|
||||
* @interface /col/case
|
||||
* @method GET
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {String} caseid
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async getCase(ctx) {
|
||||
try {
|
||||
let id = ctx.query.caseid;
|
||||
let result = await this.caseModel.get(id);
|
||||
if (!result) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '不存在的case'));
|
||||
}
|
||||
result = result.toObject();
|
||||
let data = await this.interfaceModel.get(result.interface_id);
|
||||
if (!data) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '找不到对应的接口,请联系管理员'));
|
||||
}
|
||||
data = data.toObject();
|
||||
|
||||
let projectData = await this.projectModel.getBaseInfo(data.project_id);
|
||||
result.path = projectData.basepath + data.path;
|
||||
result.method = data.method;
|
||||
result.req_body_type = data.req_body_type;
|
||||
result.req_headers = yapi.commons.handleParamsValue(data.req_headers, result.req_headers);
|
||||
result.res_body = data.res_body;
|
||||
result.res_body_type = data.res_body_type;
|
||||
result.req_body_form = yapi.commons.handleParamsValue(
|
||||
data.req_body_form,
|
||||
result.req_body_form
|
||||
);
|
||||
result.req_query = yapi.commons.handleParamsValue(data.req_query, result.req_query);
|
||||
result.req_params = yapi.commons.handleParamsValue(data.req_params, result.req_params);
|
||||
result.interface_up_time = data.up_time;
|
||||
result.req_body_is_json_schema = data.req_body_is_json_schema;
|
||||
result.res_body_is_json_schema = data.res_body_is_json_schema;
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 400, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新一个接口集name或描述
|
||||
* @interface /col/up_col
|
||||
* @method POST
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {String} name
|
||||
* @param {String} desc
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async upCol(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
let id = params.col_id;
|
||||
if (!id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '缺少 col_id 参数'));
|
||||
}
|
||||
let colData = await this.colModel.get(id);
|
||||
if (!colData) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '不存在'));
|
||||
}
|
||||
let auth = await this.checkAuth(colData.project_id, 'project', 'edit');
|
||||
if (!auth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
|
||||
}
|
||||
delete params.col_id;
|
||||
let result = await this.colModel.up(id, params);
|
||||
let username = this.getUsername();
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 更新了测试集合 <a href="/project/${
|
||||
colData.project_id
|
||||
}/interface/col/${id}">${colData.name}</a> 的信息`,
|
||||
type: 'project',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: colData.project_id
|
||||
});
|
||||
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 400, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新多个接口case index
|
||||
* @interface /col/up_case_index
|
||||
* @method POST
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {Array} [id, index]
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async upCaseIndex(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
if (!params || !Array.isArray(params)) {
|
||||
ctx.body = yapi.commons.resReturn(null, 400, '请求参数必须是数组');
|
||||
}
|
||||
params.forEach(item => {
|
||||
if (item.id) {
|
||||
this.caseModel.upCaseIndex(item.id, item.index).then(
|
||||
res => {},
|
||||
err => {
|
||||
yapi.commons.log(err.message, 'error');
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return (ctx.body = yapi.commons.resReturn('成功!'));
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 400, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新多个测试集合 index
|
||||
* @interface /col/up_col_index
|
||||
* @method POST
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {Array} [id, index]
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async upColIndex(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
if (!params || !Array.isArray(params)) {
|
||||
ctx.body = yapi.commons.resReturn(null, 400, '请求参数必须是数组');
|
||||
}
|
||||
params.forEach(item => {
|
||||
if (item.id) {
|
||||
this.colModel.upColIndex(item.id, item.index).then(
|
||||
res => {},
|
||||
err => {
|
||||
yapi.commons.log(err.message, 'error');
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return (ctx.body = yapi.commons.resReturn('成功!'));
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 400, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除一个接口集
|
||||
* @interface /col/del_col
|
||||
* @method GET
|
||||
* @category col
|
||||
* @foldnumber 10
|
||||
* @param {String}
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async delCol(ctx) {
|
||||
try {
|
||||
let id = ctx.query.col_id;
|
||||
let colData = await this.colModel.get(id);
|
||||
if (!colData) {
|
||||
ctx.body = yapi.commons.resReturn(null, 400, '不存在的id');
|
||||
}
|
||||
|
||||
if (colData.uid !== this.getUid()) {
|
||||
let auth = await this.checkAuth(colData.project_id, 'project', 'danger');
|
||||
if (!auth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
|
||||
}
|
||||
}
|
||||
let result = await this.colModel.del(id);
|
||||
await this.caseModel.delByCol(id);
|
||||
let username = this.getUsername();
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 删除了接口集 ${
|
||||
colData.name
|
||||
} 及其下面的接口`,
|
||||
type: 'project',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: colData.project_id
|
||||
});
|
||||
return (ctx.body = yapi.commons.resReturn(result));
|
||||
} catch (e) {
|
||||
yapi.commons.resReturn(null, 400, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {*} ctx
|
||||
*/
|
||||
|
||||
async delCase(ctx) {
|
||||
try {
|
||||
let caseid = ctx.query.caseid;
|
||||
let caseData = await this.caseModel.get(caseid);
|
||||
if (!caseData) {
|
||||
ctx.body = yapi.commons.resReturn(null, 400, '不存在的caseid');
|
||||
}
|
||||
|
||||
if (caseData.uid !== this.getUid()) {
|
||||
let auth = await this.checkAuth(caseData.project_id, 'project', 'danger');
|
||||
if (!auth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
|
||||
}
|
||||
}
|
||||
|
||||
let result = await this.caseModel.del(caseid);
|
||||
|
||||
let username = this.getUsername();
|
||||
this.colModel.get(caseData.col_id).then(col => {
|
||||
yapi.commons.saveLog({
|
||||
content: `<a href="/user/profile/${this.getUid()}">${username}</a> 删除了接口集 <a href="/project/${
|
||||
caseData.project_id
|
||||
}/interface/col/${caseData.col_id}">${col.name}</a> 下的接口 ${caseData.casename}`,
|
||||
type: 'project',
|
||||
uid: this.getUid(),
|
||||
username: username,
|
||||
typeid: caseData.project_id
|
||||
});
|
||||
});
|
||||
|
||||
this.projectModel.up(caseData.project_id, { up_time: new Date().getTime() }).then();
|
||||
return (ctx.body = yapi.commons.resReturn(result));
|
||||
} catch (e) {
|
||||
yapi.commons.resReturn(null, 400, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async runCaseScript(ctx) {
|
||||
let params = ctx.request.body;
|
||||
ctx.body = await yapi.commons.runCaseScript(params, params.col_id, params.interface_id, this.getUid());
|
||||
}
|
||||
|
||||
// 数组去重
|
||||
unique(array, compare) {
|
||||
let hash = {};
|
||||
let arr = array.reduce(function(item, next) {
|
||||
hash[next[compare]] ? '' : (hash[next[compare]] = true && item.push(next));
|
||||
// console.log('item',item.project_id)
|
||||
return item;
|
||||
}, []);
|
||||
// 输出去重以后的project_id
|
||||
return arr.map(item => {
|
||||
return item[compare];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = interfaceColController;
|
||||
145
server/controllers/log.js
Normal file
145
server/controllers/log.js
Normal file
@@ -0,0 +1,145 @@
|
||||
const logModel = require('../models/log.js');
|
||||
const yapi = require('../yapi.js');
|
||||
const baseController = require('./base.js');
|
||||
const groupModel = require('../models/group');
|
||||
const projectModel = require('../models/project');
|
||||
const interfaceModel = require('../models/interface');
|
||||
|
||||
class logController extends baseController {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
this.Model = yapi.getInst(logModel);
|
||||
this.groupModel = yapi.getInst(groupModel);
|
||||
this.projectModel = yapi.getInst(projectModel);
|
||||
this.interfaceModel = yapi.getInst(interfaceModel);
|
||||
this.schemaMap = {
|
||||
listByUpdate: {
|
||||
'*type': 'string',
|
||||
'*typeid': 'number',
|
||||
apis: [
|
||||
{
|
||||
method: 'string',
|
||||
path: 'string'
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取动态列表
|
||||
* @interface /log/list
|
||||
* @method GET
|
||||
* @category log
|
||||
* @foldnumber 10
|
||||
* @param {Number} typeid 动态类型id, 不能为空
|
||||
* @param {Number} [page] 分页页码
|
||||
* @param {Number} [limit] 分页大小
|
||||
* @returns {Object}
|
||||
* @example /log/list
|
||||
*/
|
||||
|
||||
async list(ctx) {
|
||||
let typeid = ctx.request.query.typeid,
|
||||
page = ctx.request.query.page || 1,
|
||||
limit = ctx.request.query.limit || 10,
|
||||
type = ctx.request.query.type,
|
||||
selectValue = ctx.request.query.selectValue;
|
||||
if (!typeid) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'typeid不能为空'));
|
||||
}
|
||||
if (!type) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'type不能为空'));
|
||||
}
|
||||
try {
|
||||
if (type === 'group') {
|
||||
let projectList = await this.projectModel.list(typeid);
|
||||
let projectIds = [],
|
||||
projectDatas = {};
|
||||
for (let i in projectList) {
|
||||
projectDatas[projectList[i]._id] = projectList[i];
|
||||
projectIds[i] = projectList[i]._id;
|
||||
}
|
||||
let projectLogList = await this.Model.listWithPagingByGroup(
|
||||
typeid,
|
||||
projectIds,
|
||||
page,
|
||||
limit
|
||||
);
|
||||
projectLogList.forEach((item, index) => {
|
||||
item = item.toObject();
|
||||
if (item.type === 'project') {
|
||||
item.content =
|
||||
`在 <a href="/project/${item.typeid}">${projectDatas[item.typeid].name}</a> 项目: ` +
|
||||
item.content;
|
||||
}
|
||||
projectLogList[index] = item;
|
||||
});
|
||||
let total = await this.Model.listCountByGroup(typeid, projectIds);
|
||||
ctx.body = yapi.commons.resReturn({
|
||||
list: projectLogList,
|
||||
total: Math.ceil(total / limit)
|
||||
});
|
||||
} else if (type === "project") {
|
||||
let result = await this.Model.listWithPaging(typeid, type, page, limit, selectValue);
|
||||
let count = await this.Model.listCount(typeid, type, selectValue);
|
||||
|
||||
ctx.body = yapi.commons.resReturn({
|
||||
total: Math.ceil(count / limit),
|
||||
list: result
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, err.message);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取特定cat_id下最新修改的动态信息
|
||||
* @interface /log/list_by_update
|
||||
* @method post
|
||||
* @category log
|
||||
* @foldnumber 10
|
||||
* @param {Number} typeid 动态类型id, 不能为空
|
||||
* @returns {Object}
|
||||
* @example /log/list
|
||||
*/
|
||||
|
||||
async listByUpdate(ctx) {
|
||||
let params = ctx.params;
|
||||
|
||||
try {
|
||||
let { typeid, type, apis } = params;
|
||||
let list = [];
|
||||
let projectDatas = await this.projectModel.getBaseInfo(typeid, 'basepath');
|
||||
let basePath = projectDatas.toObject().basepath;
|
||||
|
||||
for (let i = 0; i < apis.length; i++) {
|
||||
let api = apis[i];
|
||||
if (basePath) {
|
||||
api.path = api.path.indexOf(basePath) === 0 ? api.path.substr(basePath.length) : api.path;
|
||||
}
|
||||
let interfaceIdList = await this.interfaceModel.getByPath(
|
||||
typeid,
|
||||
api.path,
|
||||
api.method,
|
||||
'_id'
|
||||
);
|
||||
|
||||
for (let j = 0; j < interfaceIdList.length; j++) {
|
||||
let interfaceId = interfaceIdList[j];
|
||||
let id = interfaceId.id;
|
||||
let result = await this.Model.listWithCatid(typeid, type, id);
|
||||
|
||||
list = list.concat(result);
|
||||
}
|
||||
}
|
||||
|
||||
// let result = await this.Model.listWithCatid(typeid, type, catId);
|
||||
ctx.body = yapi.commons.resReturn(list);
|
||||
} catch (err) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = logController;
|
||||
422
server/controllers/open.js
Normal file
422
server/controllers/open.js
Normal file
@@ -0,0 +1,422 @@
|
||||
const projectModel = require('../models/project.js');
|
||||
const interfaceColModel = require('../models/interfaceCol.js');
|
||||
const interfaceCaseModel = require('../models/interfaceCase.js');
|
||||
const interfaceModel = require('../models/interface.js');
|
||||
const interfaceCatModel = require('../models/interfaceCat.js');
|
||||
const followModel = require('../models/follow.js');
|
||||
const userModel = require('../models/user.js');
|
||||
const yapi = require('../yapi.js');
|
||||
const baseController = require('./base.js');
|
||||
const {
|
||||
handleParams,
|
||||
crossRequest,
|
||||
handleCurrDomain,
|
||||
checkNameIsExistInArray
|
||||
} = require('../../common/postmanLib');
|
||||
const { handleParamsValue, ArrayToObject } = require('../../common/utils.js');
|
||||
const renderToHtml = require('../utils/reportHtml');
|
||||
const HanldeImportData = require('../../common/HandleImportData');
|
||||
const _ = require('underscore');
|
||||
const createContex = require('../../common/createContext')
|
||||
|
||||
/**
|
||||
* {
|
||||
* postman: require('./m')
|
||||
* }
|
||||
*/
|
||||
const importDataModule = {};
|
||||
|
||||
class openController extends baseController {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
this.projectModel = yapi.getInst(projectModel);
|
||||
this.interfaceColModel = yapi.getInst(interfaceColModel);
|
||||
this.interfaceCaseModel = yapi.getInst(interfaceCaseModel);
|
||||
this.interfaceModel = yapi.getInst(interfaceModel);
|
||||
this.interfaceCatModel = yapi.getInst(interfaceCatModel);
|
||||
this.followModel = yapi.getInst(followModel);
|
||||
this.userModel = yapi.getInst(userModel);
|
||||
this.handleValue = this.handleValue.bind(this);
|
||||
this.schemaMap = {
|
||||
runAutoTest: {
|
||||
'*id': 'number',
|
||||
project_id: 'string',
|
||||
token: 'string',
|
||||
mode: {
|
||||
type: 'string',
|
||||
default: 'html'
|
||||
},
|
||||
email: {
|
||||
type: 'boolean',
|
||||
default: false
|
||||
},
|
||||
download: {
|
||||
type: 'boolean',
|
||||
default: false
|
||||
},
|
||||
closeRemoveAdditional: true
|
||||
},
|
||||
importData: {
|
||||
'*type': 'string',
|
||||
url: 'string',
|
||||
'*token': 'string',
|
||||
json: 'string',
|
||||
project_id: 'string',
|
||||
merge: {
|
||||
type: 'string',
|
||||
default: 'normal'
|
||||
}
|
||||
}
|
||||
};
|
||||
yapi.emitHook('import_data', importDataModule);
|
||||
}
|
||||
|
||||
async importData(ctx) {
|
||||
let type = ctx.params.type;
|
||||
let content = ctx.params.json;
|
||||
let project_id = ctx.params.project_id;
|
||||
let dataSync = ctx.params.merge;
|
||||
|
||||
let warnMessage = ''
|
||||
|
||||
/**
|
||||
* 因为以前接口文档写错了,做下兼容
|
||||
*/
|
||||
try{
|
||||
if(!dataSync &&ctx.params.dataSync){
|
||||
warnMessage = 'importData Api 已废弃 dataSync 传参,请联系管理员将 dataSync 改为 merge.'
|
||||
dataSync = ctx.params.dataSync
|
||||
}
|
||||
}catch(e){}
|
||||
|
||||
let token = ctx.params.token;
|
||||
if (!type || !importDataModule[type]) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 40022, '不存在的导入方式'));
|
||||
}
|
||||
|
||||
if (!content && !ctx.params.url) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 40022, 'json 或者 url 参数,不能都为空'));
|
||||
}
|
||||
try {
|
||||
let request = require("request");// let Promise = require('Promise');
|
||||
let syncGet = function (url){
|
||||
return new Promise(function(resolve, reject){
|
||||
request.get({url : url}, function(error, response, body){
|
||||
if(error){
|
||||
reject(error);
|
||||
}else{
|
||||
resolve(body);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if(ctx.params.url){
|
||||
content = await syncGet(ctx.params.url);
|
||||
}else if(content.indexOf('http://') === 0 || content.indexOf('https://') === 0){
|
||||
content = await syncGet(content);
|
||||
}
|
||||
content = JSON.parse(content);
|
||||
} catch (e) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 40022, 'json 格式有误:' + e));
|
||||
}
|
||||
|
||||
let menuList = await this.interfaceCatModel.list(project_id);
|
||||
/**
|
||||
* 防止分类被都被删除时取不到 selectCatid
|
||||
* 如果没有分类,增加一个默认分类
|
||||
*/
|
||||
if (menuList.length === 0) {
|
||||
const catInst = yapi.getInst(interfaceCatModel);
|
||||
const menu = await catInst.save({
|
||||
name: '默认分类',
|
||||
project_id: project_id,
|
||||
desc: '默认分类',
|
||||
uid: this.getUid(),
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time()
|
||||
});
|
||||
menuList.push(menu);
|
||||
}
|
||||
let selectCatid = menuList[0]._id;
|
||||
let projectData = await this.projectModel.get(project_id);
|
||||
let res = await importDataModule[type](content);
|
||||
|
||||
let successMessage;
|
||||
let errorMessage = [];
|
||||
await HanldeImportData(
|
||||
res,
|
||||
project_id,
|
||||
selectCatid,
|
||||
menuList,
|
||||
projectData.basePath,
|
||||
dataSync,
|
||||
err => {
|
||||
errorMessage.push(err);
|
||||
},
|
||||
msg => {
|
||||
successMessage = msg;
|
||||
},
|
||||
() => {},
|
||||
token,
|
||||
yapi.WEBCONFIG.port
|
||||
);
|
||||
|
||||
if (errorMessage.length > 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 404, errorMessage.join('\n')));
|
||||
}
|
||||
ctx.body = yapi.commons.resReturn(null, 0, successMessage + warnMessage);
|
||||
}
|
||||
|
||||
async projectInterfaceData(ctx) {
|
||||
ctx.body = 'projectInterfaceData';
|
||||
}
|
||||
|
||||
handleValue(val, global) {
|
||||
let globalValue = ArrayToObject(global);
|
||||
let context = Object.assign({}, {global: globalValue}, this.records);
|
||||
return handleParamsValue(val, context);
|
||||
}
|
||||
|
||||
handleEvnParams(params) {
|
||||
let result = [];
|
||||
Object.keys(params).map(item => {
|
||||
if (/env_/gi.test(item)) {
|
||||
let curEnv = yapi.commons.trim(params[item]);
|
||||
let value = { curEnv, project_id: item.split('_')[1] };
|
||||
result.push(value);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
async runAutoTest(ctx) {
|
||||
if (!this.$tokenAuth) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 40022, 'token 验证失败'));
|
||||
}
|
||||
// console.log(1231312)
|
||||
const token = ctx.query.token;
|
||||
|
||||
const projectId = ctx.params.project_id;
|
||||
const startTime = new Date().getTime();
|
||||
const records = (this.records = {});
|
||||
const reports = (this.reports = {});
|
||||
const testList = [];
|
||||
let id = ctx.params.id;
|
||||
let curEnvList = this.handleEvnParams(ctx.params);
|
||||
|
||||
let colData = await this.interfaceColModel.get(id);
|
||||
if (!colData) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 40022, 'id值不存在'));
|
||||
}
|
||||
|
||||
let projectData = await this.projectModel.get(projectId);
|
||||
|
||||
let caseList = await yapi.commons.getCaseList(id);
|
||||
if (caseList.errcode !== 0) {
|
||||
ctx.body = caseList;
|
||||
}
|
||||
caseList = caseList.data;
|
||||
for (let i = 0, l = caseList.length; i < l; i++) {
|
||||
let item = caseList[i];
|
||||
let projectEvn = await this.projectModel.getByEnv(item.project_id);
|
||||
|
||||
item.id = item._id;
|
||||
let curEnvItem = _.find(curEnvList, key => {
|
||||
return key.project_id == item.project_id;
|
||||
});
|
||||
|
||||
item.case_env = curEnvItem ? curEnvItem.curEnv || item.case_env : item.case_env;
|
||||
item.req_headers = this.handleReqHeader(item.req_headers, projectEvn.env, item.case_env);
|
||||
item.pre_script = projectData.pre_script;
|
||||
item.after_script = projectData.after_script;
|
||||
item.env = projectEvn.env;
|
||||
let result;
|
||||
// console.log('item',item.case_env)
|
||||
try {
|
||||
result = await this.handleTest(item);
|
||||
} catch (err) {
|
||||
result = err;
|
||||
}
|
||||
|
||||
reports[item.id] = result;
|
||||
records[item.id] = {
|
||||
params: result.params,
|
||||
body: result.res_body
|
||||
};
|
||||
testList.push(result);
|
||||
}
|
||||
|
||||
function getMessage(testList) {
|
||||
let successNum = 0,
|
||||
failedNum = 0,
|
||||
len = 0,
|
||||
msg = '';
|
||||
testList.forEach(item => {
|
||||
len++;
|
||||
if (item.code === 0) {
|
||||
successNum++;
|
||||
}
|
||||
else {
|
||||
failedNum++;
|
||||
}
|
||||
});
|
||||
if (failedNum === 0) {
|
||||
msg = `一共 ${len} 测试用例,全部验证通过`;
|
||||
} else {
|
||||
msg = `一共 ${len} 测试用例,${successNum} 个验证通过, ${failedNum} 个未通过。`;
|
||||
}
|
||||
|
||||
return { msg, len, successNum, failedNum };
|
||||
}
|
||||
|
||||
const endTime = new Date().getTime();
|
||||
const executionTime = (endTime - startTime) / 1000;
|
||||
|
||||
let reportsResult = {
|
||||
message: getMessage(testList),
|
||||
runTime: executionTime + 's',
|
||||
numbs: testList.length,
|
||||
list: testList
|
||||
};
|
||||
|
||||
if (ctx.params.email === true && reportsResult.message.failedNum !== 0) {
|
||||
let autoTestUrl = `${
|
||||
ctx.request.origin
|
||||
}/api/open/run_auto_test?id=${id}&token=${token}&mode=${ctx.params.mode}`;
|
||||
yapi.commons.sendNotice(projectId, {
|
||||
title: `YApi自动化测试报告`,
|
||||
content: `
|
||||
<html>
|
||||
<head>
|
||||
<title>测试报告</title>
|
||||
<meta charset="utf-8" />
|
||||
<body>
|
||||
<div>
|
||||
<h3>测试结果:</h3>
|
||||
<p>${reportsResult.message.msg}</p>
|
||||
<h3>测试结果详情如下:</h3>
|
||||
<p>${autoTestUrl}</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
});
|
||||
}
|
||||
let mode = ctx.params.mode || 'html';
|
||||
if(ctx.params.download === true) {
|
||||
ctx.set('Content-Disposition', `attachment; filename=test.${mode}`);
|
||||
}
|
||||
if (ctx.params.mode === 'json') {
|
||||
return (ctx.body = reportsResult);
|
||||
} else {
|
||||
return (ctx.body = renderToHtml(reportsResult));
|
||||
}
|
||||
}
|
||||
|
||||
async handleTest(interfaceData) {
|
||||
let requestParams = {};
|
||||
let options;
|
||||
options = handleParams(interfaceData, this.handleValue, requestParams);
|
||||
let result = {
|
||||
id: interfaceData.id,
|
||||
name: interfaceData.casename,
|
||||
path: interfaceData.path,
|
||||
code: 400,
|
||||
validRes: []
|
||||
};
|
||||
try {
|
||||
options.taskId = this.getUid();
|
||||
let data = await crossRequest(options, interfaceData.pre_script, interfaceData.after_script,createContex(
|
||||
this.getUid(),
|
||||
interfaceData.project_id,
|
||||
interfaceData.interface_id
|
||||
));
|
||||
let res = data.res;
|
||||
|
||||
result = Object.assign(result, {
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
url: data.req.url,
|
||||
method: data.req.method,
|
||||
data: data.req.data,
|
||||
headers: data.req.headers,
|
||||
res_header: res.header,
|
||||
res_body: res.body
|
||||
});
|
||||
if (options.data && typeof options.data === 'object') {
|
||||
requestParams = Object.assign(requestParams, options.data);
|
||||
}
|
||||
|
||||
let validRes = [];
|
||||
|
||||
let responseData = Object.assign(
|
||||
{},
|
||||
{
|
||||
status: res.status,
|
||||
body: res.body,
|
||||
header: res.header,
|
||||
statusText: res.statusText
|
||||
}
|
||||
);
|
||||
|
||||
await this.handleScriptTest(interfaceData, responseData, validRes, requestParams);
|
||||
result.params = requestParams;
|
||||
if (validRes.length === 0) {
|
||||
result.code = 0;
|
||||
result.validRes = [{ message: '验证通过' }];
|
||||
} else if (validRes.length > 0) {
|
||||
result.code = 1;
|
||||
result.validRes = validRes;
|
||||
}
|
||||
} catch (data) {
|
||||
result = Object.assign(options, result, {
|
||||
res_header: data.header,
|
||||
res_body: data.body || data.message,
|
||||
status: null,
|
||||
statusText: data.message,
|
||||
code: 400
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async handleScriptTest(interfaceData, response, validRes, requestParams) {
|
||||
|
||||
try {
|
||||
let test = await yapi.commons.runCaseScript({
|
||||
response: response,
|
||||
records: this.records,
|
||||
script: interfaceData.test_script,
|
||||
params: requestParams
|
||||
}, interfaceData.col_id, interfaceData.interface_id, this.getUid());
|
||||
if (test.errcode !== 0) {
|
||||
test.data.logs.forEach(item => {
|
||||
validRes.push({
|
||||
message: item
|
||||
});
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
validRes.push({
|
||||
message: 'Error: ' + err.message
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
handleReqHeader(req_header, envData, curEnvName) {
|
||||
let currDomain = handleCurrDomain(envData, curEnvName);
|
||||
|
||||
let header = currDomain.header;
|
||||
header.forEach(item => {
|
||||
if (!checkNameIsExistInArray(item.name, req_header)) {
|
||||
item.abled = true;
|
||||
req_header.push(item);
|
||||
}
|
||||
});
|
||||
req_header = req_header.filter(item => {
|
||||
return item && typeof item === 'object';
|
||||
});
|
||||
return req_header;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = openController;
|
||||
1139
server/controllers/project.js
Normal file
1139
server/controllers/project.js
Normal file
File diff suppressed because it is too large
Load Diff
242
server/controllers/test.js
Normal file
242
server/controllers/test.js
Normal file
@@ -0,0 +1,242 @@
|
||||
const yapi = require('../yapi.js');
|
||||
const baseController = require('./base.js');
|
||||
const fs = require('fs'); //引入文件模块
|
||||
const path = require('path');
|
||||
|
||||
class interfaceColController extends baseController {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 get
|
||||
* @interface /test/get
|
||||
* @method GET
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testGet(ctx) {
|
||||
try {
|
||||
let query = ctx.query;
|
||||
// cookie 检测
|
||||
ctx.cookies.set('_uid', 12, {
|
||||
expires: yapi.commons.expireDate(7),
|
||||
httpOnly: true
|
||||
});
|
||||
ctx.body = yapi.commons.resReturn(query);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 code
|
||||
* @interface /http/code
|
||||
* @method GET
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async testHttpCode(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
ctx.status = +ctx.query.code || 200;
|
||||
ctx.body = yapi.commons.resReturn(params);
|
||||
} catch(e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 post
|
||||
* @interface /test/post
|
||||
* @method POST
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testPost(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
ctx.body = yapi.commons.resReturn(params);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 单文件上传
|
||||
* @interface /test/single/upload
|
||||
* @method POST
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testSingleUpload(ctx) {
|
||||
try {
|
||||
// let params = ctx.request.body;
|
||||
let req = ctx.req;
|
||||
|
||||
let chunks = [],
|
||||
size = 0;
|
||||
req.on('data', function(chunk) {
|
||||
chunks.push(chunk);
|
||||
size += chunk.length;
|
||||
});
|
||||
|
||||
req.on('finish', function() {
|
||||
console.log(34343);
|
||||
});
|
||||
|
||||
req.on('end', function() {
|
||||
let data = new Buffer(size);
|
||||
for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {
|
||||
let chunk = chunks[i];
|
||||
chunk.copy(data, pos);
|
||||
pos += chunk.length;
|
||||
}
|
||||
fs.writeFileSync(path.join(yapi.WEBROOT_RUNTIME, 'test.text'), data, function(err) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 402, '写入失败'));
|
||||
});
|
||||
});
|
||||
|
||||
ctx.body = yapi.commons.resReturn({ res: '上传成功' });
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 文件上传
|
||||
* @interface /test/files/upload
|
||||
* @method POST
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testFilesUpload(ctx) {
|
||||
try {
|
||||
let file = ctx.request.body.files.file;
|
||||
let newPath = path.join(yapi.WEBROOT_RUNTIME, 'test.text');
|
||||
fs.renameSync(file.path, newPath);
|
||||
ctx.body = yapi.commons.resReturn({ res: '上传成功' });
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 put
|
||||
* @interface /test/put
|
||||
* @method PUT
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testPut(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
ctx.body = yapi.commons.resReturn(params);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 delete
|
||||
* @interface /test/delete
|
||||
* @method DELETE
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testDelete(ctx) {
|
||||
try {
|
||||
let body = ctx.request.body;
|
||||
ctx.body = yapi.commons.resReturn(body);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 head
|
||||
* @interface /test/head
|
||||
* @method HEAD
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testHead(ctx) {
|
||||
try {
|
||||
let query = ctx.query;
|
||||
ctx.body = yapi.commons.resReturn(query);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 options
|
||||
* @interface /test/options
|
||||
* @method OPTIONS
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testOptions(ctx) {
|
||||
try {
|
||||
let query = ctx.query;
|
||||
ctx.body = yapi.commons.resReturn(query);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 patch
|
||||
* @interface /test/patch
|
||||
* @method PATCH
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async testPatch(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
ctx.body = yapi.commons.resReturn(params);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 测试 raw
|
||||
* @interface /test/raw
|
||||
* @method POST
|
||||
* @return {Object}
|
||||
* @example
|
||||
*/
|
||||
async testRaw(ctx) {
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
ctx.body = yapi.commons.resReturn(params);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试返回值
|
||||
* @interface /test/response
|
||||
* @method get
|
||||
* @return {Object}
|
||||
* @example
|
||||
*/
|
||||
async testResponse(ctx) {
|
||||
try {
|
||||
// let result = `<div><h2>12222222</h2></div>`;
|
||||
// let result = `wieieieieiieieie`
|
||||
let result = { b: '12', c: '23' };
|
||||
ctx.set('Access-Control-Allow-Origin', '*');
|
||||
ctx.set('Content-Type', 'text');
|
||||
console.log(ctx.response);
|
||||
ctx.body = result;
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = interfaceColController;
|
||||
731
server/controllers/user.js
Normal file
731
server/controllers/user.js
Normal file
@@ -0,0 +1,731 @@
|
||||
const userModel = require('../models/user.js');
|
||||
const yapi = require('../yapi.js');
|
||||
const baseController = require('./base.js');
|
||||
const common = require('../utils/commons.js');
|
||||
const ldap = require('../utils/ldap.js');
|
||||
|
||||
const interfaceModel = require('../models/interface.js');
|
||||
const groupModel = require('../models/group.js');
|
||||
const projectModel = require('../models/project.js');
|
||||
const avatarModel = require('../models/avatar.js');
|
||||
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
class userController extends baseController {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
this.Model = yapi.getInst(userModel);
|
||||
}
|
||||
/**
|
||||
* 用户登录接口
|
||||
* @interface /user/login
|
||||
* @method POST
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @param {String} email email名称,不能为空
|
||||
* @param {String} password 密码,不能为空
|
||||
* @returns {Object}
|
||||
* @example ./api/user/login.json
|
||||
*/
|
||||
async login(ctx) {
|
||||
//登录
|
||||
let userInst = yapi.getInst(userModel); //创建user实体
|
||||
let email = ctx.request.body.email;
|
||||
email = (email || '').trim();
|
||||
let password = ctx.request.body.password;
|
||||
|
||||
if (!email) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'email不能为空'));
|
||||
}
|
||||
if (!password) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '密码不能为空'));
|
||||
}
|
||||
|
||||
let result = await userInst.findByEmail(email);
|
||||
|
||||
if (!result) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 404, '该用户不存在'));
|
||||
} else if (yapi.commons.generatePassword(password, result.passsalt) === result.password) {
|
||||
this.setLoginCookie(result._id, result.passsalt);
|
||||
|
||||
return (ctx.body = yapi.commons.resReturn(
|
||||
{
|
||||
username: result.username,
|
||||
role: result.role,
|
||||
uid: result._id,
|
||||
email: result.email,
|
||||
add_time: result.add_time,
|
||||
up_time: result.up_time,
|
||||
type: 'site',
|
||||
study: result.study
|
||||
},
|
||||
0,
|
||||
'logout success...'
|
||||
));
|
||||
} else {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 405, '密码错误'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录接口
|
||||
* @interface /user/logout
|
||||
* @method GET
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @returns {Object}
|
||||
* @example ./api/user/logout.json
|
||||
*/
|
||||
|
||||
async logout(ctx) {
|
||||
ctx.cookies.set('_yapi_token', null);
|
||||
ctx.cookies.set('_yapi_uid', null);
|
||||
ctx.body = yapi.commons.resReturn('ok');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新
|
||||
* @interface /user/up_study
|
||||
* @method GET
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async upStudy(ctx) {
|
||||
let userInst = yapi.getInst(userModel); //创建user实体
|
||||
let data = {
|
||||
up_time: yapi.commons.time(),
|
||||
study: true
|
||||
};
|
||||
try {
|
||||
let result = await userInst.update(this.getUid(), data);
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 401, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async loginByToken(ctx) {
|
||||
try {
|
||||
let ret = await yapi.emitHook('third_login', ctx);
|
||||
let login = await this.handleThirdLogin(ret.email, ret.username);
|
||||
if (login === true) {
|
||||
yapi.commons.log('login success');
|
||||
ctx.redirect('/group');
|
||||
}
|
||||
} catch (e) {
|
||||
yapi.commons.log(e.message, 'error');
|
||||
ctx.redirect('/');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ldap登录
|
||||
* @interface /user/login_by_ldap
|
||||
* @method
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @param {String} email email名称,不能为空
|
||||
* @param {String} password 密码,不能为空
|
||||
* @returns {Object}
|
||||
*
|
||||
*/
|
||||
async getLdapAuth(ctx) {
|
||||
try {
|
||||
const { email, password } = ctx.request.body;
|
||||
// const username = email.split(/\@/g)[0];
|
||||
const { info: ldapInfo } = await ldap.ldapQuery(email, password);
|
||||
const emailPrefix = email.split(/\@/g)[0];
|
||||
const emailPostfix = yapi.WEBCONFIG.ldapLogin.emailPostfix;
|
||||
|
||||
const emailParams =
|
||||
ldapInfo[yapi.WEBCONFIG.ldapLogin.emailKey || 'mail'] ||
|
||||
(emailPostfix ? emailPrefix + emailPostfix : email);
|
||||
const username = ldapInfo[yapi.WEBCONFIG.ldapLogin.usernameKey] || emailPrefix;
|
||||
|
||||
let login = await this.handleThirdLogin(emailParams, username);
|
||||
|
||||
if (login === true) {
|
||||
let userInst = yapi.getInst(userModel); //创建user实体
|
||||
let result = await userInst.findByEmail(emailParams);
|
||||
return (ctx.body = yapi.commons.resReturn(
|
||||
{
|
||||
username: result.username,
|
||||
role: result.role,
|
||||
uid: result._id,
|
||||
email: result.email,
|
||||
add_time: result.add_time,
|
||||
up_time: result.up_time,
|
||||
type: result.type || 'third',
|
||||
study: result.study
|
||||
},
|
||||
0,
|
||||
'logout success...'
|
||||
));
|
||||
}
|
||||
} catch (e) {
|
||||
yapi.commons.log(e.message, 'error');
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, e.message));
|
||||
}
|
||||
}
|
||||
|
||||
// 处理第三方登录
|
||||
async handleThirdLogin(email, username) {
|
||||
let user, data, passsalt;
|
||||
let userInst = yapi.getInst(userModel);
|
||||
|
||||
try {
|
||||
user = await userInst.findByEmail(email);
|
||||
|
||||
// 新建用户信息
|
||||
if (!user || !user._id) {
|
||||
passsalt = yapi.commons.randStr();
|
||||
data = {
|
||||
username: username,
|
||||
password: yapi.commons.generatePassword(passsalt, passsalt),
|
||||
email: email,
|
||||
passsalt: passsalt,
|
||||
role: 'member',
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time(),
|
||||
type: 'third'
|
||||
};
|
||||
user = await userInst.save(data);
|
||||
await this.handlePrivateGroup(user._id, username, email);
|
||||
yapi.commons.sendMail({
|
||||
to: email,
|
||||
contents: `<h3>亲爱的用户:</h3><p>您好,感谢使用YApi平台,你的邮箱账号是:${email}</p>`
|
||||
});
|
||||
}
|
||||
|
||||
this.setLoginCookie(user._id, user.passsalt);
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('third_login:', e.message); // eslint-disable-line
|
||||
throw new Error(`third_login: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改用户密码
|
||||
* @interface /user/change_password
|
||||
* @method POST
|
||||
* @category user
|
||||
* @param {Number} uid 用户ID
|
||||
* @param {Number} [old_password] 旧密码, 非admin用户必须传
|
||||
* @param {Number} password 新密码
|
||||
* @return {Object}
|
||||
* @example ./api/user/change_password.json
|
||||
*/
|
||||
async changePassword(ctx) {
|
||||
let params = ctx.request.body;
|
||||
let userInst = yapi.getInst(userModel);
|
||||
|
||||
if (!params.uid) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'uid不能为空'));
|
||||
}
|
||||
|
||||
if (!params.password) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '密码不能为空'));
|
||||
}
|
||||
|
||||
let user = await userInst.findById(params.uid);
|
||||
if (this.getRole() !== 'admin' && params.uid != this.getUid()) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 402, '没有权限'));
|
||||
}
|
||||
|
||||
if (this.getRole() !== 'admin' || user.role === 'admin') {
|
||||
if (!params.old_password) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '旧密码不能为空'));
|
||||
}
|
||||
|
||||
if (yapi.commons.generatePassword(params.old_password, user.passsalt) !== user.password) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 402, '旧密码错误'));
|
||||
}
|
||||
}
|
||||
|
||||
let passsalt = yapi.commons.randStr();
|
||||
let data = {
|
||||
up_time: yapi.commons.time(),
|
||||
password: yapi.commons.generatePassword(params.password, passsalt),
|
||||
passsalt: passsalt
|
||||
};
|
||||
try {
|
||||
let result = await userInst.update(params.uid, data);
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 401, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async handlePrivateGroup(uid) {
|
||||
var groupInst = yapi.getInst(groupModel);
|
||||
await groupInst.save({
|
||||
uid: uid,
|
||||
group_name: 'User-' + uid,
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time(),
|
||||
type: 'private'
|
||||
});
|
||||
}
|
||||
|
||||
setLoginCookie(uid, passsalt) {
|
||||
let token = jwt.sign({ uid: uid }, passsalt, { expiresIn: '7 days' });
|
||||
|
||||
this.ctx.cookies.set('_yapi_token', token, {
|
||||
expires: yapi.commons.expireDate(7),
|
||||
httpOnly: true
|
||||
});
|
||||
this.ctx.cookies.set('_yapi_uid', uid, {
|
||||
expires: yapi.commons.expireDate(7),
|
||||
httpOnly: true
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户注册接口
|
||||
* @interface /user/reg
|
||||
* @method POST
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @param {String} email email名称,不能为空
|
||||
* @param {String} password 密码,不能为空
|
||||
* @param {String} [username] 用户名
|
||||
* @returns {Object}
|
||||
* @example ./api/user/login.json
|
||||
*/
|
||||
async reg(ctx) {
|
||||
//注册
|
||||
if (yapi.WEBCONFIG.closeRegister) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '禁止注册,请联系管理员'));
|
||||
}
|
||||
let userInst = yapi.getInst(userModel);
|
||||
let params = ctx.request.body; //获取请求的参数,检查是否存在用户名和密码
|
||||
|
||||
params = yapi.commons.handleParams(params, {
|
||||
username: 'string',
|
||||
password: 'string',
|
||||
email: 'string'
|
||||
});
|
||||
|
||||
if (!params.email) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '邮箱不能为空'));
|
||||
}
|
||||
|
||||
if (!params.password) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '密码不能为空'));
|
||||
}
|
||||
|
||||
let checkRepeat = await userInst.checkRepeat(params.email); //然后检查是否已经存在该用户
|
||||
|
||||
if (checkRepeat > 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, '该email已经注册'));
|
||||
}
|
||||
|
||||
let passsalt = yapi.commons.randStr();
|
||||
let data = {
|
||||
username: params.username,
|
||||
password: yapi.commons.generatePassword(params.password, passsalt), //加密
|
||||
email: params.email,
|
||||
passsalt: passsalt,
|
||||
role: 'member',
|
||||
add_time: yapi.commons.time(),
|
||||
up_time: yapi.commons.time(),
|
||||
type: 'site'
|
||||
};
|
||||
|
||||
if (!data.username) {
|
||||
data.username = data.email.substr(0, data.email.indexOf('@'));
|
||||
}
|
||||
|
||||
try {
|
||||
let user = await userInst.save(data);
|
||||
|
||||
this.setLoginCookie(user._id, user.passsalt);
|
||||
await this.handlePrivateGroup(user._id, user.username, user.email);
|
||||
ctx.body = yapi.commons.resReturn({
|
||||
uid: user._id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
add_time: user.add_time,
|
||||
up_time: user.up_time,
|
||||
role: 'member',
|
||||
type: user.type,
|
||||
study: false
|
||||
});
|
||||
yapi.commons.sendMail({
|
||||
to: user.email,
|
||||
contents: `<h3>亲爱的用户:</h3><p>您好,感谢使用YApi可视化接口平台,您的账号 ${
|
||||
params.email
|
||||
} 已经注册成功</p>`
|
||||
});
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 401, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户列表
|
||||
* @interface /user/list
|
||||
* @method GET
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @param {Number} [page] 分页页码
|
||||
* @param {Number} [limit] 分页大小,默认为10条
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async list(ctx) {
|
||||
let page = ctx.request.query.page || 1,
|
||||
limit = ctx.request.query.limit || 10;
|
||||
|
||||
const userInst = yapi.getInst(userModel);
|
||||
try {
|
||||
let user = await userInst.listWithPaging(page, limit);
|
||||
let count = await userInst.listCount();
|
||||
return (ctx.body = yapi.commons.resReturn({
|
||||
count: count,
|
||||
total: Math.ceil(count / limit),
|
||||
list: user
|
||||
}));
|
||||
} catch (e) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 402, e.message));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户个人信息
|
||||
* @interface /user/find
|
||||
* @method GET
|
||||
* @param id 用户uid
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async findById(ctx) {
|
||||
//根据id获取用户信息
|
||||
try {
|
||||
let userInst = yapi.getInst(userModel);
|
||||
let id = ctx.request.query.id;
|
||||
|
||||
if (this.getRole() !== 'admin' && id != this.getUid()) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, '没有权限'));
|
||||
}
|
||||
|
||||
if (!id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'uid不能为空'));
|
||||
}
|
||||
|
||||
let result = await userInst.findById(id);
|
||||
|
||||
if (!result) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 402, '不存在的用户'));
|
||||
}
|
||||
|
||||
return (ctx.body = yapi.commons.resReturn({
|
||||
uid: result._id,
|
||||
username: result.username,
|
||||
email: result.email,
|
||||
role: result.role,
|
||||
type: result.type,
|
||||
add_time: result.add_time,
|
||||
up_time: result.up_time
|
||||
}));
|
||||
} catch (e) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 402, e.message));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除用户,只有admin用户才有此权限
|
||||
* @interface /user/del
|
||||
* @method POST
|
||||
* @param id 用户uid
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async del(ctx) {
|
||||
//根据id删除一个用户
|
||||
try {
|
||||
if (this.getRole() !== 'admin') {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 402, 'Without permission.'));
|
||||
}
|
||||
|
||||
let userInst = yapi.getInst(userModel);
|
||||
let id = ctx.request.body.id;
|
||||
if (id == this.getUid()) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 403, '禁止删除管理员'));
|
||||
}
|
||||
if (!id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'uid不能为空'));
|
||||
}
|
||||
|
||||
let result = await userInst.del(id);
|
||||
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户个人信息
|
||||
* @interface /user/update
|
||||
* @method POST
|
||||
* @param uid 用户uid
|
||||
* @param [role] 用户角色,只有管理员有权限修改
|
||||
* @param [username] String
|
||||
* @param [email] String
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
async update(ctx) {
|
||||
//更新用户信息
|
||||
try {
|
||||
let params = ctx.request.body;
|
||||
|
||||
params = yapi.commons.handleParams(params, {
|
||||
username: 'string',
|
||||
email: 'string'
|
||||
});
|
||||
|
||||
if (this.getRole() !== 'admin' && params.uid != this.getUid()) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, '没有权限'));
|
||||
}
|
||||
|
||||
let userInst = yapi.getInst(userModel);
|
||||
let id = params.uid;
|
||||
|
||||
if (!id) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'uid不能为空'));
|
||||
}
|
||||
|
||||
let userData = await userInst.findById(id);
|
||||
if (!userData) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'uid不存在'));
|
||||
}
|
||||
|
||||
let data = {
|
||||
up_time: yapi.commons.time()
|
||||
};
|
||||
|
||||
params.username && (data.username = params.username);
|
||||
params.email && (data.email = params.email);
|
||||
|
||||
if (data.email) {
|
||||
var checkRepeat = await userInst.checkRepeat(data.email); //然后检查是否已经存在该用户
|
||||
if (checkRepeat > 0) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 401, '该email已经注册'));
|
||||
}
|
||||
}
|
||||
|
||||
let member = {
|
||||
uid: id,
|
||||
username: data.username || userData.username,
|
||||
email: data.email || userData.email
|
||||
};
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
await groupInst.updateMember(member);
|
||||
let projectInst = yapi.getInst(projectModel);
|
||||
await projectInst.updateMember(member);
|
||||
|
||||
let result = await userInst.update(id, data);
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 402, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传用户头像
|
||||
* @interface /user/upload_avatar
|
||||
* @method POST
|
||||
* @param {*} basecode base64编码,通过h5 api传给后端
|
||||
* @category user
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async uploadAvatar(ctx) {
|
||||
try {
|
||||
let basecode = ctx.request.body.basecode;
|
||||
if (!basecode) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, 'basecode不能为空'));
|
||||
}
|
||||
let pngPrefix = 'data:image/png;base64,';
|
||||
let jpegPrefix = 'data:image/jpeg;base64,';
|
||||
let type;
|
||||
if (basecode.substr(0, pngPrefix.length) === pngPrefix) {
|
||||
basecode = basecode.substr(pngPrefix.length);
|
||||
type = 'image/png';
|
||||
} else if (basecode.substr(0, jpegPrefix.length) === jpegPrefix) {
|
||||
basecode = basecode.substr(jpegPrefix.length);
|
||||
type = 'image/jpeg';
|
||||
} else {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '仅支持jpeg和png格式的图片'));
|
||||
}
|
||||
let strLength = basecode.length;
|
||||
if (parseInt(strLength - (strLength / 8) * 2) > 200000) {
|
||||
return (ctx.body = yapi.commons.resReturn(null, 400, '图片大小不能超过200kb'));
|
||||
}
|
||||
|
||||
let avatarInst = yapi.getInst(avatarModel);
|
||||
let result = await avatarInst.up(this.getUid(), basecode, type);
|
||||
ctx.body = yapi.commons.resReturn(result);
|
||||
} catch (e) {
|
||||
ctx.body = yapi.commons.resReturn(null, 401, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据用户uid头像
|
||||
* @interface /user/avatar
|
||||
* @method GET
|
||||
* @param {*} uid
|
||||
* @category user
|
||||
* @returns {Object}
|
||||
* @example
|
||||
*/
|
||||
|
||||
async avatar(ctx) {
|
||||
try {
|
||||
let uid = ctx.query.uid ? ctx.query.uid : this.getUid();
|
||||
let avatarInst = yapi.getInst(avatarModel);
|
||||
let data = await avatarInst.get(uid);
|
||||
let dataBuffer, type;
|
||||
if (!data || !data.basecode) {
|
||||
dataBuffer = yapi.fs.readFileSync(yapi.path.join(yapi.WEBROOT, 'static/image/avatar.png'));
|
||||
type = 'image/png';
|
||||
} else {
|
||||
type = data.type;
|
||||
dataBuffer = new Buffer(data.basecode, 'base64');
|
||||
}
|
||||
|
||||
ctx.set('Content-type', type);
|
||||
ctx.body = dataBuffer;
|
||||
} catch (err) {
|
||||
ctx.body = 'error:' + err.message;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 模糊搜索用户名或者email
|
||||
* @interface /user/search
|
||||
* @method GET
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @param {String} q
|
||||
* @return {Object}
|
||||
* @example ./api/user/search.json
|
||||
*/
|
||||
async search(ctx) {
|
||||
const { q } = ctx.request.query;
|
||||
|
||||
if (!q) {
|
||||
return (ctx.body = yapi.commons.resReturn(void 0, 400, 'No keyword.'));
|
||||
}
|
||||
|
||||
if (!yapi.commons.validateSearchKeyword(q)) {
|
||||
return (ctx.body = yapi.commons.resReturn(void 0, 400, 'Bad query.'));
|
||||
}
|
||||
|
||||
let queryList = await this.Model.search(q);
|
||||
let rules = [
|
||||
{
|
||||
key: '_id',
|
||||
alias: 'uid'
|
||||
},
|
||||
'username',
|
||||
'email',
|
||||
'role',
|
||||
{
|
||||
key: 'add_time',
|
||||
alias: 'addTime'
|
||||
},
|
||||
{
|
||||
key: 'up_time',
|
||||
alias: 'upTime'
|
||||
}
|
||||
];
|
||||
|
||||
let filteredRes = common.filterRes(queryList, rules);
|
||||
|
||||
return (ctx.body = yapi.commons.resReturn(filteredRes, 0, 'ok'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据路由id初始化项目数据
|
||||
* @interface /user/project
|
||||
* @method GET
|
||||
* @category user
|
||||
* @foldnumber 10
|
||||
* @param {String} type 可选group|interface|project
|
||||
* @param {Number} id
|
||||
* @return {Object}
|
||||
* @example
|
||||
*/
|
||||
async project(ctx) {
|
||||
let { id, type } = ctx.request.query;
|
||||
let result = {};
|
||||
try {
|
||||
if (type === 'interface') {
|
||||
let interfaceInst = yapi.getInst(interfaceModel);
|
||||
let interfaceData = await interfaceInst.get(id);
|
||||
result.interface = interfaceData;
|
||||
type = 'project';
|
||||
id = interfaceData.project_id;
|
||||
}
|
||||
|
||||
if (type === 'project') {
|
||||
let projectInst = yapi.getInst(projectModel);
|
||||
let projectData = await projectInst.get(id);
|
||||
result.project = projectData.toObject();
|
||||
let ownerAuth = await this.checkAuth(id, 'project', 'danger'),
|
||||
devAuth;
|
||||
if (ownerAuth) {
|
||||
result.project.role = 'owner';
|
||||
} else {
|
||||
devAuth = await this.checkAuth(id, 'project', 'site');
|
||||
if (devAuth) {
|
||||
result.project.role = 'dev';
|
||||
} else {
|
||||
result.project.role = 'member';
|
||||
}
|
||||
}
|
||||
type = 'group';
|
||||
id = projectData.group_id;
|
||||
}
|
||||
|
||||
if (type === 'group') {
|
||||
let groupInst = yapi.getInst(groupModel);
|
||||
let groupData = await groupInst.get(id);
|
||||
result.group = groupData.toObject();
|
||||
let ownerAuth = await this.checkAuth(id, 'group', 'danger'),
|
||||
devAuth;
|
||||
if (ownerAuth) {
|
||||
result.group.role = 'owner';
|
||||
} else {
|
||||
devAuth = await this.checkAuth(id, 'group', 'site');
|
||||
if (devAuth) {
|
||||
result.group.role = 'dev';
|
||||
} else {
|
||||
result.group.role = 'member';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (ctx.body = yapi.commons.resReturn(result));
|
||||
} catch (e) {
|
||||
return (ctx.body = yapi.commons.resReturn(result, 422, e.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = userController;
|
||||
Reference in New Issue
Block a user