Spartacus login form(spring security) submit to external application?

 1. login component HTML

refer form tag:

 <form  (ngSubmit)="submitForm()" [formGroup]="loginForm" id="loginForm" >

 submitForm() is defined in login component ts file

<form  (ngSubmit)="submitForm()" [formGroup]="loginForm" id="loginForm" > 
 <label >{{ 'miniLogin.signInRegister' | cxTranslate | uppercase }}</label> 
  <div class="form-group">
    <label>
      <input
        type="email"
        class="form-control"
        formControlName="j_username"
        placeholder="{{ 'loginForm.emailAddress.placeholder' | cxTranslate }}"
        name="j_username"
      />
      <cx-form-errors [control]="loginForm.get('j_username')"></cx-form-errors>
    </label>
  </div>
  <div class="form-group">
    <label>
      <input
        type="password"
        class="form-control"
        placeholder="{{ 'loginForm.password.placeholder' | cxTranslate }}"
        formControlName="j_password"
        name="j_password"
        
      />
      <cx-form-errors [control]="loginForm.get('j_password')"></cx-form-errors>
    </label>
  </div>
  <p>
    <a
      [routerLink]="{ cxRoute: 'forgotPassword' } | cxUrl"
      aria-controls="reset-password"
      class="btn-link"
      >{{ 'loginForm.forgotPassword' | cxTranslate }}</a
    >
  </p>
  <ng-container>
    <div class="row">
      <div class="col-6"> <button type="submit" class="btn btn-block btn-primary" >
        {{ 'loginForm.signIn' | cxTranslate | uppercase }}
      </button></div>
      <div class="col-6">
        <ng-container *ngIf="!loginAsGuest">
          <a
            [routerLink]="{ cxRoute: 'register' } | cxUrl"
            class="btn btn-block btn-primary"
            >{{ 'loginForm.register' | cxTranslate | uppercase}}</a
          >
        </ng-container> </div>
    </div>
  
</ng-container>
</form>


 

2. login component ts file

 refer: submitForm(): void method.

import { DOCUMENT } from '@angular/common';
import { ComponentInjectOnDestroyOnInit } from '@angular/core';
import { FormBuilderFormGroupValidators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import {
  AuthRedirectService,
  AuthService,
  BaseSiteService,
  GlobalMessageService,
  GlobalMessageType,
  LanguageService,
  WindowRef,
from '@spartacus/core';
import { CheckoutConfigServiceCustomFormValidators } from '@spartacus/storefront';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-bdi-login-form',
  templateUrl: './bdilogin-form.component.html',
})
export class BDILoginFormComponent implements OnInitOnDestroy {
  subSubscription;
  loginFormFormGroup;
  loginAsGuest = false;
  currentCoutry = '';
  currentLanguage = '';

  constructor(
    protected authAuthService,
    protected globalMessageServiceGlobalMessageService,
    protected fbFormBuilder,
    protected authRedirectServiceAuthRedirectService,
    protected winRefWindowRef,
    protected activatedRouteActivatedRoute,
    protected checkoutConfigServiceCheckoutConfigService,
    protected languageServiceLanguageService,
    protected baseSiteServiceBaseSiteService,
    @Inject(DOCUMENTprivate documentDocument
  ) {}

  ngOnInit(): void {
    const routeState = this.winRef.nativeWindow?.history?.state;
    const prefilledEmail = routeState?.['newUid'];

    this.loginForm = this.fb.group({
      j_username: [
        prefilledEmail?.length ? prefilledEmail : '',
        [Validators.requiredCustomFormValidators.emailValidator],
      ],
      j_password: [''Validators.required],
    });

    if (this.checkoutConfigService.isGuestCheckout()) {
      this.loginAsGuest = this.activatedRoute?.snapshot?.queryParams?.['forced'];
    }
  }

  submitForm(): void {
    if (this.loginForm.valid) {
      
      const window = this.winRef.nativeWindow;
      const loginURL = window.location.href + '/j_spring_security_check';
      console.log('loginURL: ' + loginURL);

      const formHTMLFormElement = this.document.querySelector('form#loginForm');
      form.method = 'POST';
      form.action = loginURL;
      form.style.display = 'none';
      form.submit();
      //this.loginUser();
    } else {
      this.loginForm.markAllAsTouched();
    }
  }

  ngOnDestroy(): void {
    if (this.sub) {
      this.sub.unsubscribe();
    }
  }

  protected loginUser(): void {
    const { j_usernamej_password } = this.loginForm.controls;
    this.auth.authorize(
      j_username.value.toLowerCase(), // backend accepts lowercase emails only
      j_password.value
    );

    if (!this.sub) {
      this.sub = this.auth.getUserToken().subscribe((data=> {
        if (data && data.access_token) {
          this.globalMessageService.remove(GlobalMessageType.MSG_TYPE_ERROR);
          this.authRedirectService.redirect();
        }
      });
    }
  }
}


 


Comments

Popular posts from this blog

Hybris / SAP Commerce Cloud Groovy Scripting Job to Generate CSV/Excel Reports and copy to Commerce cloud Blob Storage

Emma's dream - a kids story - By Kavya

Hybris/ SAP commerce Cloud: Retry failed/not sent emails due to SMTP connection issue.