Limiting Login attempt in Flutter?

926 Views Asked by At

I was wondering to find a way to limit login attempt in flutter/firebase. I want the user to be able attempt login post 5 minutes of waiting. I had searched through the internet and could not find any resources to help me out. Do you have any sample code for my references ?

2

There are 2 best solutions below

2
Amit butani On

You can stored the time in local storage and when user login again match the stored time with current time if it's less then current time then show error.

0
quoci On

You can use SharedPreferences to store the last attempt of the user. Before the user can login you have to check if got a login restriction and have to pass 5 minutes.

In checkLogin you check if the user has a restriction, in this case if a login attempt time was stored. If not then he has no restriction and can login as usual. Else you check if 5 minutes have passed.

static const int fiveMinutes = 5 * 60 * 1000;
static const String lastAttemptKey = 'lastAttempt';

Future<void> checkLogin() async {
    // Initialize SharedPreferences
    SharedPreferences prefs = await SharedPreferences.getInstance();

    // Get last login attempt
    final int lastAttempt = prefs.getInt(lastAttemptKey);

    // Check if is not null
    if (lastAttempt != null) {
      // Get time now
      final int now = DateTime.now().millisecondsSinceEpoch;

      // Get the difference from last login attempt
      final int difference = now - lastAttempt;

      // Check if 5 minutes passed since last login attempt
      if (difference >= fiveMinutes) {
        // User can try to login again
        prefs.remove(lastAttemptKey);
        await login();
      } else {
        // Still in limit, show error
        print('You have to wait 5 minutes');
      }
    } else {
      // First try of user login
      await login();
    }
  }

Here the user can try to login. If it is succesfull navigate to the HomePage. Else you set the time of the login attempt to the local storage.

Future<void> login() async {
    if (login.success) {
      // Navigate to HomePage
    } else {
      // Initialize SharedPreferences
      SharedPreferences prefs = await SharedPreferences.getInstance();

      // Store attempt time
      prefs.setInt(lastAttemptKey, DateTime.now().millisecondsSinceEpoch);
    }
  }