11import { inject as Inject , injectable as Injectable } from 'tsyringe' ;
22
3- import { OtpType , TokenType } from '@common/enums' ;
3+ import { OtpType , TemplatePath , TokenType } from '@common/enums' ;
44import { ServiceCore } from '@core/service' ;
5+ import {
6+ INotificationService ,
7+ NotificationInject ,
8+ } from '@modules/notification' ;
59import { IOtpService , OtpInject } from '@modules/otp' ;
610import { IPlatformService , PlatformInject } from '@modules/platform' ;
711import {
@@ -23,6 +27,7 @@ import {
2327 AuthLogout ,
2428 AuthPlatform ,
2529 AuthRefreshToken ,
30+ AuthResetPasswordByEmail ,
2631 AuthToken ,
2732} from '../auth.type' ;
2833import { IAuthService , IAuthTokenService } from '../interface' ;
@@ -33,6 +38,8 @@ export class AuthService extends ServiceCore implements IAuthService {
3338 @Inject ( AuthInject . TOKEN_SERVICE )
3439 private authTokenService : IAuthTokenService ,
3540 @Inject ( LoggerInject . SERVICE ) protected readonly logger : ILoggerService ,
41+ @Inject ( NotificationInject . SERVICE )
42+ private readonly notificationService : INotificationService ,
3643 @Inject ( OtpInject . SERVICE ) private otpService : IOtpService ,
3744 @Inject ( PlatformInject . SERVICE ) private platformService : IPlatformService ,
3845 @Inject ( RefreshTokenInject . SERVICE )
@@ -82,6 +89,28 @@ export class AuthService extends ServiceCore implements IAuthService {
8289 return this . getTokens ( user ) ;
8390 }
8491
92+ async resetPasswordByEmail ( {
93+ email,
94+ token,
95+ password,
96+ } : AuthResetPasswordByEmail ) {
97+ const user = await this . userService . getOne ( { email } ) ;
98+
99+ if ( user ) {
100+ await this . otpService . verifyCode ( {
101+ code : token ,
102+ type : OtpType . RESET_PASSWORD_BY_EMAIL ,
103+ user,
104+ } ) ;
105+ await this . userService . update ( { id : user . id } , { password } ) ;
106+
107+ this . notificationService . send (
108+ { email } ,
109+ { templatePath : TemplatePath . PASSWORD_CHANGED } ,
110+ ) ;
111+ }
112+ }
113+
85114 protected async getTokens ( user : FullUser ) : Promise < AuthToken > {
86115 const [ accessToken , refreshToken ] = await Promise . all ( [
87116 this . authTokenService . getAccessToken ( user . id , user . getPayload ( ) ) ,
@@ -94,45 +123,4 @@ export class AuthService extends ServiceCore implements IAuthService {
94123 refreshToken,
95124 } ;
96125 }
97-
98- // async resetPassword({ password, token }: ResetPasswordRequest) {
99- // const { jti, email } = await Crypto.verifyJwt<JwtPayload>(
100- // token,
101- // JwtConfig.secretToken,
102- // );
103-
104- // await this.userService.update({ id: user.id }, { password: password });
105-
106- // void this.notificationService.send(query, {
107- // template: TemplateType.PASSWORD_CHANGED,
108- // });
109-
110- // try {
111- // await this.userService.update(
112- // { email, resetPasswordCode: jti },
113- // { password: password },
114- // );
115- // void this.notificationService.addToQueue({
116- // email,
117- // template: TemplateType.PASSWORD_CHANGED,
118- // });
119- // } catch {
120- // throw Exception.getError(HttpCode.UNPROCESSABLE_ENTITY, {
121- // errors: { token: i18n()['validate.token.resetPassword'] },
122- // });
123- // }
124- // }
125126}
126-
127- // Создаем таблице OTP (one time password) для хранения временных кодов
128- // для восстановления пароля, подтверждения email, подтверждения телефона, подтверждения смены email и т.д.
129- // В таблице должны быть поля: id, user_id, code, type, expired_at, created_at, updated_at.
130- // Поле type должно быть enum со значениями: reset_password, confirm_email, confirm_phone, change_email.
131- // Поле code должно содержать код, который будет отправляться на email или телефон.
132- // Поле expired_at должно содержать время, когда код перестанет быть действительным.
133- // Отправлять код на email будем как jwt токен, в котором будет зашифрован id пользователя, код и тип кода.
134- // Далее добавить env OTP_RESET_PASSWORD_EXPIRED_AT, OTP_CONFIRM_EMAIL_EXPIRED_AT, OTP_CONFIRM_PHONE_EXPIRED_AT, OTP_CHANGE_EMAIL_EXPIRED_AT и тд
135- // В сервисе Auth добавить методы: forgotPasswordByEmail, resetPasswordByEmail
136- // В методе forgotPasswordByEmail создаем код, сохраняем его в таблицу OTP и отправляем на email.
137- // В методе resetPasswordByEmail проверяем код, если код не найден или просрочен, то выкидываем ошибку.
138- // Если код найден и не просрочен, то обновляем пароль пользователя и удаляем код из таблицы OTP.
0 commit comments