Preventing Multiple Login Attempts in Angular.js Using Typescript

Is there a way to maintain the user login attempts limit even after page refresh?

login() {
/* Check if user has fewer than 5 failed login attempts */
if (this.failedAttempts < 4) {


  this.auth.login(this.credentials).subscribe(() => {
    this.router.navigateByUrl('/');
    this.alert.success('Welcome! Thanks for logging in!');
  }, (err) => {
    this.failedAttempts++;
    console.error(err);
    this.alert.error('Login failed. Invalid email or password.');
  });
  /*If user reaches 5 failed attempts, reset count after 5 minutes and disable submit button*/
} else if (this.failedAttempts < 4) {
} else {
  /* Increment number of lockouts */
  this.numLockedOut++;

  this.alert.error('Login failed. Invalid email or password. Locked out for ' + (this.numLockedOut * 300000) / 60000 + ' minutes');
  this.btnDisable = true;
  setTimeout(() => this.failedAttempts = 0, this.numLockedOut * 300000);
  setTimeout(() => this.btnDisable = false, this.numLockedOut * 300000);
}

}

Can we use settimeout() without restarting the timer on page refresh?

Answer №1

My recommendation is to integrate this feature using a login API, specifically a REST API.

Whenever the UI sends a login request to the API, it has the ability to monitor the number of unsuccessful login attempts.

// Keep track of login failure count for each username; this can be stored in a database or a Map
// loginFailureCount(username, count, expiryTime)

if (usernameIsBlocked(username) {
   return response indicating that login is blocked
} 

if (loginFailed) {
   incrementLoginFailureCount(username, expiryTime);
} else {
   resetLoginFailureCount(username);
}
// Include the loginFailureCount(username) in the API response if the login attempt fails

Now, the API not only records the failure count but also provides information about locked accounts.

// Display the failure count or locked message in the UI when the login response indicates a failure

Answer №2

It is crucial to log failed login attempts on the server instead of relying on client-side scripting. Even if you manage to implement this code successfully, it's easy for users to manipulate the JavaScript and launch unlimited login tries.

By having the server track attempted logins associated with a username, it can inform the user when the login limit is surpassed. This approach not only addresses the issue of retaining attempt counts across sessions but also enhances security. :)

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

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

Leaving the "OK" button untouched in the sweet alert dialog

While implementing sweet alert in my project, I encountered an issue where the button text was not changing and the cancel button was missing on some pages. On certain pages, it only displayed OK. You can see a screenshot below for reference. https://i.s ...

How should .has(), .get() and .set() be properly implemented for a JavaScript Map() within an ExpressJS server?

Feeling thrown off by javascript Map()? My query revolves around javascript Map() - the set, get, and has() functions. Despite thinking I was an expert, it seems I still have things to learn... Situation: I'm dealing with a 'global' map sto ...

Error encountered: The object 'Sys' is not defined in the Microsoft JScript runtime

I currently have a webpage with the following code snippet: <script type="text/javascript" language="javascript"> /// <reference name="MicrosoftAjax.js" /> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler ...

Enforcing type safety for mysql2 results in Typescript leads to robust data handling

I have been working on a project using NextJS and Typescript where I need to properly type my MySQL responses. This is the API endpoint I am working with: import { hash } from "bcrypt"; import type { NextApiRequest, NextApiResponse } from "n ...

Encountering a syntax error while utilizing a JavaScript variable in a jQuery selector for a lightbox feature

I'm currently working on creating a lightbox feature and have reached the stage where I am implementing next and previous buttons to navigate through images. I am utilizing console.log to check if the correct href is being retrieved when the next butt ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

What is the best way to export image paths using require() from a single index.js file in a React Native project?

I am looking for a way to efficiently export all images from a single file named index.js, so that in the future, if I need to change the path of an image, I only have to make changes in one file. For example: export {default as avatar} from './avata ...

Angular is unable to fetch the chosen option from a dropdown selection

Recently, I encountered an issue with a module form that appears as a pop-up. Within this form, users can input data required to create a new object of a specific class. One field allows users to select a ventilation zone for the new room object being crea ...

Testing Material-UI's autocomplete with React Testing Library: a step-by-step guide

I am currently using the material-ui autocomplete component and attempting to test it with react-testing-library. Component: /* eslint-disable no-use-before-define */ import TextField from '@material-ui/core/TextField'; import Autocomplete from ...

Upon upgrading @types/angular, I encountered error TS2694 stating that the namespace 'angular' does not have an exported member 'xxx'

Following the upgrade of angular and @types/angular to version 1.6.x, an array of TS2694 errors suddenly appeared: error TS2694: Namespace 'angular' does not include an exported member named 'material' error TS2694: Namespace 'ang ...

Validate if the Jquery AJAX response contains any data

I've been attempting to integrate an alert message in my code that triggers if the response is null, but every time I try to do so, something goes wrong. If anyone has any suggestions or assistance with this issue, it would be greatly appreciated. He ...

Step-by-step guide on generating a fluid list with Express and HTML

Looking to create a dynamic list by fetching data from a JSON file. I want the list items to redirect me to specific content based on their IDs when clicked. However, my current approach is not working as expected, and the list needs to be truly dynamic. ...

Creating interactive form fields using React

How can I update nested fields in react forms? First, create a new item using handleAddShareholder. Next, delete an existing item with handleRemoveShareholder. To change details of an item, use handleShareholderNameChange. You can then add a new array ...

Tips for creating a high-performing algorithm to locate a specific word within a JSON file

I am in the process of creating a word game that involves users typing letters on a board to form meaningful words. If the typed word matches any word in a JSON file, the user earns a point. I have successfully implemented the basic functionalities of the ...

Trigger a functional component's function in React using Chrome developer tools

function App() { const myFunction = () => { console.log('hello world!') } return <div>...</div> } After the website has fully loaded and the component is mounted, can we access the JavaScript to call myFunction()? ...

Adjusting individual row data

Currently, I am utilizing the smart-table to showcase tabular data. Within the table, there is one editable column that can be modified within an input field. Each row contains a reset button, intended to revert any edits made in the input field back to it ...

Improving Vue Component on Navigation

I am facing an issue with my navbar where I have two versions. Version 1 features a white text color, while Version 2 has black text. The need for two versions arises due to some pages having a white background, hence the requirement for black text. Bot ...

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

Creating a versatile function for rendering content

I am working on a unique calendar feature that involves using checkboxes for filtering purposes. So far, I have managed to get all the filters functioning correctly by triggering my render event in this manner: //Initiate render event when checkbox is cli ...