user.js 11 KB

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