user.js 10 KB

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