user.router.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. const Router = require('@koa/router');
  2. const router = new Router({ prefix: '/user' });
  3. const util = require('../utils/util');
  4. const userService = require('../service/user.service');
  5. const projectService = require('../service/projects.service');
  6. const projectUserService = require('../service/project.user.service');
  7. const pageRoleService = require('../service/pagesRole.service');
  8. const pageService = require('../service/pages.service');
  9. const menuService = require('../service/menu.service');
  10. const publishService = require('../service/publish.service');
  11. const roleService = require('../service/roles.service');
  12. const imgcloudService = require('../service/imgcloud.service');
  13. const md5 = require('md5.js');
  14. const nodemailer = require('nodemailer');
  15. const config = require('../config');
  16. const request = require('../utils/request');
  17. const { Keyv } = require('keyv');
  18. const keyv = new Keyv();
  19. /**
  20. * 编辑器端用户登录
  21. */
  22. router.post('/login', async (ctx) => {
  23. const { userName, userPwd, openId } = ctx.request.body;
  24. if (!userName || !userPwd) {
  25. util.fail(ctx, '用户名或密码不能为空');
  26. return;
  27. }
  28. const pwd = new md5().update(userPwd).digest('hex');
  29. const res = await userService.findUser(userName, pwd, openId || userName);
  30. if (!res) {
  31. util.fail(ctx, '用户名或密码错误');
  32. return;
  33. }
  34. if (!res.openId && openId) {
  35. const cacheUser = await keyv.get(openId);
  36. if (cacheUser) {
  37. await userService.bindOpenId({ ...cacheUser, id: res.id });
  38. }
  39. }
  40. const token = util.createToken({ userName, userId: res.id, nickName: res.nickName });
  41. userService.updateUserInfo(res.id);
  42. util.success(ctx, {
  43. userId: res.id,
  44. userName,
  45. token,
  46. });
  47. });
  48. /**
  49. * admin端登录
  50. */
  51. router.post('/admin/login', async (ctx) => {
  52. const { userName, userPwd, openId } = ctx.request.body;
  53. if (!userName || !userPwd) {
  54. util.fail(ctx, '用户名或密码不能为空');
  55. return;
  56. }
  57. const pwd = new md5().update(userPwd).digest('hex');
  58. const res = await userService.findSubUser(userName, pwd, openId || userName);
  59. if (!res) {
  60. util.fail(ctx, '用户名或密码错误');
  61. return;
  62. }
  63. if (!res.openId && openId) {
  64. const cacheUser = await keyv.get(openId);
  65. if (cacheUser) {
  66. await userService.bindOpenId({ ...cacheUser, id: res.id });
  67. }
  68. }
  69. const token = util.createToken({ userName, userId: res.id, nickName: res.nickName });
  70. userService.updateUserInfo(res.id);
  71. util.success(ctx, {
  72. userId: res.id,
  73. userName,
  74. token,
  75. });
  76. });
  77. /**
  78. * 微信授权登录
  79. */
  80. router.post('/wechat', async (ctx) => {
  81. const { code } = ctx.request.body;
  82. if (!code) {
  83. util.fail(ctx, 'code不能为空');
  84. return;
  85. }
  86. const response = await request.get(
  87. `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.WECHAT_APP_ID}&secret=${config.WECHAT_APP_SECRET}&code=${code}&grant_type=authorization_code`,
  88. {},
  89. );
  90. const { access_token, openid, unionid, errcode } = JSON.parse(response.data);
  91. if (errcode) {
  92. util.success(ctx, '');
  93. return;
  94. }
  95. const wxUser = await userService.findUser(openid, openid, openid);
  96. if (wxUser) {
  97. userService.updateUserInfo(wxUser.id);
  98. const token = util.createToken({ userName: wxUser.userName, userId: wxUser.id, nickName: wxUser.nickName });
  99. util.success(ctx, {
  100. userId: wxUser.id,
  101. userName: wxUser.userName,
  102. token,
  103. });
  104. return;
  105. }
  106. const res1 = await request.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`);
  107. const { nickname, headimgurl } = JSON.parse(res1.data);
  108. await keyv.set(
  109. openid,
  110. {
  111. openid,
  112. unionid,
  113. nickname,
  114. headimgurl,
  115. },
  116. 3 * 60 * 1000,
  117. );
  118. util.success(ctx, {
  119. openId: openid,
  120. });
  121. });
  122. /**
  123. * 获取用户信息
  124. */
  125. router.get('/info', async (ctx) => {
  126. const { userId } = util.decodeToken(ctx);
  127. const res = await userService.profile(userId);
  128. util.success(ctx, res);
  129. });
  130. /**
  131. * 获取个人信息
  132. */
  133. router.get('/profile', async (ctx) => {
  134. const { userId } = util.decodeToken(ctx);
  135. const res = await userService.profile(userId);
  136. util.success(ctx, res);
  137. });
  138. /**
  139. * 用户搜索
  140. */
  141. router.post('/search', async (ctx) => {
  142. const { keyword } = ctx.request.body;
  143. if (!keyword) {
  144. util.fail(ctx, '关键字不能为空');
  145. return;
  146. }
  147. const res = await userService.search(keyword);
  148. if (!res) {
  149. util.fail(ctx, '当前用户名不存在');
  150. return;
  151. }
  152. util.success(ctx, res);
  153. });
  154. /**
  155. * 用户信息更新
  156. */
  157. router.post('/update/profile', async (ctx) => {
  158. const { nickName, avatar } = ctx.request.body;
  159. if (!nickName && !avatar) {
  160. util.fail(ctx, '参数异常,请重新提交');
  161. return;
  162. }
  163. const { userId } = util.decodeToken(ctx);
  164. await userService.updateUserInfo(userId, nickName, avatar);
  165. util.success(ctx, '更新成功');
  166. });
  167. /**
  168. * 用户注册 - 发送验证码
  169. */
  170. router.post('/sendEmail', async (ctx) => {
  171. try {
  172. const { email } = ctx.request.body;
  173. if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
  174. util.fail(ctx, '邮箱不能为空或格式错误');
  175. return;
  176. }
  177. const val = await keyv.get(email);
  178. if (val) {
  179. util.fail(ctx, '验证码已发送,请查收');
  180. return;
  181. }
  182. let transporter = nodemailer.createTransport({
  183. host: config.EMAIL_HOST,
  184. port: config.EMAIL_PORT,
  185. auth: {
  186. user: config.EMAIL_USER, // 你的Gmail地址
  187. pass: config.EMAIL_PASSWORD, // 你的Gmail密码或应用专用密码
  188. },
  189. });
  190. const random = Math.random().toString().slice(2, 7).replace(/^(0)+/, '1');
  191. let mailOptions = {
  192. from: `"Marsview" <${config.EMAIL_USER}>`, // 发送者地址
  193. to: email, // 接收者列表
  194. subject: 'Marsview账号注册', // 主题行
  195. text: '验证码发送', // 纯文字正文
  196. html: `当前验证码为:<b>${random}</b>,3分钟内有效。<br/><br/>感谢您体验 Marsview 搭建平台,线上平台不保证数据的稳定性,建议有条件用户,切换到 Marsview 私有化部署服务,您在使用过程中遇到任何问题均联系我。<br/><br/>邮 箱:marsview@163.com<br/>微 信:17611021717`, // HTML正文
  197. };
  198. await transporter.sendMail(mailOptions);
  199. await keyv.set(email, random, 3 * 60 * 1000);
  200. util.success(ctx, '发送成功');
  201. } catch (error) {
  202. util.fail(ctx, error.message);
  203. }
  204. });
  205. /**
  206. * 用户注册
  207. */
  208. router.post('/regist', async (ctx) => {
  209. const { userName, code, userPwd } = ctx.request.body;
  210. if (!userName || !userPwd) {
  211. util.fail(ctx, '用户名或密码不能为空');
  212. return;
  213. }
  214. if (!code) {
  215. util.fail(ctx, '邮箱验证码不能为空');
  216. return;
  217. }
  218. const val = await keyv.get(userName);
  219. if (!val) {
  220. util.fail(ctx, '验证码已过期');
  221. return;
  222. }
  223. if (val != code) {
  224. util.fail(ctx, '验证码错误');
  225. return;
  226. }
  227. const user = await userService.search(userName);
  228. if (user) {
  229. util.fail(ctx, '当前用户已存在');
  230. return;
  231. }
  232. const nickName = userName.split('@')[0];
  233. const pwd = new md5().update(userPwd).digest('hex');
  234. const res = await userService.create(nickName, userName, pwd);
  235. if (res.affectedRows == 1) {
  236. // 生成用户token
  237. const token = util.createToken({ userName, userId: res.insertId });
  238. util.success(ctx, {
  239. userId: res.id,
  240. userName,
  241. token,
  242. });
  243. } else {
  244. util.fail(ctx, '注册失败,请重试');
  245. }
  246. });
  247. /**
  248. * 忘记密码 - 生成链接
  249. */
  250. router.post('/password/forget', async (ctx) => {
  251. const { userEmail } = ctx.request.body;
  252. if (!userEmail) {
  253. util.fail(ctx, '邮箱不能为空');
  254. return;
  255. }
  256. const user = await userService.search(userEmail);
  257. if (!user) {
  258. util.fail(ctx, '当前用户不存在');
  259. return;
  260. }
  261. // 生成验证码,保存在redis中,用来验证链接有效期
  262. const random = Math.random().toString().slice(2, 7);
  263. await keyv.set(userEmail, random, 5 * 60 * 1000);
  264. // 生成加密后token
  265. const token = util.createToken({ userEmail });
  266. // 发送邮件
  267. let transporter = nodemailer.createTransport({
  268. host: config.EMAIL_HOST,
  269. port: config.EMAIL_PORT,
  270. auth: {
  271. user: config.EMAIL_USER, // 你的Gmail地址
  272. pass: config.EMAIL_PASSWORD, // 你的Gmail密码或应用专用密码
  273. },
  274. });
  275. let mailOptions = {
  276. from: `"Marsview" <${config.EMAIL_USER}>`, // 发送者地址
  277. to: userEmail, // 接收者列表
  278. subject: 'Marsview密码找回', // 主题行
  279. text: '验证码发送', // 纯文字正文
  280. html: `Hello,${userEmail}! <br/> 我们收到了你重置密码的申请,请点击下方按链接行重置,<a href="https://www.marsview.com.cn/password-reset?resetToken=${token}">重置密码</a> <br/> 链接 3分钟内有效,请尽快操作,如不是你发起的请求,请忽略。`, // HTML正文
  281. };
  282. await transporter.sendMail(mailOptions);
  283. util.success(ctx, '发送成功');
  284. });
  285. /**
  286. * 忘记密码 - 获取账号
  287. */
  288. router.post('/password/getUserByToken', async (ctx) => {
  289. const { resetToken } = ctx.request.query;
  290. const { userEmail } = util.decodeResetToken(resetToken);
  291. const val = await keyv.get(userEmail);
  292. if (!val) {
  293. util.fail(ctx, '链接已失效,请重新操作');
  294. return;
  295. }
  296. util.success(ctx, userEmail);
  297. });
  298. /**
  299. * 忘记密码 - 重置密码
  300. */
  301. router.post('/password/reset', async (ctx) => {
  302. const { resetToken, userPwd } = ctx.request.body;
  303. if (!resetToken) {
  304. util.fail(ctx, '重置Token不能为空');
  305. return;
  306. }
  307. if (!userPwd) {
  308. util.fail(ctx, '重置密码不能为空');
  309. return;
  310. }
  311. const { userEmail } = util.decodeResetToken(resetToken);
  312. if (!userEmail) {
  313. util.fail(ctx, 'Token 识别错误,请重新操作');
  314. return;
  315. }
  316. const val = await keyv.get(userEmail);
  317. if (!val) {
  318. util.fail(ctx, '链接已失效,请重新操作');
  319. return;
  320. }
  321. const pwd = new md5().update(userPwd).digest('hex');
  322. await userService.resetPwd(userEmail, pwd);
  323. await keyv.delete(userEmail);
  324. util.success(ctx, '更新成功');
  325. });
  326. /**
  327. * 密码修改
  328. */
  329. router.post('/password/update', async (ctx) => {
  330. const { oldPwd, userPwd, confirmPwd } = ctx.request.body;
  331. if (!oldPwd || !userPwd || !confirmPwd) {
  332. util.fail(ctx, '密码不能为空');
  333. return;
  334. }
  335. if (userPwd !== confirmPwd) {
  336. util.fail(ctx, '两次密码不一致');
  337. return;
  338. }
  339. const { userName } = util.decodeToken(ctx);
  340. try {
  341. const res = await userService.verifyOldPwd(userName, oldPwd);
  342. if (res) {
  343. const pwd = new md5().update(userPwd).digest('hex');
  344. await userService.resetPwd(userName, pwd);
  345. util.success(ctx, '密码更改成功');
  346. } else {
  347. util.fail(ctx, '原密码输入错误');
  348. }
  349. } catch (error) {
  350. util.fail(ctx, error.message);
  351. }
  352. });
  353. /**
  354. * 用户注销
  355. */
  356. router.post('/logout', async (ctx) => {
  357. const { userId, userName } = util.decodeToken(ctx);
  358. if (userId == 50) {
  359. util.fail(ctx, '管理员账号不支持注销');
  360. return;
  361. }
  362. // 删除用户所有项目
  363. await projectService.deleteAllProject(userId, userName);
  364. // 删除用户所有关联
  365. await projectUserService.deleteAllProjectUser(userId);
  366. // 删除用户所有页面角色
  367. await pageRoleService.deleteAllPageRole(userId);
  368. // 删除用户所有页面
  369. await pageService.deleteAllPage(userId, userName);
  370. // 删除用户所有菜单
  371. await menuService.deleteAllMenu(userId);
  372. // 删除用户所有发布
  373. await publishService.deleteAllPublish(userId);
  374. // 删除用户所有角色
  375. await roleService.deleteAllRole(userId);
  376. // 删除用户
  377. await userService.deleteUser(userId, userName);
  378. // 删除用户图片
  379. await imgcloudService.deleteAllImg(userId);
  380. util.success(ctx, '注销成功');
  381. });
  382. /**
  383. * 查询子用户列表
  384. */
  385. router.get('/subUser/list', async (ctx) => {
  386. const { userId } = util.decodeToken(ctx);
  387. const { pageNum, pageSize, keyword } = ctx.request.query;
  388. const { total } = await userService.getSubUsersCount(userId, keyword);
  389. if (total == 0) {
  390. return util.success(ctx, {
  391. list: [],
  392. total: 0,
  393. pageSize: +pageSize || 12,
  394. pageNum: +pageNum || 1,
  395. });
  396. }
  397. const list = await userService.getSubUsersList(userId, pageNum || 1, pageSize || 12, keyword);
  398. util.success(ctx, {
  399. list,
  400. total,
  401. pageSize: +pageSize,
  402. pageNum: +pageNum,
  403. });
  404. });
  405. // 创建子用户
  406. router.post('/subUser/create', async (ctx) => {
  407. const { userName, userPwd } = ctx.request.body;
  408. if (!userName || !userPwd) {
  409. util.fail(ctx, '用户名或密码不能为空');
  410. return;
  411. }
  412. const { userId } = util.decodeToken(ctx);
  413. const user = await userService.search(userName);
  414. if (user) {
  415. util.fail(ctx, '当前用户已存在');
  416. return;
  417. }
  418. const nickName = userName.split('@')[0];
  419. const pwd = new md5().update(userPwd).digest('hex');
  420. const res = await userService.create(nickName, userName, pwd, userId);
  421. if (res.affectedRows == 1) {
  422. util.success(ctx, '注册成功');
  423. } else {
  424. util.fail(ctx, '注册失败,请重试');
  425. }
  426. });
  427. // 删除子用户
  428. router.post('/subUser/delete', async (ctx) => {
  429. const { id } = ctx.request.body;
  430. if (!id) {
  431. util.fail(ctx, '用户ID不能为空');
  432. return;
  433. }
  434. const { userId } = util.decodeToken(ctx);
  435. const res = await userService.deleteSubUser(id, userId);
  436. if (res.affectedRows == 1) {
  437. util.success(ctx, '删除成功');
  438. } else {
  439. util.fail(ctx, '删除失败,请重试');
  440. }
  441. });
  442. /**
  443. * 平台管理员创建用户账号
  444. */
  445. router.post('/create/account', async (ctx) => {
  446. const { userName, userPwd } = ctx.request.body;
  447. if (!userName || !userPwd) {
  448. util.fail(ctx, '用户名或密码不能为空');
  449. return;
  450. }
  451. const user = await userService.search(userName);
  452. if (user) {
  453. util.fail(ctx, '当前用户已存在');
  454. return;
  455. }
  456. const nickName = userName.split('@')[0];
  457. const pwd = new md5().update(userPwd).digest('hex');
  458. const res = await userService.create(nickName, userName, pwd);
  459. if (res.affectedRows == 1) {
  460. const token = util.createToken({ userName, userId: res.insertId });
  461. util.success(ctx, {
  462. userId: res.id,
  463. userName,
  464. token,
  465. });
  466. } else {
  467. util.fail(ctx, '创建失败,请稍后重试');
  468. }
  469. });
  470. module.exports = router;