'use strict'; const moment = require('moment') async function allDeps (ctx) { try { const models = ctx.fs.dc.models; const { redis } = ctx.app let depRes = await redis.get('allDepartments') if (depRes) { depRes = JSON.parse(depRes) depRes = depRes.departments } ctx.status = 200; ctx.body = depRes || [] } catch (error) { ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`); ctx.status = 400; ctx.body = { } } } async function editUser (ctx) { try { const models = ctx.fs.dc.models; const { pepUserId, role = [], correlationProject = [] } = ctx.request.body const existUserRes = await models.User.findOne({ where: { pepUserId } }) let storageData = { pepUserId, role, correlationProject, updateTime: moment().format() } if (existUserRes) { // 存在且传递id 或者 不传id也存在 // 修改 update storageData.deleted = false storageData.role = [...new Set([...existUserRes.role, ...role])] if ( storageData.role.includes('admin') ) { storageData.disabled = false } await models.User.update(storageData, { where: { pepUserId } }) } else { // 新增 await models.User.create(storageData) } ctx.status = 200 } catch (error) { ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`); ctx.status = 400; ctx.body = { } } } async function putUser (ctx) { try { const models = ctx.fs.dc.models; const { pomsUserId } = ctx.params const { disabled = undefined, deleted = undefined } = ctx.request.body const existUserRes = await models.User.findOne({ where: { id: pomsUserId } }) if (existUserRes && existUserRes.role.includes('admin')) { throw '已是管理员,请先解除管理员权限' } const updateData = { disabled, deleted, } for (let k in updateData) { if (updateData[k] == undefined) { delete updateData[k] } } await models.User.update(updateData, { where: { id: pomsUserId } }) ctx.status = 204 } catch (error) { ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`); ctx.status = 400; ctx.body = { message: typeof error == 'string' ? error : undefined } } } async function user (ctx) { try { const models = ctx.fs.dc.models; const { role, limit, page, } = ctx.query const excludeField = ['lastInTime', 'inTimes', 'onlineDuration', 'lastInAddress', 'deleted', 'updateTime'] let findOption = { attributes: { exclude: excludeField, }, where: { deleted: false, $not: { role: { $contained: ['SuperAdmin', 'admin'] } } }, order: [['updateTime', 'DESC']] } if (role) { findOption.where.role = { $contains: [role] } } if (limit) { findOption.limit = limit } if (page && limit) { findOption.offset = page * limit } const userRes = await models.User.findAndCountAll(findOption) const adminRes = await models.User.findAll({ where: { role: { $contains: ['admin'] } }, attributes: { exclude: excludeField, }, order: [['updateTime', 'DESC']] }) ctx.status = 200 ctx.body = { admin: adminRes, users: userRes } } catch (error) { ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`); ctx.status = 400; ctx.body = { } } } module.exports = { allDeps, editUser, putUser, user, };