import { Component, OnInit } from '@angular/core' import { FormControl, FormGroup, Validators } from '@angular/forms' import { ActivatedRoute, Router } from '@angular/router' import { UikitAuthService } from '@bit/dapi.lib-uikit-auth.uikit-auth/dist/uikit-auth' import { SessionService } from 'src/app/services/session/session.service' import { loginVariables } from './variables' @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit { redirectUri = '' loginVariables: any loginAppear = false errorMessage = false loginForm = new FormGroup({ user: new FormControl('', [ Validators.required, Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$'), ]), password: new FormControl('', Validators.required), }) constructor( private router: Router, private route: ActivatedRoute, private sessionService: SessionService, private snackBarService: UikitAuthService, ) { this.redirectUri = this.route.snapshot.queryParamMap.get('redirect_uri') this.loginVariables = loginVariables.admin } ngOnInit() { this.sessionService .verifyRedirectUri(this.redirectUri) .then((isValid: boolean) => { isValid ? (this.loginAppear = true) : this.router.navigate(['invalid']) }) .catch((err) => { console.error(err) this.router.navigate(['invalid']) }) } /** * If the url is valid , the login page will be rendered * And the user can put credential to go into the page */ login() { this.sessionService .login( this.loginForm.get('user').value, this.loginForm.get('password').value, ) .then((response) => { location.href = `${this.redirectUri}?AccessToken=${response.AccessToken}&idToken=${response.IdToken}&RobotinuumToken=${response.RobotinuumToken}` }) .catch((err) => { if (err.status === 403) { this.router.navigate(['first-confirm-password'], { state: { user: this.loginForm.value.user, oldPassword: this.loginForm.value.password, }, }) } else { this.wrongCredentials(err.error) } }) } /** * Redirect the user to the forgot password page. */ forgotPassword() { this.router.navigate(['forgot-password']) } /** * If the login fails a message will be appeared * And the notification message will be displayed * * @param errMsg Text with the error message. */ wrongCredentials(errMsg: string) { errMsg.includes('disabled')? '': this.errorMessage = true this.snackBarService.openSnackBar(errMsg) } }