sysUser.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. const await = require('await-stream-ready/lib/await');
  4. const md5 = require('md5-node');
  5. const { queryHandleByService } = require('../extend/context');
  6. class AdminUserService extends Service {
  7. async login(name, password) {
  8. let { ctx , config, app} = this;
  9. let pwdmd5 = md5(password);
  10. console.log( name, pwdmd5 );
  11. let mysql = app.mysql;
  12. //判定是否是root用户
  13. let devUsers = config.devUsers;
  14. let rootIndex = devUsers.users.indexOf(name);
  15. if( rootIndex > -1 ){
  16. let pwd = devUsers.pwds[ rootIndex ];
  17. if( pwdmd5 != pwd ) throw '用户名或密码错误!';
  18. let configAdmin = config.loginAdmin;
  19. let token = await ctx.jwtSign({name:name, id: -1, role:"root"}, configAdmin.secret, { expiresIn: configAdmin.expiresIn });
  20. return {token, name:name, role: "root"};
  21. }
  22. //验证用户是否存在
  23. let data = await mysql.get("users", {name, pwd: pwdmd5});
  24. if( !data ) {
  25. throw '用户名或密码错误!';
  26. }
  27. let info = data;
  28. await mysql.query("update users set last_login_time=now() , last_login_ip=?", [ctx.ip]);
  29. let configAdmin = config.loginAdmin;
  30. let token = await ctx.jwtSign({name:info.name, id:info.id, role:"admin"}, configAdmin.secret, { expiresIn: configAdmin.expiresIn });
  31. return {token, name:info.name, role: "admin"};
  32. }
  33. async list(query) {
  34. let name = query.username;
  35. let role = query.role;
  36. let where = name ? `where name like '%${name}%' or realname like '%${name}%' `: "";
  37. if( role != undefined ) {
  38. where = where?where + `and role=${role}`: `where role=${role}`;
  39. }
  40. let ctx = this.ctx;
  41. 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 => {
  42. if( element.status == 1 ) element.status_dictText = "正常";
  43. else if( element.status == 2) element.status_dictText = "冻结" });
  44. return ret;
  45. }
  46. async roleList(query) {
  47. let ctx = this.ctx;
  48. let where = query.roleName? `where role_name like '%${query.roleName}%'`:'';
  49. let ret = await ctx.pageSelect(query, 'admin_role', `id,role_name,role_code,\`desc\`,${ctx.SqlFmtTime('add_time')}`, `${where}`)
  50. return ret;
  51. }
  52. async userRoleList(query) {
  53. let roleId = query.roleId;
  54. let ctx = this.ctx;
  55. let where = `where ur.role_id=${roleId} ` + (query.username ? ` and u.name like '%${query.username}%' or u.realname like '%${query.username}%'`:'');
  56. 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}`)
  57. return ret;
  58. }
  59. async deleteUserRole(data)
  60. {
  61. ///sys/user/deleteUserRole?roleId=2&userId=1
  62. let mysql = this.app.mysql;
  63. let ret = await mysql.query("delete from admin_user_role where role_id=? and user_id=?",[data.roleId, data.userId]);
  64. return ret;
  65. }
  66. async addRole( data ) {
  67. let mysql = this.app.mysql;
  68. let {desc, role_code, role_name } = data;
  69. let ret = await mysql.insert("admin_role", {desc, role_name, role_code, add_time:mysql.literals.now});
  70. return ret;
  71. }
  72. async addSysUserRole( data ) {
  73. let mysql = this.app.mysql;
  74. let {roleId, userIdList} = data;
  75. if( !roleId ) throw "角色ID为空";
  76. let n = userIdList.length;
  77. for( let i=0; i<n; i++) {
  78. let r = await mysql.query(`select id from admin_user_role where role_id=${roleId} and user_id=${userIdList[i]}`);
  79. if( r.length < 1) {
  80. await mysql.insert("admin_user_role", {role_id: roleId, user_id: userIdList[i]});
  81. }
  82. }
  83. return n;
  84. }
  85. async delete(id)
  86. {
  87. let mysql = this.app.mysql;
  88. let ret = await mysql.query("delete from admin_user where id=?",[id]);
  89. return ret;
  90. }
  91. async deleteRole( id ) {
  92. let mysql = this.app.mysql;
  93. let ret = await mysql.query("delete from admin_role where id=?",[id]);
  94. return ret;
  95. }
  96. async deleteUserRoleBatch(data)
  97. {
  98. //sys/user/deleteUserRoleBatch?roleId=2&userIds=1,3,2,
  99. let {roleId, userIds} = data;
  100. userIds = userIds.split(",");
  101. console.log( data );
  102. let mysql = this.app.mysql;
  103. let n = userIds.length;
  104. for( let i=0; i<n; i++) {
  105. if( userIds[i] ) await mysql.query("delete from admin_user_role where role_id=? and user_id=?",[roleId, userIds[i]]);
  106. }
  107. return n;
  108. }
  109. async queryRolePermission(data) {
  110. // /sys/permission/queryRolePermission?_t=1602508085&roleId=2
  111. let {roleId} = data;
  112. let mysql = this.app.mysql;
  113. let ret = await mysql.query("select * from admin_role_permission where role_id=?",[roleId ]);
  114. // let ctx = this.ctx;
  115. // let where = query.roleName? `where role_name like '%${query.roleName}%'`:'';
  116. // let ret = await ctx.pageSelect(query, 'admin_role_permission', `id,role_name,role_code,\`desc\`,${ctx.SqlFmtTime('add_time')}`, `${where}`)
  117. // return ret;
  118. }
  119. async edit(data) {
  120. let mysql = this.app.mysql;
  121. if( data.add_time ) delete data.add_time;
  122. if( !data.id ) throw "ID为空";
  123. let {realname, avatar, phone, selectedroles} = data;
  124. let conn = await mysql.beginTransaction();
  125. try {
  126. let updateData = {realname, avatar, phone};
  127. let ret = await conn.update("admin_user", updateData, {where:{id: data.id}});
  128. if( selectedroles ) {
  129. console.log("更新角色");
  130. let roles = selectedroles.split(",");
  131. let n = roles.length;
  132. for( let i=0; i<n; i++) {
  133. if( roles[i] != "" && roles[i] != undefined) {
  134. let role = await conn.query("select id from admin_user_role where user_id=? and role_id=?",[data.id, roles[i]]);
  135. if( role.length < 1) {
  136. await conn.insert("admin_user_role", {user_id: data.id, role_id: roles[i]});
  137. }
  138. }
  139. }
  140. }
  141. await conn.commit();
  142. } catch (error) {
  143. await conn.rollback();
  144. throw error;
  145. }
  146. return true;
  147. }
  148. async editRole( data ) {
  149. let mysql = this.app.mysql;
  150. if( data.add_time ) delete data.add_time;
  151. if( !data.id ) throw "ID为空";
  152. let ret = await mysql.update("admin_role", data, {where:{id: data.id}});
  153. return ret;
  154. }
  155. async add( data ) {
  156. let mysql = this.app.mysql;
  157. let {avatar, password, phone, realname, name } = data;
  158. if( !password ) throw "密码不能为空";
  159. let addData = {avatar, password:md5( password ), phone, realname, name, add_time:mysql.literals.now};
  160. let ret = await mysql.insert("admin_user", addData);
  161. if( data.selectedroles ) {
  162. //设置角色
  163. // console.log( ret );
  164. // selectedroles
  165. await mysql.insert("admin_user_role", {role_id: data.selectedroles, user_id: ret.insertId});
  166. }
  167. return ret;
  168. }
  169. async resetpwd( data ) {
  170. let mysql = this.app.mysql;
  171. if( !data.id ) throw "ID不能为空";
  172. if( !data.pwd ) throw "密码不能为空";
  173. if( data.pwd ) data.pwd = md5( data.pwd );
  174. let ret = await mysql.update("users", data, {where:{id: data.id}});
  175. return ret;
  176. }
  177. async frozenBatch( data ) {
  178. let mysql = this.app.mysql;
  179. if( !data.ids ) throw "ID不能为空";
  180. let ret = await mysql.update("admin_user", {status: data.status}, {where:{id: data.ids}});
  181. return ret;
  182. }
  183. async queryTreeList( query ) {
  184. let mysql = this.app.mysql;
  185. let ret = await mysql.query(`select * from admin_permission order by \`sort_no\` `);
  186. let ids = ret.map( e=>e.id );
  187. let nodes = {};
  188. ret.forEach(r=>{
  189. nodes[r.id] = r;
  190. });
  191. //三级树
  192. let treeList = [];
  193. let cacheNodes = {};
  194. function parseNode( node ) {
  195. if( node.parent_id == 0 ) { //根节点
  196. let cnode = cacheNodes[node.id];
  197. if( treeList.indexOf(cnode) < 0) { //还没有加入List
  198. let curNode = {children:[], key: node.id, isLeaf:false, icon:'icon', title:node.name, value:node.id};
  199. treeList.push( curNode );
  200. cacheNodes[node.id] = curNode;
  201. return curNode;
  202. }
  203. return cnode;
  204. } else {
  205. //处理父亲节点
  206. let parentNode = nodes[node.parent_id];
  207. let parent = cacheNodes[parentNode.id];
  208. if( !parent ) {
  209. parent = parseNode(parentNode);
  210. }
  211. //处理自己
  212. let curNode = {children:[], key: node.id, isLeaf:false, icon:'icon', title:node.name, value:node.id};
  213. parent.children.push( curNode );
  214. cacheNodes[node.id] = curNode;
  215. return curNode;
  216. }
  217. }
  218. ret.forEach( node=>{
  219. parseNode( node );
  220. });
  221. function checkNode(node) {
  222. node.isLeaf = node.children.length < 1;
  223. if( node.children.length < 1) {
  224. node.children = null;
  225. return;
  226. }
  227. node.children.forEach( c=>checkNode(c) );
  228. }
  229. treeList.forEach( c=>checkNode(c) );
  230. return {ids, treeList};
  231. }
  232. async saveRolePermission( data ) {
  233. console.log( data );
  234. let {lastpermissionIds, permissionIds, roleId} = data;
  235. if( roleId == undefined ) throw "RoleId为空";
  236. let mysql = this.app.mysql;
  237. const conn = await mysql.beginTransaction();
  238. try {
  239. let lastIds = lastpermissionIds.split(",");
  240. let n = lastIds.length;
  241. for( let i=0; i<n; i++) {
  242. await conn.query(`delete from admin_role_permission where role_id=? and permission_id=?`,[roleId, lastIds[i]]);
  243. }
  244. let ids = permissionIds.split(",");
  245. n = ids.length;
  246. for( let i=0; i<n; i++) {
  247. await conn.query(`insert into admin_role_permission (role_id, permission_id, add_time) values (?,?, now())`,[roleId, ids[i]]);
  248. }
  249. await conn.commit();
  250. } catch (error) {
  251. await conn.rollback();
  252. throw error;
  253. }
  254. }
  255. async queryRolePermission(query){
  256. //sys/permission/queryRolePermission?_t=1602560082&roleId=2
  257. let mysql = this.app.mysql;
  258. let ret = await mysql.query(`select permission_id as id from admin_role_permission where role_id=${query.roleId}`);
  259. let ids = ret.map( e=>e.id );
  260. return ids;
  261. }
  262. async queryUserRole( query ) {
  263. //let userid = query.userid;
  264. let mysql = this.app.mysql;
  265. let ret = await mysql.query(`select role_id as id from admin_user_role where user_id=${query.userid}`);
  266. let ids = ret.map( e=>e.id );
  267. return ids;
  268. }
  269. }
  270. module.exports = AdminUserService;