]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+login/login.component.ts
Merge branch 'feature/otp' into develop
[github/Chocobozzz/PeerTube.git] / client / src / app / +login / login.component.ts
1 import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'
2 import { ActivatedRoute, Router } from '@angular/router'
3 import { AuthService, Notifier, RedirectService, SessionStorageService, UserService } from '@app/core'
4 import { HooksService } from '@app/core/plugins/hooks.service'
5 import { LOGIN_PASSWORD_VALIDATOR, LOGIN_USERNAME_VALIDATOR } from '@app/shared/form-validators/login-validators'
6 import { USER_OTP_TOKEN_VALIDATOR } from '@app/shared/form-validators/user-validators'
7 import { FormReactive, FormReactiveService, InputTextComponent } from '@app/shared/shared-forms'
8 import { InstanceAboutAccordionComponent } from '@app/shared/shared-instance'
9 import { NgbAccordion, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'
10 import { PluginsManager } from '@root-helpers/plugins-manager'
11 import { RegisteredExternalAuthConfig, ServerConfig } from '@shared/models'
12
13 @Component({
14 selector: 'my-login',
15 templateUrl: './login.component.html',
16 styleUrls: [ './login.component.scss' ]
17 })
18
19 export class LoginComponent extends FormReactive implements OnInit, AfterViewInit {
20 private static SESSION_STORAGE_REDIRECT_URL_KEY = 'login-previous-url'
21
22 @ViewChild('forgotPasswordModal', { static: true }) forgotPasswordModal: ElementRef
23 @ViewChild('otpTokenInput') otpTokenInput: InputTextComponent
24
25 accordion: NgbAccordion
26 error: string = null
27 forgotPasswordEmail = ''
28
29 isAuthenticatedWithExternalAuth = false
30 externalAuthError = false
31 externalLogins: string[] = []
32
33 instanceInformationPanels = {
34 terms: true,
35 administrators: false,
36 features: false,
37 moderation: false,
38 codeOfConduct: false
39 }
40
41 otpStep = false
42
43 private openedForgotPasswordModal: NgbModalRef
44 private serverConfig: ServerConfig
45
46 constructor (
47 protected formReactiveService: FormReactiveService,
48 private route: ActivatedRoute,
49 private modalService: NgbModal,
50 private authService: AuthService,
51 private userService: UserService,
52 private redirectService: RedirectService,
53 private notifier: Notifier,
54 private hooks: HooksService,
55 private storage: SessionStorageService,
56 private router: Router
57 ) {
58 super()
59 }
60
61 get signupAllowed () {
62 return this.serverConfig.signup.allowed === true
63 }
64
65 get instanceName () {
66 return this.serverConfig.instance.name
67 }
68
69 onTermsClick (event: Event, instanceInformation: HTMLElement) {
70 event.preventDefault()
71
72 if (this.accordion) {
73 this.accordion.expand('terms')
74 instanceInformation.scrollIntoView({ behavior: 'smooth' })
75 }
76 }
77
78 isEmailDisabled () {
79 return this.serverConfig.email.enabled === false
80 }
81
82 ngOnInit () {
83 const snapshot = this.route.snapshot
84
85 // Avoid undefined errors when accessing form error properties
86 this.buildForm({
87 username: LOGIN_USERNAME_VALIDATOR,
88 password: LOGIN_PASSWORD_VALIDATOR,
89 'otp-token': {
90 VALIDATORS: [], // Will be set dynamically
91 MESSAGES: USER_OTP_TOKEN_VALIDATOR.MESSAGES
92 }
93 })
94
95 this.serverConfig = snapshot.data.serverConfig
96
97 if (snapshot.queryParams.externalAuthToken) {
98 this.loadExternalAuthToken(snapshot.queryParams.username, snapshot.queryParams.externalAuthToken)
99 return
100 }
101
102 if (snapshot.queryParams.externalAuthError) {
103 this.externalAuthError = true
104 return
105 }
106
107 const previousUrl = this.redirectService.getPreviousUrl()
108 if (previousUrl && previousUrl !== '/') {
109 this.storage.setItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY, previousUrl)
110 }
111 }
112
113 ngAfterViewInit () {
114 this.hooks.runAction('action:login.init', 'login')
115 }
116
117 getExternalLogins () {
118 return this.serverConfig.plugin.registeredExternalAuths
119 }
120
121 getAuthHref (auth: RegisteredExternalAuthConfig) {
122 return PluginsManager.getExternalAuthHref(auth)
123 }
124
125 login () {
126 this.error = null
127
128 const options = {
129 username: this.form.value['username'],
130 password: this.form.value['password'],
131 otpToken: this.form.value['otp-token']
132 }
133
134 this.authService.login(options)
135 .pipe()
136 .subscribe({
137 next: () => this.redirectService.redirectToPreviousRoute(),
138
139 error: err => {
140 this.handleError(err)
141 }
142 })
143 }
144
145 askResetPassword () {
146 this.userService.askResetPassword(this.forgotPasswordEmail)
147 .subscribe({
148 next: () => {
149 const message = $localize`An email with the reset password instructions will be sent to ${this.forgotPasswordEmail}.
150 The link will expire within 1 hour.`
151
152 this.notifier.success(message)
153 this.hideForgotPasswordModal()
154 },
155
156 error: err => this.notifier.error(err.message)
157 })
158 }
159
160 openForgotPasswordModal () {
161 this.openedForgotPasswordModal = this.modalService.open(this.forgotPasswordModal)
162 }
163
164 hideForgotPasswordModal () {
165 this.openedForgotPasswordModal.close()
166 }
167
168 onInstanceAboutAccordionInit (instanceAboutAccordion: InstanceAboutAccordionComponent) {
169 this.accordion = instanceAboutAccordion.accordion
170 }
171
172 hasUsernameUppercase () {
173 return this.form.value['username'].match(/[A-Z]/)
174 }
175
176 private loadExternalAuthToken (username: string, token: string) {
177 this.isAuthenticatedWithExternalAuth = true
178
179 this.authService.login({ username, password: null, token })
180 .subscribe({
181 next: () => {
182 const redirectUrl = this.storage.getItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY)
183 if (redirectUrl) {
184 this.storage.removeItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY)
185 return this.router.navigateByUrl(redirectUrl)
186 }
187
188 this.redirectService.redirectToLatestSessionRoute()
189 },
190
191 error: err => {
192 this.handleError(err)
193 this.isAuthenticatedWithExternalAuth = false
194 }
195 })
196 }
197
198 private handleError (err: any) {
199 if (this.authService.isOTPMissingError(err)) {
200 this.otpStep = true
201
202 setTimeout(() => {
203 this.form.get('otp-token').setValidators(USER_OTP_TOKEN_VALIDATOR.VALIDATORS)
204 this.otpTokenInput.focus()
205 })
206
207 return
208 }
209
210 if (err.message.indexOf('credentials are invalid') !== -1) this.error = $localize`Incorrect username or password.`
211 else if (err.message.indexOf('blocked') !== -1) this.error = $localize`Your account is blocked.`
212 else this.error = err.message
213 }
214 }