Encountering issues with verifying login credentials in Angular 2

Greetings! I have designed a login page where the user will be logged in if the response is successful, otherwise an error message will be displayed. Below is the JSON data with email and password fields:

{ 
  Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="600d011817090c2005030f1705024e030f0d">[email protected]</a>",
  password:56897

}

Here is the login method implementation:

 this.serv.getLogin(data.Email,data.password).subscribe(res=>{
          if (res.Data.Id === 0 && res.Data.Id === null || res.Status === 'false') {
            alert('please check the username or password');
            return false;
          } else {
            console.log(res);
            localStorage.setItem('UserDetails', JSON.stringify(res));
            this.router.navigate(['/TrackDriver']);
            return true;
          }

        },err => {
          console.log(err);
        });

The issue here is that it still logs in even with incorrect credentials. However, when using the correct email and password provided above, the login is successful.

{
    "Data": {
        "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e535f464957527e5b5d51495b5c105d5153">[email protected]</a>",
        "Id": "1",
        "Name": "Admin"
    },
    "ErrorCode": "201 - Success",
    "Message": "Success",
    "Status": true
}

Even with incorrect details, the system logs in and returns the following response:

{
  "Data": {
    "Email": null,
    "Id": null,
    "Name": null
  },
  "ErrorCode": "501 - No Data Found",
  "Message": "Please Check Credentials",
  "Status": false
}

Despite providing incorrect details, the system still allows login. The cause of this issue remains unclear to me.

Answer №1

The issue lies within your if condition in the getLogin callback function:

if (res.Data.Id === 0 && res.Data.Id === null || res.Status === 'false') {

This condition is logically incorrect, as it is impossible for res.Data.Id to be both 0 and null simultaneously. Additionally, there is a type mismatch with res.Status: it is treated as boolean false, not string 'false'.

To rectify this, modify the second part of the condition to check if res.Status is false:

if ([...] || !res.Status)

If both 0 and null indicate login failure, adjust the first part of the condition accordingly:

if (res.Data.Id === 0 && res.Data.Id === null || [...])

Considering that both 0 and null are considered falsy values, you can simplify the condition as follows:

if (!res.Data.Id || !res.Status)

Answer №2

An error has been identified:

res.Status === 'false'

It is important to note that a boolean, not a string, is needed:

res.Status === false // this is the same as !res.Status

As a result, the login validation will not pass:

{
  "Data": {
    "Email": null,
    "Id": null,
    "Name": null
  },
  "ErrorCode": "501 - No Data Found",
  "Message": "Please Check Credentials",
  "Status": false // <---- This should be a Boolean value!
}

In addition, there is an issue with your if logic. The condition

res.Data.Id === 0 && res.Data.Id === null
will never be true, as a variable cannot be both 0 and null simultaneously.

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

Error! Unexpected closure occurred while creating an Angular CLI project with npm

After cloning an Angular (4+) CLI project onto a new machine and running npm install, I encountered an error that reads as follows. This project works perfectly fine on other computers: npm ERR! premature close npm ERR! A complete log of this run can be ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

Looking for a way to transfer the value of a variable to a PHP variable using any script or code in PHP prior to submitting a form?

Within this form, the script dynamically updates the module dropdown list based on the selected project from the dropdown box. The value of the module list is captured in a text field with id='mm', and an alert box displays the value after each s ...

The reason the CSS direct descendant selector does not affect Angular components

We are working with a basic main.html. <app> <sidebar></sidebar> <main-content> <router-outlet></router-outlet> </main-content> </app> After loading a component through routing (changing the ...

Having difficulty mastering the redux-form component typing

I am facing an issue while trying to export my component A by utilizing redux-form for accessing the form-state, which is primarily populated by another component. During the export process, I encountered this typing error: TS2322 Type A is not assignabl ...

An error has occurred: Unable to access the 'group_status' property of an undefined console object

I have been encountering a persistent error in the console, with it continuously increasing. The issue arises when I utilize two-way binding with ngModel alongside an interface. To provide further insight, I have included screenshots of my code below. Scr ...

Managing the resizing event of a structural directive while maintaining the original context

I am in the process of creating a custom ngIf directive to handle different platforms. *ifPl="'android' Currently, it is functioning well. When I am on an ios platform, the element is not present in the DOM, and vice versa. However, I would lik ...

Ways to eliminate the worldwide model in SAPUI5

I've been attempting to break down the global model without success. I have a filter button that's set up like this: navToSecond : function (oEvent){ var oObject = this.getView().byId("inp").getValue(); sap.ui.getCore().setModel( ...

Issue encountered with invoking carousel.to() method in Bootstrap 5

// Create a new carousel instance let car = new bootstrap.Carousel(document.querySelector('#carouselMenu'), { interval: 0, wrap: false }); // <SNIP> // Go to page at index 1 car.to("1"); Error: https://i.sstat ...

Guide to triggering React Material-UI modal and filling it with data from an Ajax request when a button is clicked

Despite my efforts to find a similar question, I couldn't come across one. My apologies if I overlooked it. Currently, I am working on a React Material-UI project to develop a basic web application. Within this application, there is an XGrid that disp ...

Monitor and retrieve live updates of links using Javascript

I am a beginner in JavaScript and recently developed a successful Chrome extension for Dubtrack. I have been struggling to find a way to make my injected script run in real-time and grab the latest YouTube music video URL. Any assistance would be greatly a ...

Trouble encountered while retrieving the data structure in order to obtain the outcome [VueJs]

I am facing an issue while trying to save information from an HTTP request into a structure and then store it in local storage. When I attempt to retrieve the stored item and print a specific value from the structure, it does not work! Here is my code: / ...

PHP form submission upon conditions being satisfied

I am not utilizing Javascript as it is disabled in my current environment. Here is the code that I would like you to review. I am attempting to use PHP to replicate the functionality of Javascript or jQuery's simple : document.form2.submit() <div ...

Error: The function webpackMerge.strategy does not exist

I've been in the process of updating an older Angular project to the latest version of Angular. However, I'm encountering a problem when trying to build, and I'm unsure why this is happening. Below is the error message that I've receiv ...

Ensure that the link's color remains constant and remove any styling of text-decoration

Attempting to create a customized header. My goal is to change the color and remove text decoration in the navbar. Below is my code snippet: ReactJS: import React from 'react'; import './Header.css'; function Header() { return ( ...

The placement of the breadcrumb trail is not in the right position

My website includes a menu and breadcrumbs. The menu consists of two submenus: Design Services, Design Portfolio, Design Fees, About Us, Contact Us, Design Resources, Design Vacancies, and Terms. Clicking on Design Services reveals Graphic Design, Logo Des ...

What is the technique for filtering multiple values using the OR operation in ng-model functions?

Currently, I am using an ng-modal labeled as "myQuery." At the moment, there are two filters in place that look like this: <accordion-group heading="" ng-repeat="hungry_pets in Pets" | filter:{hungry:false} | filter:{name:myQuery}" ... > I have ...

How can you make the coordinates of the cursor track the cursor when it hovers over a rectangle?

The code provided below will constantly display the cursor's coordinates right below the cursor: function displayCursorCoordinates(e) { var x = event.clientX; var y = event.clientY; var coordinates = "(" + x + ", " + y + ")"; document.getEl ...

Determine whether a JavaScript string exclusively consists of punctuation marks

In an if statement, I want to verify whether the given string contains any punctuation. If it does contain punctuation marks, I intend to display a pop-up alert message. if((/*regex presumably*/.test(rspace))==true||(/*regex presumably*/.test(sspace))==tr ...

Altering the hover functionality for dynamically created class elements

I have a vision to create a unique e-commerce storefront with tile design, featuring an item thumbnail that reveals the item name upon hovering. I found inspiration from this example, but I want the item name to slide up smoothly on hover, rather than simp ...