Failure to validate the API in accordance with the database

Having an issue with login validation in Angular code while using Spring Boot backend. Even when providing incorrect credentials, the login form still shows as successful. Need help troubleshooting this problem.

1) auth.service.ts


    import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  
  USER_NAME_SESSION_ATTRIBUTE_NAME = 'authenticatedUser'

  public patId!: number;
  public password!: String;

  constructor(private http: HttpClient) {

  }

  authenticationService(patId :number, password: String) {
    return this.http.get(`http://localhost:8080/patientlogins`,
      { headers: { authorization: this.createBasicAuthToken(patId, password) } }).pipe(map((res) => {
        this.patId = patId;
        this.password = password;
        
      }));
  }

  createBasicAuthToken(patId: number, password: String) {
    return 'Basic ' + window.btoa(patId + ":" + password)
  }

  
  isUserLoggedIn() {
    let user = sessionStorage.getItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME)
    if (user === null) return false
    return true
  }

  getLoggedInpatId() {
    let user = sessionStorage.getItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME)
    if (user === null) return ''
    return user
  }
}

2)login.component.html

<div class="container col-lg-6">
    <h1 class="text-center">Login</h1>
    <div class="card">
      <div class="card-body">
        <form class="form-group">
          <div class="alert alert-warning" *ngIf='invalidLogin'>{{errorMessage}}</div>
          <div class="alert alert-success" *ngIf='loginSuccess'>{{successMessage}}</div>
          <div class="form-group">
            <label for="number">PatientId:</label>
            <input type="text" class="form-control" id="patId" [(ngModel)]="patId" placeholder="Enter patId"
              name="patId">
          </div>
          <div class="form-group">
            <label for="pwd">Password:</label>
            <input type="password" class="form-control" [(ngModel)]="password" id="password" placeholder="Enter password"
              name="password">
          </div>
          <button (click)=handleLogin() class="btn btn-success">Login</button>
          <p class="message">Not registered? <a href="#">Create an account</a></p>
        </form>
      </div>
    </div>
  </div>

3)login.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

import { AuthenticationService } from './auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  patId!: number;
  password!: string;
  errorMessage = 'Invalid Credentials';
  successMessage!: string;
  invalidLogin = false;
  loginSuccess = false;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService) {   }

  ngOnInit() {
  }

  handleLogin() {
    this.authenticationService.authenticationService(this.patId, this.password).subscribe((result)=> {
      this.invalidLogin = false;
      this.loginSuccess = true;
      this.successMessage = 'Login Successful.';
      this.errorMessage='Invalid Login';
      
    }, () => {
      this.invalidLogin = true;
      this.loginSuccess = false;
    });      
  }
}

4)app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/login.component';

const routes: Routes = [
  {path: 'login', component: LoginComponent},

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

5)app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { LoginComponent } from './login/login.component';
import { FormsModule } from '@angular/forms';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
   
    LoginComponent,
        HomeComponent
    
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №1

() => {
        this.invalidLogin = true;
        this.loginSuccess = false;
      }

When the handleLogin function is triggered, it only runs if the HTTP server returns an error (such as 500 or 503).

Implementing this part of the code should resolve the issue.

  handleLogin() {
    this.authenticationService.authenticationService(this.patId, this.password).subscribe((result)=> {
      
      for (const obj of result) {
        if (obj.patId === this.patId && obj.password === this.password) {
          this.invalidLogin = false;
          this.loginSuccess = true;
          this.successMessage = 'Login Successful.';
          return;
        }
      }
      this.invalidLogin = true;
      this.loginSuccess = false;
      this.errorMessage='Invalid Login';
      
    }, () => {
      this.invalidLogin = true;
      this.loginSuccess = false;
    });      
  }

It is highly recommended not to include user passwords in the HTTP response to avoid exposing sensitive information. Validate the ID and password on the server side and only provide the necessary response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When setting a value that has been explicitly casted, the original literal type remains intact for the new property or variable

After defining the constant MODE with specific values, I noticed something interesting: const MODE = { NONE: 0 as 0, COMPLETED: 1 as 1, DELETED: 2 as 2 } as const // In a CreateReactApp project, enums aren't available It became appar ...

Facing issues with query parameters functionality

For my Angular2 application, I need to include some optional parameters in a route. Since they are not mandatory, I have opted to utilize the queryParams feature. This is the code snippet I am using to pass the optional argument: public recoverPassword() ...

When I executed the npm install -g @angularcli command, I encountered an npm error with the code ENOLOCAL

On my initial attempt, I used a computer with Windows 10 and another one with Windows 8.1. Surprisingly, I encountered the same error message on both systems. The log of the error is as follows: npm ERR! code ENOLOCAL npm ERR! Could not install from "@ang ...

Choose the material and eliminate any gaps

Is there a preferred method for eliminating empty space in Material select/input fields? I am looking to ensure the field width matches the content size. https://i.stack.imgur.com/ZmgKK.png Visit https://material.angular.io/components/select/overview for ...

Transform **kerry James O'keeffe-martin** into **Kerry James O'Keeffe-Martin** using TypeScript and Java Script

Is there a way to capitalize names in both TypeScript and JavaScript? For example, changing kerry James O'keeffe-martin to Kerry James O'Keeffe-Martin. ...

Form with checkboxes in a Next.js and Typescript application

I am currently working on a project using Next.js and Typescript. I have implemented a form in this project, which is my first experience with Typescript and checkbox types. However, I am encountering difficulties in retrieving all checkbox values, adding ...

Confirm that one input falls within a specified range of two inputs

I am trying to implement javascript validation for a form with two inputs. Specifically, I want to achieve the following: If a text input is entered and the dropdown remains unselected, the validation should trigger for the text input and the form should ...

What exactly does RouteComponentProps entail?

While exploring information on React, I came across the term RouteComponentProps. For example: import { RouteComponentProps } from 'react-router-dom'; const ~~~: React.FC<RouteComponentProps> and class BookingSiteOverview extends React.Com ...

Storing Passport.js Token Locally: Best Practices

Struggling to save the jwt token provided by passport.js in browser localStorage, I am facing challenges with transferring it from the server to the client as it is generated on the server side. If anyone can assist me with setting the server-generated to ...

Prevent special characters in input fields using Angular and TypeScript

I am currently working on an Angular project using Ant Design ng Zorro. I've encountered an issue with validation when trying to restrict special characters in an input field. Despite setting up the validation rules, it seems that the key press event ...

When an Angular service is created, its properties are not immediately configured

My current task involves testing an Angular (4.1) service that looks like this: @Injectable() export class JobService { private answerSource = new Subject<AnswerWrapper>(); answer$ = this.answerSource.asObservable(); answer(answer: AnswerWra ...

Angular 5 is encountering an error with a recursive template, specifically a RangeError stating that the maximum call stack

Hey there, I'm currently utilizing Angular recursive template to represent arrays recursively. The code I've been following is provided in this link. My array is dynamic in nature. <ul> <ng-template #recursiveList let-list> ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

Having trouble building my Angular 2 app with Angular-cli beta 14, despite it working perfectly fine with systemjs beforeEach

I have been using VSCode on Windows 10 to work on an app developed in Angular 2 final version, which runs smoothly with systemjs. Recently, I upgraded to angular-cli beta 14 webpack version and followed the steps outlined in the upgrade document here. How ...

Securing Email and Password Data in Cypress Tests

Greetings! I trust everyone is in good spirits. My dilemma lies in the fact that I am hesitant to include email and passwords in version control. I am considering using environment variables in my cypress tests and utilizing secrets for runtime value pro ...

Enhancing Selectpicker options in Angular using data fetched from a web service

Having trouble with updating a selectpicker element within a subscribe method. I've included the code snippets below: Here is my HTML code: <div class="form-group col-md-2 pull-right"> <label for="city">City</label> <select ...

Saving the contents of a JSON query field to a file using Angular

Currently, I am working on an Angular application that interacts with a JSON API to extract specific fields from the data and save them to a file. For instance, if the API query yields: [{"id":1,"name":"Banana"},{"id" ...

ReactNative: When attempting to navigate, a TypeError occurred - this.props.navigation.navigate is not a function

It's confusing to see how this issue is occurring, even though all props have been properly typed. The goal is to pass the navigator to the bottom bar component in order to navigate onPress. Initially, I define the props interface: export interface B ...

Tips for formatting the return Date when utilizing the setDate() method

I set the end of the week to be the upcoming weekend using the following code snippet this.weekEnd = new Date(this.currentDate.setDate(end)); Now, my goal is to update the weekEnd by adding 7 days to it. I attempted to achieve this as shown below, however ...