user.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 redirect_uri = ctx.cookies.get('redirect_uri')
  27. let client_id = ctx.cookies.get('client_id')
  28. if (!redirect_uri) {
  29. redirect_uri = ctx.origin + '/api/receiveIDToken'
  30. }
  31. if (!client_id) {
  32. client_id = 'seec-portal'
  33. }
  34. const data = {
  35. iss: 'p.seecoder.cn',
  36. sub: user.phone,
  37. aud: client_id,
  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: redirect_uri })
  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. const options = {
  101. timeout: 3000, // default 3000 ms
  102. formatAction: true, // default true, format the action to Action
  103. formatParams: true, // default true, format the parameter name to first letter upper case
  104. method: 'GET', // set the http method, default is GET
  105. headers: {} // set the http request headers
  106. }
  107. try {
  108. const result = await aliClient.request('SendSms', params)
  109. // console.log("result:", result);
  110. if (result.Code === 'OK') {
  111. ctx.session.maxAge = 5 * 60 * 1000
  112. ctx.session.verification_code = code
  113. ctx.session.verification_phone = phone
  114. // console.log('verification_code:', ctx.session.verification_code);
  115. ctx.body = Response.success({ message: '发送成功' })
  116. } else {
  117. console.log('error:', result.message)
  118. ctx.body = Response.failed('发送失败,请重试')
  119. }
  120. } catch (e) {
  121. console.log(e)
  122. ctx.body = Response.failed('发送失败,请重试')
  123. }
  124. }
  125. static async getInfo (ctx) {
  126. const theUser = await getTokenUser(ctx)
  127. if (!theUser) {
  128. ctx.status = 401
  129. } else {
  130. const id = theUser.id
  131. const user = await userModel.findByUid(id)
  132. if (user) {
  133. ctx.body = Response.success({ phone: user.phone, email: user.email, id: user.id, name: user.name, signature: user.signature })
  134. } else {
  135. ctx.body = Response.failed('用户信息获取失败')
  136. }
  137. }
  138. }
  139. static async saveName (ctx) {
  140. const theUser = await getTokenUser(ctx)
  141. if (!theUser) {
  142. ctx.status = 401
  143. } else {
  144. const id = theUser.id
  145. const newName = ctx.request.body.newName
  146. const result = await userModel.updateName(id, newName)
  147. if (result.code === 0) {
  148. ctx.body = Response.success({})
  149. } else {
  150. ctx.body = Response.failed('此昵称已被占用')
  151. }
  152. }
  153. }
  154. static async saveEmail (ctx) {
  155. const theUser = await getTokenUser(ctx)
  156. if (!theUser) {
  157. ctx.status = 401
  158. } else {
  159. const id = theUser.id
  160. const newEmail = ctx.request.body.newEmail
  161. const myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/
  162. if (!myReg.test(newEmail)) {
  163. ctx.body = Response.failed('邮箱格式有误')
  164. } else {
  165. const result = await userModel.updateEmail(id, newEmail)
  166. if (result.code === 0) {
  167. ctx.body = Response.success({})
  168. } else {
  169. ctx.body = Response.failed('修改失败')
  170. }
  171. }
  172. }
  173. }
  174. static async saveSignature (ctx) {
  175. const theUser = await getTokenUser(ctx)
  176. if (!theUser) {
  177. ctx.status = 401
  178. } else {
  179. const id = theUser.id
  180. const newSignature = ctx.request.body.newSignature
  181. if (newSignature === 0) {
  182. ctx.body = Response.failed('个性签名不得为空')
  183. } else if (newSignature > 20) {
  184. ctx.body = Response.failed('个性签名过长')
  185. } else {
  186. const result = await userModel.updateSignature(id, newSignature)
  187. if (result.code === 0) {
  188. ctx.body = Response.success({})
  189. } else {
  190. ctx.body = Response.failed('修改失败')
  191. }
  192. }
  193. }
  194. }
  195. static async resetPassword (ctx) {
  196. const data = ctx.request.body
  197. if (!ctx.session.verification_phone || !ctx.session.verification_code) {
  198. ctx.body = Response.failed('请重新获取验证码')
  199. } else if (ctx.session.verification_code !== data.identifyCode || ctx.session.verification_phone !== data.phone) {
  200. ctx.body = Response.failed('验证码错误')
  201. } else if (data.password.length < 6 || data.password.length > 20 || data.phone.length !== 11) {
  202. ctx.body = Response.failed('参数非法')
  203. } else {
  204. const hashPassword = bcrypt.hashSync(data.password, 10)
  205. const result = await userModel.resetPassword(data.phone, hashPassword)
  206. ctx.session.verification_phone = undefined
  207. ctx.session.verification_code = undefined
  208. if (result) {
  209. ctx.body = Response.success({})
  210. } else {
  211. ctx.body = Response.failed('此手机号未注册')
  212. }
  213. }
  214. }
  215. static async findIdByName (ctx) {
  216. }
  217. }
  218. module.exports = UserController