user.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. const userModel = require('../model/user')
  2. const jwt = require('jsonwebtoken')
  3. const bcrypt = require('bcrypt')
  4. const secret = require('../config/secret')
  5. const Response = require('../util/response')
  6. const aliClient = require('../util/aliClient')
  7. const getTokenUser = require('../util/tokenProcessor')
  8. class UserController {
  9. /**
  10. * 登录
  11. * @param ctx
  12. * @returns {Promise.<void>}
  13. */
  14. static async login (ctx) {
  15. const data = ctx.request.body
  16. const user = await userModel.findByPhone(data.phone)
  17. if (user) {
  18. const confirmRes = bcrypt.compareSync(data.password, user.password)
  19. if (!confirmRes) {
  20. ctx.body = Response.failed('密码错误,请重试')
  21. } else if (!user.isValid) {
  22. ctx.body = Response.failed('账号封禁中')
  23. } else {
  24. // console.log('ctx',ctx);
  25. // console.log('ctx.cookies.redirect_uri',ctx.cookies.get('redirect_uri'));
  26. let redirectUri = ctx.cookies.get('redirect_uri')
  27. let clientId = ctx.cookies.get('client_id')
  28. if (!redirectUri) {
  29. redirectUri = ctx.origin + '/api/receiveIDToken'
  30. }
  31. if (!clientId) {
  32. clientId = 'seec-portal'
  33. }
  34. const data = {
  35. iss: 'p.seecoder.cn',
  36. sub: user.phone,
  37. aud: clientId,
  38. auth_time: Math.floor(new Date().getTime() / 1000),
  39. iat: Math.floor(new Date().getTime() / 1000),
  40. exp: Math.floor(new Date().getTime() / 1000 + 24 * 60 * 60),
  41. user_info: { phone: user.phone, email: user.email, id: user.id, name: user.name, role: user.role }
  42. }
  43. const token = jwt.sign(data, secret.sign)
  44. // ctx.redirect(redirect_uri + "?id_token=" + token);
  45. ctx.cookies.set('redirect_uri', '', {
  46. maxAge: 0
  47. })
  48. ctx.cookies.set('client_id', '', {
  49. maxAge: 0
  50. })
  51. ctx.body = Response.success({ token: token, name: user.name, path: redirectUri })
  52. }
  53. } else {
  54. ctx.body = Response.failed('此账号不存在')
  55. }
  56. }
  57. /**
  58. * 注册
  59. * @param ctx
  60. * @returns {Promise.<void>}
  61. */
  62. static async register (ctx) {
  63. const myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/
  64. const myReg2 = /^\w+$/
  65. const data = ctx.request.body
  66. if (!ctx.session.verification_phone || !ctx.session.verification_code) {
  67. ctx.body = Response.failed('请重新获取验证码')
  68. } else if (ctx.session.verification_code !== data.identifyCode || ctx.session.verification_phone !== data.phone) {
  69. ctx.body = Response.failed('验证码错误')
  70. } else if (!myReg.test(data.email)) {
  71. ctx.body = Response.failed('邮箱格式有误')
  72. } else if (data.name.length < 1 || data.name.length > 10 || data.password.length < 6 || data.password.length > 20 || data.phone.length !== 11 || !myReg2.test(data.name)) {
  73. ctx.body = Response.failed('参数非法')
  74. } else {
  75. const hashPassword = bcrypt.hashSync(data.password, 10)
  76. const result = await userModel.create(data.name, hashPassword, data.phone, data.email)
  77. ctx.session.verification_phone = undefined
  78. ctx.session.verification_code = undefined
  79. if (result.code === 0) {
  80. ctx.body = Response.success({ name: result.data.name })
  81. } else if (result.code === -2) {
  82. ctx.body = Response.failed('此手机号已注册')
  83. } else if (result.code === -1) {
  84. ctx.body = Response.failed('此用户名已使用')
  85. }
  86. }
  87. }
  88. static async sendMessage (ctx) {
  89. const { phone } = ctx.request.body
  90. let code = ''
  91. for (let i = 0; i < 6; i++) {
  92. code += Math.floor(Math.random() * 10)
  93. }
  94. const params = {
  95. PhoneNumbers: phone,
  96. SignName: 'seeccoder',
  97. TemplateCode: 'SMS_181555598',
  98. TemplateParam: '{"code":"' + code + '"}'
  99. }
  100. // TODO: ??? 这里写个 options 到底是要干啥
  101. // const options = {
  102. // timeout: 3000, // default 3000 ms
  103. // formatAction: true, // default true, format the action to Action
  104. // formatParams: true, // default true, format the parameter name to first letter upper case
  105. // method: 'GET', // set the http method, default is GET
  106. // headers: {} // set the http request headers
  107. // }
  108. try {
  109. const result = await aliClient.request('SendSms', params)
  110. // console.log("result:", result);
  111. if (result.Code === 'OK') {
  112. ctx.session.maxAge = 5 * 60 * 1000
  113. ctx.session.verification_code = code
  114. ctx.session.verification_phone = phone
  115. // console.log('verification_code:', ctx.session.verification_code);
  116. ctx.body = Response.success({ message: '发送成功' })
  117. } else {
  118. console.log('error:', result.message)
  119. ctx.body = Response.failed('发送失败,请重试')
  120. }
  121. } catch (e) {
  122. console.log(e)
  123. ctx.body = Response.failed('发送失败,请重试')
  124. }
  125. }
  126. static async getInfo (ctx) {
  127. const theUser = getTokenUser(ctx)
  128. if (!theUser) {
  129. ctx.status = 401
  130. } else {
  131. const id = theUser.id
  132. const user = await userModel.findByUid(id)
  133. if (user) {
  134. ctx.body = Response.success({ phone: user.phone, email: user.email, id: user.id, name: user.name, signature: user.signature })
  135. } else {
  136. ctx.body = Response.failed('用户信息获取失败')
  137. }
  138. }
  139. }
  140. static async saveName (ctx) {
  141. const theUser = getTokenUser(ctx)
  142. if (!theUser) {
  143. ctx.status = 401
  144. } else {
  145. const id = theUser.id
  146. const newName = ctx.request.body.newName
  147. const result = await userModel.updateName(id, newName)
  148. if (result.code === 0) {
  149. ctx.body = Response.success({})
  150. } else {
  151. ctx.body = Response.failed('此昵称已被占用')
  152. }
  153. }
  154. }
  155. static async saveEmail (ctx) {
  156. const theUser = await getTokenUser(ctx)
  157. if (!theUser) {
  158. ctx.status = 401
  159. } else {
  160. const id = theUser.id
  161. const newEmail = ctx.request.body.newEmail
  162. const myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/
  163. if (!myReg.test(newEmail)) {
  164. ctx.body = Response.failed('邮箱格式有误')
  165. } else {
  166. const result = await userModel.updateEmail(id, newEmail)
  167. if (result.code === 0) {
  168. ctx.body = Response.success({})
  169. } else {
  170. ctx.body = Response.failed('修改失败')
  171. }
  172. }
  173. }
  174. }
  175. static async saveSignature (ctx) {
  176. const theUser = await getTokenUser(ctx)
  177. if (!theUser) {
  178. ctx.status = 401
  179. } else {
  180. const id = theUser.id
  181. const newSignature = ctx.request.body.newSignature
  182. if (newSignature === 0) {
  183. ctx.body = Response.failed('个性签名不得为空')
  184. } else if (newSignature > 20) {
  185. ctx.body = Response.failed('个性签名过长')
  186. } else {
  187. const result = await userModel.updateSignature(id, newSignature)
  188. if (result.code === 0) {
  189. ctx.body = Response.success({})
  190. } else {
  191. ctx.body = Response.failed('修改失败')
  192. }
  193. }
  194. }
  195. }
  196. static async resetPassword (ctx) {
  197. const data = ctx.request.body
  198. if (!ctx.session.verification_phone || !ctx.session.verification_code) {
  199. ctx.body = Response.failed('请重新获取验证码')
  200. } else if (ctx.session.verification_code !== data.identifyCode || ctx.session.verification_phone !== data.phone) {
  201. ctx.body = Response.failed('验证码错误')
  202. } else if (data.password.length < 6 || data.password.length > 20 || data.phone.length !== 11) {
  203. ctx.body = Response.failed('参数非法')
  204. } else {
  205. const hashPassword = bcrypt.hashSync(data.password, 10)
  206. const result = await userModel.resetPassword(data.phone, hashPassword)
  207. ctx.session.verification_phone = undefined
  208. ctx.session.verification_code = undefined
  209. if (result) {
  210. ctx.body = Response.success({})
  211. } else {
  212. ctx.body = Response.failed('此手机号未注册')
  213. }
  214. }
  215. }
  216. /**
  217. * 手机号搜id
  218. */
  219. static async findIdByPhone (ctx) {
  220. const phone = ctx.params.phone
  221. const user = await userModel.findByPhone(phone)
  222. if (user) {
  223. ctx.body = Response.success({ id: user.id })
  224. } else {
  225. ctx.body = Response.failed('此手机号未注册')
  226. }
  227. }
  228. }
  229. module.exports = UserController