import { Component } from '@angular/core' ; import { ActivatedRoute , Router } from '@angular/router' ; import { Subscription } from 'rxjs' ; import { Client } from '../../../services/api' ; import { Session } from '../../../services/session' ; import { RegexService } from '../../../common/services/regex.service' ; import { FormToastService } from '../../../common/services/form-toast.service' ; @ Component ( { moduleId : module . id , selector : 'm-forgot-password' , templateUrl : 'forgot-password.component.html' , } ) export class ForgotPasswordComponent { inProgress : boolean = false ; step : number = 1 ; username : string = '' ; code : string = '' ; paramsSubscription : Subscription ; private errorTexts : { [ key ] : string ; } = { 'email-detected' : 'Enter your username, not your email.' , default : 'There was a problem trying to reset your password. Please try again.' , } ; constructor ( public client , public router , public route , public session , public regex , public toaster ) { } ngOnInit ( ) { this . paramsSubscription = this . route . params . subscribe ( params => { if ( params [ 'code' ] ) { this . setCode ( params [ 'code' ] ) ; } if ( params [ 'username' ] ) { this . username = params [ 'username' ] ; } } ) ; } ngOnDestroy ( ) { this . paramsSubscription . unsubscribe ( ) ; } param { { value : string } } username async request ( username ) { this . inProgress = true ; const regex = this . regex . getRegex ( 'mail' ) ; regex . lastIndex = 0 ; if ( regex . test ( username . value ) ) { this . inProgress = false ; this . toaster . error ( this . errorTexts [ 'email-detected' ] ) ; return ; } let usernameValue = username . value ; if ( usernameValue . charAt ( 0 ) === '@' ) { usernameValue = usernameValue . substr ( 1 ) ; } try { await this . client . post ( 'api/v1/forgotpassword/request' , { username : usernameValue , } ) ; username . value = '' ; this . inProgress = false ; this . step = 2 ; } catch ( e ) { this . inProgress = false ; if ( e . status === 'failed' ) { this . toaster . error ( this . errorTexts [ 'default' ] ) ; } if ( e . status === 'error' ) { this . toaster . error ( e . message ) ; } } } setCode ( code ) { this . step = 3 ; this . code = code ; } reset ( password ) { if ( ! this . inProgress ) { this . inProgress = true ; this . client . post ( 'api/v1/forgotpassword/reset' , { password : password . value , code : this . code , username : this . username , } ) . then ( ( response ) => { this . inProgress = false ; this . session . login ( response . user ) ; this . router . navigate ( [ '/newsfeed' ] ) ; } ) . catch ( e => { this . inProgress = false ; this . toaster . error ( e . message ) ; } ) ; } } }