c8bd368c19df09e2928f9fd5507cbd5f91915ed5
[oweals/peertube.git] / client / src / app / reset-password / reset-password.component.ts
1 import { Component, OnInit } from '@angular/core'
2 import { FormBuilder, FormGroup, Validators } from '@angular/forms'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { USER_PASSWORD, UserService } from '@app/shared'
5 import { NotificationsService } from 'angular2-notifications'
6 import { AuthService } from '../core'
7 import { FormReactive } from '../shared'
8 import { I18n } from '@ngx-translate/i18n-polyfill'
9
10 @Component({
11   selector: 'my-login',
12   templateUrl: './reset-password.component.html',
13   styleUrls: [ './reset-password.component.scss' ]
14 })
15
16 export class ResetPasswordComponent extends FormReactive implements OnInit {
17   form: FormGroup
18   formErrors = {
19     'password': '',
20     'password-confirm': ''
21   }
22   validationMessages = {
23     'password': USER_PASSWORD.MESSAGES,
24     'password-confirm': {
25       'required': 'Confirmation of the password is required.'
26     }
27   }
28
29   private userId: number
30   private verificationString: string
31
32   constructor (
33     private authService: AuthService,
34     private userService: UserService,
35     private notificationsService: NotificationsService,
36     private formBuilder: FormBuilder,
37     private router: Router,
38     private route: ActivatedRoute,
39     private i18n: I18n
40   ) {
41     super()
42   }
43
44   buildForm () {
45     this.form = this.formBuilder.group({
46       password: [ '', USER_PASSWORD.VALIDATORS ],
47       'password-confirm': [ '', Validators.required ]
48     })
49
50     this.form.valueChanges.subscribe(data => this.onValueChanged(data))
51   }
52
53   ngOnInit () {
54     this.buildForm()
55
56     this.userId = this.route.snapshot.queryParams['userId']
57     this.verificationString = this.route.snapshot.queryParams['verificationString']
58
59     if (!this.userId || !this.verificationString) {
60       this.notificationsService.error(this.i18n('Error'), this.i18n('Unable to find user id or verification string.'))
61       this.router.navigate([ '/' ])
62     }
63   }
64
65   resetPassword () {
66     this.userService.resetPassword(this.userId, this.verificationString, this.form.value.password)
67       .subscribe(
68         () => {
69           this.notificationsService.success(this.i18n('Success'), this.i18n('Your password has been successfully reset!'))
70           this.router.navigate([ '/login' ])
71         },
72
73         err => this.notificationsService.error('Error', err.message)
74       )
75   }
76
77   isConfirmedPasswordValid () {
78     const values = this.form.value
79     return values.password === values['password-confirm']
80   }
81 }