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'
16 templateUrl: './login.component.html',
17 styleUrls: [ './login.component.scss' ]
20 export class LoginComponent extends FormReactive implements OnInit, AfterViewInit {
21 private static SESSION_STORAGE_REDIRECT_URL_KEY = 'login-previous-url'
23 @ViewChild('forgotPasswordModal', { static: true }) forgotPasswordModal: ElementRef
24 @ViewChild('otpTokenInput') otpTokenInput: InputTextComponent
25 @ViewChild('instanceAboutAccordion') instanceAboutAccordion: InstanceAboutAccordionComponent
27 accordion: NgbAccordionDirective
29 forgotPasswordEmail = ''
31 isAuthenticatedWithExternalAuth = false
32 externalAuthError = false
33 externalLogins: string[] = []
35 instanceInformationPanels = {
37 administrators: false,
45 private openedForgotPasswordModal: NgbModalRef
46 private serverConfig: ServerConfig
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
63 get signupAllowed () {
64 return this.serverConfig.signup.allowed === true
68 return this.serverConfig.instance.name
71 onTermsClick (event: Event, instanceInformation: HTMLElement) {
72 event.preventDefault()
74 if (this.instanceAboutAccordion) {
75 this.instanceAboutAccordion.expandTerms()
76 instanceInformation.scrollIntoView({ behavior: 'smooth' })
81 return this.serverConfig.email.enabled === false
85 const snapshot = this.route.snapshot
87 // Avoid undefined errors when accessing form error properties
89 'username': LOGIN_USERNAME_VALIDATOR,
90 'password': LOGIN_PASSWORD_VALIDATOR,
92 VALIDATORS: [], // Will be set dynamically
93 MESSAGES: USER_OTP_TOKEN_VALIDATOR.MESSAGES
97 this.serverConfig = snapshot.data.serverConfig
99 if (snapshot.queryParams.externalAuthToken) {
100 this.loadExternalAuthToken(snapshot.queryParams.username, snapshot.queryParams.externalAuthToken)
104 if (snapshot.queryParams.externalAuthError) {
105 this.externalAuthError = true
109 const previousUrl = this.redirectService.getPreviousUrl()
110 if (previousUrl && previousUrl !== '/') {
111 this.storage.setItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY, previousUrl)
116 this.hooks.runAction('action:login.init', 'login')
119 getExternalLogins () {
120 return this.serverConfig.plugin.registeredExternalAuths
123 getAuthHref (auth: RegisteredExternalAuthConfig) {
124 return getExternalAuthHref(environment.apiUrl, auth)
131 username: this.form.value['username'],
132 password: this.form.value['password'],
133 otpToken: this.form.value['otp-token']
136 this.authService.login(options)
139 next: () => this.redirectService.redirectToPreviousRoute(),
142 this.handleError(err)
147 askResetPassword () {
148 this.userService.askResetPassword(this.forgotPasswordEmail)
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.`
154 this.notifier.success(message)
155 this.hideForgotPasswordModal()
158 error: err => this.notifier.error(err.message)
162 openForgotPasswordModal () {
163 this.openedForgotPasswordModal = this.modalService.open(this.forgotPasswordModal)
166 hideForgotPasswordModal () {
167 this.openedForgotPasswordModal.close()
170 onInstanceAboutAccordionInit (instanceAboutAccordion: InstanceAboutAccordionComponent) {
171 this.accordion = instanceAboutAccordion.accordion
174 hasUsernameUppercase () {
175 return this.form.value['username'].match(/[A-Z]/)
178 private loadExternalAuthToken (username: string, token: string) {
179 this.isAuthenticatedWithExternalAuth = true
181 this.authService.login({ username, password: null, token })
184 const redirectUrl = this.storage.getItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY)
186 this.storage.removeItem(LoginComponent.SESSION_STORAGE_REDIRECT_URL_KEY)
187 return this.router.navigateByUrl(redirectUrl)
190 this.redirectService.redirectToLatestSessionRoute()
194 this.handleError(err)
195 this.isAuthenticatedWithExternalAuth = false
200 private handleError (err: any) {
201 if (this.authService.isOTPMissingError(err)) {
205 this.form.get('otp-token').setValidators(USER_OTP_TOKEN_VALIDATOR.VALIDATORS)
206 this.otpTokenInput.focus()
212 if (err.message.includes('credentials are invalid')) {
213 this.error = $localize`Incorrect username or password.`
217 if (err.message.includes('blocked')) {
218 this.error = $localize`Your account is blocked.`
222 if (err.body?.code === ServerErrorCode.ACCOUNT_WAITING_FOR_APPROVAL) {
223 this.error = $localize`This account is awaiting approval by moderators.`
227 if (err.body?.code === ServerErrorCode.ACCOUNT_APPROVAL_REJECTED) {
228 this.error = $localize`Registration approval has been rejected for this account.`
232 this.error = err.message