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