e5343b33d6798bce06fdc9ff9e9c9ca121227451
[oweals/peertube.git] /
1 import { Component, OnInit } from '@angular/core'
2 import { NotificationsService } from 'angular2-notifications'
3 import { FormReactive, UserService } from '../../../shared'
4 import { I18n } from '@ngx-translate/i18n-polyfill'
5 import { FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
6 import { UserValidatorsService } from '@app/shared/forms/form-validators/user-validators.service'
7 import { filter } from 'rxjs/operators'
8 import { AuthService } from '@app/core'
9 import { User } from '../../../../../../shared'
10
11 @Component({
12   selector: 'my-account-change-password',
13   templateUrl: './my-account-change-password.component.html',
14   styleUrls: [ './my-account-change-password.component.scss' ]
15 })
16 export class MyAccountChangePasswordComponent extends FormReactive implements OnInit {
17   error: string = null
18   user: User = null
19
20   constructor (
21     protected formValidatorService: FormValidatorService,
22     private userValidatorsService: UserValidatorsService,
23     private notificationsService: NotificationsService,
24     private authService: AuthService,
25     private userService: UserService,
26     private i18n: I18n
27   ) {
28     super()
29   }
30
31   ngOnInit () {
32     this.buildForm({
33       'current-password': this.userValidatorsService.USER_PASSWORD,
34       'new-password': this.userValidatorsService.USER_PASSWORD,
35       'new-confirmed-password': this.userValidatorsService.USER_CONFIRM_PASSWORD
36     })
37
38     this.user = this.authService.getUser()
39
40     const confirmPasswordControl = this.form.get('new-confirmed-password')
41
42     confirmPasswordControl.valueChanges
43                           .pipe(filter(v => v !== this.form.value[ 'new-password' ]))
44                           .subscribe(() => confirmPasswordControl.setErrors({ matchPassword: true }))
45   }
46
47   changePassword () {
48     const currentPassword = this.form.value[ 'current-password' ]
49     const newPassword = this.form.value[ 'new-password' ]
50
51     this.userService.changePassword(currentPassword, newPassword).subscribe(
52       () => {
53         this.notificationsService.success(this.i18n('Success'), this.i18n('Password updated.'))
54
55         this.form.reset()
56         this.error = null
57       },
58
59       err => {
60         if (err.status === 401) {
61           this.error = this.i18n('You current password is invalid.')
62           return
63         }
64
65         this.error = err.message
66       }
67     )
68   }
69 }