common.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. const path = require("path");
  4. const uuid = require('uuid');
  5. const fs = require("fs");
  6. const awaitWriteStream = require("await-stream-ready").write;
  7. const sendToWormhole = require("stream-wormhole");
  8. const dayjs = require("dayjs");
  9. class CommonController extends Controller {
  10. async upload() {
  11. let {ctx } = this;
  12. // const parts = ctx.multipart({ autoFields: true });
  13. // const files = [];
  14. // let stream;
  15. // while ((stream = await parts()) != null) {
  16. // const filename = stream.filename.toLowerCase();
  17. // // const target = path.join(this.config.baseDir, 'app/public', filename);
  18. // // const writeStream = fs.createWriteStream(target);
  19. // // await pump(stream, writeStream);
  20. // console.log("xxx, ok11", filename);
  21. // files.push(filename);
  22. // }
  23. const stream = await this.ctx.getFileStream();
  24. // 基础的目录
  25. const uplaodBasePath = 'app/public/uploads';
  26. // 生成文件名
  27. const filename = `${Date.now()}${Number.parseInt( Math.random() * 1000)}${path.extname(stream.filename).toLocaleLowerCase()}`;
  28. // 生成文件夹
  29. const dirname = dayjs(Date.now()).format('YYYY-MM-DD');
  30. function mkdirsSync(dirname) {
  31. if (fs.existsSync(dirname)) {
  32. return true;
  33. } else {
  34. if (mkdirsSync(path.dirname(dirname))) {
  35. fs.mkdirSync(dirname);
  36. return true;
  37. }
  38. }
  39. }
  40. mkdirsSync(path.join(uplaodBasePath, dirname));
  41. // 生成写入路径
  42. const target = path.join(uplaodBasePath, dirname, filename);
  43. // 写入流
  44. const writeStream = fs.createWriteStream(target);
  45. try {
  46. //异步把文件流 写入
  47. await awaitWriteStream(stream.pipe(writeStream));
  48. } catch (err) {
  49. //如果出现错误,关闭管道
  50. await sendToWormhole(stream);
  51. throw err;
  52. }
  53. let url = `uploads/${dirname}/${filename}`;
  54. ctx.adminOK(true, url);
  55. }
  56. async sendSms() {
  57. let { ctx } = this;
  58. let {phone, use} = ctx.request.body;
  59. if( !use || !phone ) {
  60. ctx.resultFail("error");
  61. return;
  62. }
  63. console.log("sendSms", use);
  64. let code = await ctx.service.sms.send(phone);
  65. await ctx.service.cache.setString(`sms#${phone}#${use}`, code, 180);//3分钟后失效
  66. ctx.resultOK("发送成功");
  67. }
  68. async bindThirdparty() {
  69. let { ctx , app} = this;
  70. let {mobile, wechatCode, alipayCode, code} = ctx.request.body;
  71. if( !alipayCode && !wechatCode ) {
  72. ctx.resultFail("授权码不能为空");
  73. return;
  74. }
  75. if( !mobile ) {
  76. ctx.resultFail("手机号码不能为空");
  77. return;
  78. }
  79. if( !code ) {
  80. ctx.resultFail("验证码不能为空");
  81. return;
  82. }
  83. let cacheKey = `sms#${mobile}#bind`;
  84. let cacheCode = await ctx.service.cache.getString(cacheKey);//3分钟后失效
  85. if( cacheCode != code) {
  86. ctx.resultFail("验证码错误");
  87. return;
  88. }
  89. await ctx.service.cache.removeCache(cacheKey);
  90. let thirdUser = {userId:"", nickName: "", avatar:""};
  91. if( alipayCode ) {
  92. thirdUser = await ctx.service.alipay.getUserInfo( alipayCode );
  93. }
  94. //更新用户
  95. let user = await app.mysql.get("app_user", {tel: mobile}, {columns:["id","name","avatar"]});
  96. if( user && user.id ) {
  97. let v = {};
  98. if( wechatCode ) v.wechat = thirdUser.userId;
  99. else if( alipayCode ) v.alipay = thirdUser.userId;
  100. if( !user.name ) v.name = thirdUser.nickName;
  101. if( !user.avatar ) v.avatar = thirdUser.avatar;
  102. await app.mysql.update("app_user", v, {where:{id: user.id} });
  103. let token = await ctx.jwtSign({name:user.name, tel:mobile, id:user.id}, app.config.loginUser.secret, { expiresIn: app.config.loginUser.expiresIn });
  104. ctx.resultOK({id: user.id, username: user.name, avatar:user.avatar,tel:mobile, token}, "绑定成功");
  105. return;
  106. }
  107. //创建用户
  108. let res = await app.mysql.query(`insert into app_user (name, avatar, tel,${alipayCode?"alipay":"wechat"}, add_time, last_login, last_login_ip) values (?,?,?,?,now(),now(), ?)`, [thirdUser.nickName, thirdUser.avatar, mobile, thirdUser.userId, ctx.ip]);
  109. let id = res.insertId;
  110. if( id ) {
  111. let token = await ctx.jwtSign({name:thirdUser.nickName, id, tel:mobile}, app.config.loginUser.secret, { expiresIn: 24 * 60 * 60 });
  112. ctx.resultOK({id: id, tel:mobile, username: thirdUser.nickName, avatar: thirdUser.avatar, token}, "绑定成功");
  113. return;
  114. }
  115. ctx.resultFail("绑定失败");
  116. }
  117. }
  118. module.exports = CommonController;