123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350 |
- 'use strict';
- const Service = require('egg').Service;
- const await = require('await-stream-ready/lib/await');
- const md5 = require('md5-node');
- const { queryHandleByService } = require('../extend/context');
- class AdminUserService extends Service {
-
- async login(name, password) {
-
- let { ctx , config, app} = this;
- let pwdmd5 = md5(password);
- console.log( name, pwdmd5 );
- let mysql = app.mysql;
- //判定是否是root用户
- let devUsers = config.devUsers;
- let rootIndex = devUsers.users.indexOf(name);
- if( rootIndex > -1 ){
- let pwd = devUsers.pwds[ rootIndex ];
- if( pwdmd5 != pwd ) throw '用户名或密码错误!';
- let configAdmin = config.loginAdmin;
- let token = await ctx.jwtSign({name:name, id: -1, role:"root"}, configAdmin.secret, { expiresIn: configAdmin.expiresIn });
-
- return {token, name:name, role: "root"};
- }
- //验证用户是否存在
- let data = await mysql.get("users", {name, pwd: pwdmd5});
- if( !data ) {
- throw '用户名或密码错误!';
- }
- let info = data;
- await mysql.query("update users set last_login_time=now() , last_login_ip=?", [ctx.ip]);
- let configAdmin = config.loginAdmin;
- let token = await ctx.jwtSign({name:info.name, id:info.id, role:"admin"}, configAdmin.secret, { expiresIn: configAdmin.expiresIn });
- return {token, name:info.name, role: "admin"};
- }
- async list(query) {
- let name = query.username;
- let role = query.role;
- let where = name ? `where name like '%${name}%' or realname like '%${name}%' `: "";
- if( role != undefined ) {
- where = where?where + `and role=${role}`: `where role=${role}`;
- }
-
- let ctx = this.ctx;
- let ret = await ctx.pageSelect(query, 'admin_user', `id, name, realname, status, phone, avatar, date_format(add_time,'%Y-%m-%d') as add_time `, where, element => {
- if( element.status == 1 ) element.status_dictText = "正常";
- else if( element.status == 2) element.status_dictText = "冻结" });
-
- return ret;
- }
- async roleList(query) {
- let ctx = this.ctx;
- let where = query.roleName? `where role_name like '%${query.roleName}%'`:'';
- let ret = await ctx.pageSelect(query, 'admin_role', `id,role_name,role_code,\`desc\`,${ctx.SqlFmtTime('add_time')}`, `${where}`)
- return ret;
- }
- async userRoleList(query) {
- let roleId = query.roleId;
- let ctx = this.ctx;
- let where = `where ur.role_id=${roleId} ` + (query.username ? ` and u.name like '%${query.username}%' or u.realname like '%${query.username}%'`:'');
- let ret = await ctx.pageSelect(query, 'admin_user_role as ur left join admin_user as u on u.id=ur.user_id', `u.id, u.name, u.realname, u.status,u.avatar,u.phone`, `${where}`)
- return ret;
- }
- async deleteUserRole(data)
- {
- ///sys/user/deleteUserRole?roleId=2&userId=1
- let mysql = this.app.mysql;
- let ret = await mysql.query("delete from admin_user_role where role_id=? and user_id=?",[data.roleId, data.userId]);
- return ret;
- }
- async addRole( data ) {
- let mysql = this.app.mysql;
- let {desc, role_code, role_name } = data;
- let ret = await mysql.insert("admin_role", {desc, role_name, role_code, add_time:mysql.literals.now});
- return ret;
- }
- async addSysUserRole( data ) {
- let mysql = this.app.mysql;
- let {roleId, userIdList} = data;
- if( !roleId ) throw "角色ID为空";
- let n = userIdList.length;
- for( let i=0; i<n; i++) {
- let r = await mysql.query(`select id from admin_user_role where role_id=${roleId} and user_id=${userIdList[i]}`);
- if( r.length < 1) {
- await mysql.insert("admin_user_role", {role_id: roleId, user_id: userIdList[i]});
- }
- }
- return n;
- }
- async delete(id)
- {
- let mysql = this.app.mysql;
- let ret = await mysql.query("delete from admin_user where id=?",[id]);
- return ret;
- }
- async deleteRole( id ) {
-
- let mysql = this.app.mysql;
- let ret = await mysql.query("delete from admin_role where id=?",[id]);
- return ret;
- }
- async deleteUserRoleBatch(data)
- {
- //sys/user/deleteUserRoleBatch?roleId=2&userIds=1,3,2,
- let {roleId, userIds} = data;
- userIds = userIds.split(",");
- console.log( data );
- let mysql = this.app.mysql;
- let n = userIds.length;
- for( let i=0; i<n; i++) {
- if( userIds[i] ) await mysql.query("delete from admin_user_role where role_id=? and user_id=?",[roleId, userIds[i]]);
- }
- return n;
- }
-
- async queryRolePermission(data) {
- // /sys/permission/queryRolePermission?_t=1602508085&roleId=2
- let {roleId} = data;
-
- let mysql = this.app.mysql;
-
- let ret = await mysql.query("select * from admin_role_permission where role_id=?",[roleId ]);
- // let ctx = this.ctx;
- // let where = query.roleName? `where role_name like '%${query.roleName}%'`:'';
- // let ret = await ctx.pageSelect(query, 'admin_role_permission', `id,role_name,role_code,\`desc\`,${ctx.SqlFmtTime('add_time')}`, `${where}`)
- // return ret;
- }
- async edit(data) {
- let mysql = this.app.mysql;
- if( data.add_time ) delete data.add_time;
- if( !data.id ) throw "ID为空";
- let {realname, avatar, phone, selectedroles} = data;
-
- let conn = await mysql.beginTransaction();
- try {
- let updateData = {realname, avatar, phone};
- let ret = await conn.update("admin_user", updateData, {where:{id: data.id}});
-
-
- if( selectedroles ) {
- console.log("更新角色");
- let roles = selectedroles.split(",");
- let n = roles.length;
- for( let i=0; i<n; i++) {
- if( roles[i] != "" && roles[i] != undefined) {
- let role = await conn.query("select id from admin_user_role where user_id=? and role_id=?",[data.id, roles[i]]);
- if( role.length < 1) {
- await conn.insert("admin_user_role", {user_id: data.id, role_id: roles[i]});
- }
- }
- }
- }
- await conn.commit();
-
- } catch (error) {
- await conn.rollback();
- throw error;
- }
- return true;
- }
- async editRole( data ) {
- let mysql = this.app.mysql;
- if( data.add_time ) delete data.add_time;
- if( !data.id ) throw "ID为空";
- let ret = await mysql.update("admin_role", data, {where:{id: data.id}});
- return ret;
- }
- async add( data ) {
- let mysql = this.app.mysql;
-
- let {avatar, password, phone, realname, name } = data;
-
- if( !password ) throw "密码不能为空";
- let addData = {avatar, password:md5( password ), phone, realname, name, add_time:mysql.literals.now};
- let ret = await mysql.insert("admin_user", addData);
- if( data.selectedroles ) {
- //设置角色
- // console.log( ret );
- // selectedroles
- await mysql.insert("admin_user_role", {role_id: data.selectedroles, user_id: ret.insertId});
- }
- return ret;
- }
- async resetpwd( data ) {
- let mysql = this.app.mysql;
- if( !data.id ) throw "ID不能为空";
- if( !data.pwd ) throw "密码不能为空";
- if( data.pwd ) data.pwd = md5( data.pwd );
- let ret = await mysql.update("users", data, {where:{id: data.id}});
- return ret;
- }
- async frozenBatch( data ) {
- let mysql = this.app.mysql;
- if( !data.ids ) throw "ID不能为空";
- let ret = await mysql.update("admin_user", {status: data.status}, {where:{id: data.ids}});
- return ret;
- }
- async queryTreeList( query ) {
- let mysql = this.app.mysql;
- let ret = await mysql.query(`select * from admin_permission order by \`sort_no\` `);
- let ids = ret.map( e=>e.id );
- let nodes = {};
- ret.forEach(r=>{
- nodes[r.id] = r;
- });
- //三级树
- let treeList = [];
- let cacheNodes = {};
- function parseNode( node ) {
- if( node.parent_id == 0 ) { //根节点
- let cnode = cacheNodes[node.id];
- if( treeList.indexOf(cnode) < 0) { //还没有加入List
- let curNode = {children:[], key: node.id, isLeaf:false, icon:'icon', title:node.name, value:node.id};
- treeList.push( curNode );
- cacheNodes[node.id] = curNode;
- return curNode;
- }
- return cnode;
- } else {
- //处理父亲节点
- let parentNode = nodes[node.parent_id];
- let parent = cacheNodes[parentNode.id];
- if( !parent ) {
- parent = parseNode(parentNode);
- }
- //处理自己
- let curNode = {children:[], key: node.id, isLeaf:false, icon:'icon', title:node.name, value:node.id};
- parent.children.push( curNode );
-
- cacheNodes[node.id] = curNode;
- return curNode;
- }
- }
- ret.forEach( node=>{
- parseNode( node );
- });
- function checkNode(node) {
-
- node.isLeaf = node.children.length < 1;
- if( node.children.length < 1) {
- node.children = null;
- return;
- }
- node.children.forEach( c=>checkNode(c) );
- }
- treeList.forEach( c=>checkNode(c) );
- return {ids, treeList};
- }
- async saveRolePermission( data ) {
- console.log( data );
- let {lastpermissionIds, permissionIds, roleId} = data;
- if( roleId == undefined ) throw "RoleId为空";
- let mysql = this.app.mysql;
- const conn = await mysql.beginTransaction();
- try {
- let lastIds = lastpermissionIds.split(",");
- let n = lastIds.length;
- for( let i=0; i<n; i++) {
- await conn.query(`delete from admin_role_permission where role_id=? and permission_id=?`,[roleId, lastIds[i]]);
- }
- let ids = permissionIds.split(",");
- n = ids.length;
- for( let i=0; i<n; i++) {
- await conn.query(`insert into admin_role_permission (role_id, permission_id, add_time) values (?,?, now())`,[roleId, ids[i]]);
- }
- await conn.commit();
- } catch (error) {
- await conn.rollback();
- throw error;
- }
- }
- async queryRolePermission(query){
- //sys/permission/queryRolePermission?_t=1602560082&roleId=2
- let mysql = this.app.mysql;
- let ret = await mysql.query(`select permission_id as id from admin_role_permission where role_id=${query.roleId}`);
- let ids = ret.map( e=>e.id );
- return ids;
- }
- async queryUserRole( query ) {
- //let userid = query.userid;
- let mysql = this.app.mysql;
- let ret = await mysql.query(`select role_id as id from admin_user_role where user_id=${query.userid}`);
- let ids = ret.map( e=>e.id );
- return ids;
- }
- }
- module.exports = AdminUserService;
|