user.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. let 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. static canManageUser(ctx){
  58. let curUser = getTokenUser(ctx);
  59. if (curUser === null){// 没有身份,不可以
  60. return false;
  61. }
  62. // 管理员或者老师可以管理
  63. return curUser.role === "ADMIN" || curUser.role === "TEACHER";
  64. }
  65. /*
  66. 批量注册用户
  67. 接收一个数组,返回一个map
  68. */
  69. static async batchRegister(ctx){
  70. if (!UserController.canManageUser(ctx)){
  71. return "Method Not Allowed."
  72. }
  73. const usersToRegister = ctx.request.body;
  74. for (const user of usersToRegister) {
  75. const {name, password, phone, email} = user
  76. try {
  77. const result = await UserController.createUser(name, password, phone, email);
  78. user.result = "创建成功"
  79. }catch (e){
  80. user.result = e.message
  81. }
  82. }
  83. console.log(usersToRegister)
  84. ctx.body = Response.success(usersToRegister);
  85. }
  86. /**
  87. * 注册用户
  88. * @param ctx
  89. * @returns {Promise.<void>}
  90. */
  91. static async register(ctx) {
  92. const { name, password, phone, email, identifyCode } = ctx.request.body;
  93. let curUser = await getTokenUser(ctx);
  94. try {
  95. if (curUser === null || curUser.role === "STUDENT"){ // 普通用户注册流程
  96. UserController.validateIdentifyCode(ctx,identifyCode,phone) //需要验证手机验证码
  97. ctx.session.verification_phone = undefined;
  98. ctx.session.verification_code = undefined;
  99. }
  100. const result = await UserController.createUser(name, password, phone, email)
  101. ctx.body = Response.success({name:result.data.name})
  102. }catch (e) {
  103. ctx.body = Response.failed(e.message)
  104. }
  105. }
  106. //创建用户
  107. static async createUser(name, password, phone, email){
  108. UserController.validateRegistrationData(name, password, phone, email);
  109. //注册逻辑
  110. const hashPassword = bcrypt.hashSync(password, 10);
  111. const result = await userModel.create(name, hashPassword, phone, email);
  112. if (result.code === 0) {
  113. return result
  114. } else if (result.code === -2) {
  115. throw new Error('此手机号已注册');
  116. } else if (result.code === -1) {
  117. throw new Error('此用户名已使用');
  118. }else {
  119. throw new Error("未知错误")
  120. }
  121. }
  122. static validateIdentifyCode(ctx,idetifyCode,phone){
  123. if (!ctx.session.verification_phone || !ctx.session.verification_code) {
  124. throw new Error('请重新获取验证码')
  125. }
  126. if (ctx.session.verification_code !== identifyCode || ctx.session.verification_phone !== phone) {
  127. throw new Error('验证码错误');
  128. }
  129. }
  130. // 验证注册数据是否合法
  131. static validateRegistrationData(name, password, phone, email) {
  132. const emailRegex = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
  133. const usernameRegex = /^\w+$/; //由字母、数字、下划线组成且不包含其他字符的字符串
  134. if (!emailRegex.test(email)) {
  135. throw new Error('邮箱格式有误');
  136. }
  137. if (name.length < 1 || name.length > 10) {
  138. throw new Error('用户名长度应在1到10之间');
  139. }
  140. if (password.length < 6 || password.length > 20) {
  141. throw new Error('密码长度应在6到20之间');
  142. }
  143. if (phone.length !== 11) {
  144. throw new Error('手机号码长度应为11位');
  145. }
  146. if (!usernameRegex.test(name)) {
  147. throw new Error('用户名只能包含字母、数字和下划线');
  148. }
  149. }
  150. static async sendMessage(ctx){
  151. let {phone} = ctx.request.body;
  152. let code = "";
  153. for(let i = 0; i < 6; i++){
  154. code+=Math.floor(Math.random()*10)
  155. }
  156. let params = {
  157. PhoneNumbers: phone,
  158. SignName: 'SEECODER',
  159. TemplateCode: 'SMS_253920073',
  160. TemplateParam: '{"code":"' + code + '"}'
  161. };
  162. let options = {
  163. timeout: 3000, // default 3000 ms
  164. formatAction: true, // default true, format the action to Action
  165. formatParams: true, // default true, format the parameter name to first letter upper case
  166. method: 'GET', // set the http method, default is GET
  167. headers: {}, // set the http request headers
  168. };
  169. try{
  170. const result = await aliClient.request('SendSms', params);
  171. // console.log("result:", result);
  172. if(result.Code === "OK"){
  173. ctx.session.maxAge = 5 * 60 * 1000;
  174. ctx.session.verification_code = code;
  175. ctx.session.verification_phone = phone;
  176. console.log('verification_code:', ctx.session.verification_code);
  177. ctx.body = Response.success({message: '发送成功'});
  178. }else{
  179. console.log("error:", result.message);
  180. ctx.body = Response.failed("发送失败,请重试");
  181. }
  182. }catch (e) {
  183. console.log(e);
  184. ctx.body = Response.failed("发送失败,请重试");
  185. }
  186. }
  187. static async getInfo(ctx) {
  188. let theUser = await getTokenUser(ctx);
  189. if(!theUser){
  190. ctx.status = 401;
  191. }else{
  192. let id = theUser.id;
  193. const user = await userModel.findByUid(id);
  194. if (user) {
  195. ctx.body = Response.success({phone: user.phone, email: user.email, id: user.id, name: user.name, signature: user.signature});
  196. } else {
  197. ctx.body = Response.failed('用户信息获取失败');
  198. }
  199. }
  200. }
  201. static async saveName(ctx){
  202. let theUser = await getTokenUser(ctx);
  203. if(!theUser){
  204. ctx.status = 401;
  205. }else{
  206. let id = theUser.id;
  207. let newName = ctx.request.body.newName;
  208. let result = await userModel.updateName(id, newName);
  209. if(result.code === 0){
  210. ctx.body = Response.success({});
  211. }else{
  212. ctx.body = Response.failed('此昵称已被占用');
  213. }
  214. }
  215. }
  216. static async saveEmail(ctx){
  217. let theUser = await getTokenUser(ctx);
  218. if(!theUser){
  219. ctx.status = 401;
  220. }else{
  221. let id = theUser.id;
  222. let newEmail = ctx.request.body.newEmail;
  223. const myReg=/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
  224. if(!myReg.test(newEmail)){
  225. ctx.body = Response.failed('邮箱格式有误');
  226. }else{
  227. let result = await userModel.updateEmail(id, newEmail);
  228. if(result.code === 0){
  229. ctx.body = Response.success({});
  230. }else{
  231. ctx.body = Response.failed('修改失败');
  232. }
  233. }
  234. }
  235. }
  236. static async saveSignature(ctx){
  237. let theUser = await getTokenUser(ctx);
  238. if(!theUser){
  239. ctx.status = 401;
  240. }else{
  241. let id = theUser.id;
  242. let newSignature = ctx.request.body.newSignature;
  243. if(newSignature === 0){
  244. ctx.body = Response.failed('个性签名不得为空');
  245. }else if(newSignature > 20){
  246. ctx.body = Response.failed('个性签名过长');
  247. }else {
  248. let result = await userModel.updateSignature(id, newSignature);
  249. if(result.code === 0){
  250. ctx.body = Response.success({});
  251. }else{
  252. ctx.body = Response.failed('修改失败');
  253. }
  254. }
  255. }
  256. }
  257. static async resetPassword(ctx) {
  258. const data = ctx.request.body;
  259. if(!ctx.session.verification_phone || !ctx.session.verification_code){
  260. ctx.body = Response.failed('请重新获取验证码');
  261. }else if(ctx.session.verification_code !== data.identifyCode || ctx.session.verification_phone !== data.phone){
  262. ctx.body = Response.failed('验证码错误');
  263. }else if( data.password.length<6 || data.password.length>20 || data.phone.length !== 11){
  264. ctx.body = Response.failed('参数非法');
  265. }else{
  266. const hashPassword = bcrypt.hashSync(data.password, 10);
  267. const result = await userModel.resetPassword(data.phone, hashPassword);
  268. ctx.session.verification_phone = undefined;
  269. ctx.session.verification_code = undefined;
  270. if (result) {
  271. ctx.body = Response.success({});
  272. } else {
  273. ctx.body = Response.failed('此手机号未注册');
  274. }
  275. }
  276. }
  277. }
  278. module.exports = UserController;