dflzm
Version:
x
184 lines (172 loc) • 3.3 kB
JavaScript
const selectPath = async (ctx, group_id) => {
try {
const attributes = ['path_id']
const rst = await ctx.sql.auth_group
.findOne({
attributes,
where: {
group_id,
}
})
if (rst) {
return rst.path_id
}
return
} catch (err) {
ctx.logger.error(err)
}
}
/**
* @brief select user
*
* @param user_id
*
* @return {} or []
*/
const selectAuth = async (ctx) => {
try {
const { user_id } = ctx.query
const attributes = ['user_id', 'path_id', 'group_id', 'created_at', 'updated_at']
let rst, all_path = []
if (user_id) {
rst = await ctx.sql.user_auth
.findOne({
attributes,
where: {
user_id,
}
})
} else {
rst = await ctx.sql.user_auth
.findAll({
attributes
})
}
if (user_id && rst) {
all_path = all_path.concat(rst.path_id.split(','))
const group = rst.group_id.split(',')
for (let i = group.length; i >= 0 ; i--) {
const sp = await new Promise((resolve) => {
resolve(selectPath(ctx, group[i]))
})
if (sp) all_path = all_path.concat(sp.split(','))
}
all_path = Array.from(new Set(all_path))
rst.dataValues.all_path = all_path
}
ctx.body = {
code: rst ? 0 : 1,
msg: (user_id && !rst) || (!user_id && !rst.length) ? '没有匹配的查询结果' : '',
data: rst ? rst : user_id ? {} : [],
}
} catch (err) {
ctx.logger.error(err)
ctx.body = {
code: 1,
msg: 'error',
data: {},
}
}
}
/**
* @brief create auth
*
* @param user_id, path_id, group_id
*
* @return {}
*/
const createAuth = async (ctx) => {
try {
const {
user_id,
path_id,
group_id,
} = ctx.request.body
const rst = await ctx.sql.user_auth
.create({
user_id,
path_id,
group_id,
})
ctx.body = {
code: 0,
msg: '',
data: rst,
}
} catch (err) {
ctx.logger.error(err)
ctx.body = {
code: 1,
msg: 'error',
data: {},
}
}
}
const updateAuth = async (ctx) => {
try {
const {
user_id,
path_id,
group_id,
} = ctx.request.body
const rst = await ctx.sql.user_auth
.update({
path_id,
group_id,
}, {
where: {
user_id
}
})
ctx.body = {
code: rst[0] ? 0 : 1,
msg: rst[0] ? '' : '没有匹配的数据项',
data: rst,
}
} catch (err) {
ctx.logger.error(err)
ctx.body = {
code: 1,
msg: 'error',
data: {},
}
}
}
/**
* @brief delete user
*
* @param ctx
*
* @return row
*/
const deleteAuth = async (ctx) => {
try {
const {
user_id,
} = ctx.request.body
const rst = await ctx.sql.user_auth
.destroy({
where: {
user_id
}
})
ctx.body = {
code: 0,
msg: '',
data: rst,
}
} catch (err) {
ctx.logger.error(err)
ctx.body = {
code: 1,
msg: 'error',
data: {},
}
}
}
module.exports = {
'GET /user_auth': selectAuth,
'PUT /user_auth': updateAuth,
'POST /user_auth': createAuth,
'DELETE /user_auth': deleteAuth,
}