user.js 11 KB

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