1 import { Component, OnInit } from '@angular/core'
2 import { FormGroup } from '@angular/forms'
3 import { Router } from '@angular/router'
4 import { AuthService, Notifier, User } from '@app/core'
5 import { USER_EXISTING_PASSWORD_VALIDATOR, USER_OTP_TOKEN_VALIDATOR } from '@app/shared/form-validators/user-validators'
6 import { FormReactiveService } from '@app/shared/shared-forms'
7 import { TwoFactorService } from '@app/shared/shared-users'
10 selector: 'my-account-two-factor',
11 templateUrl: './my-account-two-factor.component.html',
12 styleUrls: [ './my-account-two-factor.component.scss' ]
14 export class MyAccountTwoFactorComponent implements OnInit {
15 twoFactorAlreadyEnabled: boolean
17 step: 'request' | 'confirm' | 'confirmed' = 'request'
19 twoFactorSecret: string
24 formPassword: FormGroup
25 formErrorsPassword: any
31 private requestToken: string
34 private notifier: Notifier,
35 private twoFactorService: TwoFactorService,
36 private formReactiveService: FormReactiveService,
37 private auth: AuthService,
38 private router: Router
43 this.buildPasswordForm()
46 this.auth.userInformationLoaded.subscribe(() => {
47 this.user = this.auth.getUser()
49 this.twoFactorAlreadyEnabled = this.user.twoFactorEnabled
54 this.twoFactorService.requestTwoFactor({
56 currentPassword: this.formPassword.value['current-password']
58 next: ({ otpRequest }) => {
59 this.requestToken = otpRequest.requestToken
60 this.twoFactorURI = otpRequest.uri
61 this.twoFactorSecret = otpRequest.secret.replace(/(.{4})/g, '$1 ').trim()
66 error: err => this.notifier.error(err.message)
71 this.twoFactorService.confirmTwoFactorRequest({
73 requestToken: this.requestToken,
74 otpToken: this.formOTP.value['otp-token']
77 this.notifier.success($localize`Two factor authentication has been enabled.`)
79 this.auth.refreshUserInformation()
81 this.router.navigateByUrl('/my-account/settings')
84 error: err => this.notifier.error(err.message)
88 private buildPasswordForm () {
89 const { form, formErrors } = this.formReactiveService.buildForm({
90 'current-password': USER_EXISTING_PASSWORD_VALIDATOR
93 this.formPassword = form
94 this.formErrorsPassword = formErrors
97 private buildOTPForm () {
98 const { form, formErrors } = this.formReactiveService.buildForm({
99 'otp-token': USER_OTP_TOKEN_VALIDATOR
103 this.formErrorsOTP = formErrors