forgot-password.component.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { Component, inject } from '@angular/core';
  2. import { FormsModule } from '@angular/forms';
  3. import { Router, RouterModule } from '@angular/router';
  4. import { FaIconComponent } from '@fortawesome/angular-fontawesome';
  5. import {
  6. faEnvelope,
  7. faLock,
  8. faEye,
  9. faEyeSlash,
  10. faCircleCheck,
  11. } from '@fortawesome/free-solid-svg-icons';
  12. import { AuthService } from '../../../core/auth/auth.service';
  13. @Component({
  14. selector: 'app-forgot-password',
  15. standalone: true,
  16. imports: [FormsModule, FaIconComponent, RouterModule],
  17. templateUrl: './forgot-password.component.html',
  18. })
  19. export class ForgotPasswordComponent {
  20. private authService = inject(AuthService);
  21. private router = inject(Router);
  22. protected readonly faEnvelope = faEnvelope;
  23. protected readonly faLock = faLock;
  24. protected readonly faEye = faEye;
  25. protected readonly faEyeSlash = faEyeSlash;
  26. protected readonly faCircleCheck = faCircleCheck;
  27. email = '';
  28. newPassword = '';
  29. confirmPassword = '';
  30. showPassword = false;
  31. showConfirmPassword = false;
  32. submitted = false;
  33. success = false;
  34. errorMessage = '';
  35. protected togglePasswordVisibility(): void {
  36. this.showPassword = !this.showPassword;
  37. }
  38. protected toggleConfirmPasswordVisibility(): void {
  39. this.showConfirmPassword = !this.showConfirmPassword;
  40. }
  41. protected async onSubmit(): Promise<void> {
  42. this.submitted = true;
  43. this.errorMessage = '';
  44. if (!this.email.trim()) {
  45. this.errorMessage = '请输入邮箱地址';
  46. return;
  47. }
  48. if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email.trim())) {
  49. this.errorMessage = '邮箱格式不正确';
  50. return;
  51. }
  52. if (!this.newPassword) {
  53. this.errorMessage = '请输入新密码';
  54. return;
  55. }
  56. if (this.newPassword.length < 6) {
  57. this.errorMessage = '新密码长度不能少于6位';
  58. return;
  59. }
  60. if (this.newPassword !== this.confirmPassword) {
  61. this.errorMessage = '两次输入的密码不一致';
  62. return;
  63. }
  64. const result = await this.authService.resetPasswordByEmail(
  65. this.email.trim(),
  66. this.newPassword,
  67. );
  68. if (result.ok) {
  69. this.success = true;
  70. } else {
  71. this.errorMessage = result.error ?? '该邮箱未注册,请检查后重试';
  72. }
  73. }
  74. protected goToLogin(): void {
  75. this.router.navigate(['/login'], { queryParams: { reset: 'true' } });
  76. }
  77. }