user.router.js 13 KB

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