Repository: jupyterhub/nativeauthenticator

Issue:
Block user after X logins failed
- [ ] Allow blocking user from system
- [ ] Add feature on admin panel to set number of trials 
- [ ] Add list of blocked users on admin panel
- [ ] Add verification of number of trials on login

Discussion:

Patch:
diff --git a/docs/index.rst b/docs/index.rst
index fec3322..ce1b415 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -14,7 +14,7 @@ Indices and tables
 ==================
 
 .. toctree::
-   :maxdepth: 2
+   :maxdepth: 1
    :caption: Contents:
 
    quickstart
diff --git a/docs/options.rst b/docs/options.rst
index 565a19f..2a33fb7 100644
--- a/docs/options.rst
+++ b/docs/options.rst
@@ -2,7 +2,7 @@ Feature Options
 ===============
 
 Password Strength
-----------------
+-----------------
 
 By default, when a user signs up through Native Authenticator there is no password strength verification. There are two methods that you can add to increase password strength: a verification for commmon passowords and a minimum length of password. 
 
@@ -20,3 +20,19 @@ You can also add a minimum password length that the user must have. To do this a
 .. code-block:: python
 
     c.Authenticator.minimim_password_length = 10
+
+
+Block users after failed logins
+-------------------------------
+
+One thing that can make systems more safe is to block users after a number of failed logins. With Native Authenticator you can add this feature by adding `allowed_failed_logins` on the config file. The default is 0, which means that the system will not block users ever.
+
+.. code-block:: python
+
+    c.Authenticator.allowed_failed_logins = 3
+
+You can also define the number of seconds a user must wait before trying again. The default value is 600 seconds.
+
+.. code-block:: python
+
+    c.Authenticator.secs_before_next_try = 1200
diff --git a/nativeauthenticator/nativeauthenticator.py b/nativeauthenticator/nativeauthenticator.py
index 1f2c1f8..d454a33 100644
--- a/nativeauthenticator/nativeauthenticator.py
+++ b/nativeauthenticator/nativeauthenticator.py
@@ -1,5 +1,6 @@
 import bcrypt
 import os
+from datetime import datetime
 from jupyterhub.auth import Authenticator
 
 from sqlalchemy import inspect
@@ -26,10 +27,23 @@ class NativeAuthenticator(Authenticator):
         help="""Check if the length of the password is at least this size on
         signup"""
     )
+    allowed_failed_logins = Integer(
+        config=True,
+        default=0,
+        help="""Configures the number of failed attempts a user can have
+                before being blocked."""
+    )
+    seconds_before_next_try = Integer(
+        config=True,
+        default=600,
+        help="""Configures the number of seconds a user has to wait
+                after being blocked. Default is 600."""
+    )
 
     def __init__(self, add_new_table=True, *args, **kwargs):
         super().__init__(*args, **kwargs)
 
+        self.login_attempts = dict()
         if add_new_table:
             self.add_new_table()
 
@@ -38,13 +52,57 @@ class NativeAuthenticator(Authenticator):
         if 'users_info' not in inspector.get_table_names():
             UserInfo.__table__.create(self.db.bind)
 
+    def add_login_attempt(self, username):
+        if not self.login_attempts.get(username):
+            self.login_attempts[username] = {'count': 1,
+                                             'time': datetime.now()}
+        else:
+            self.login_attempts[username]['count'] += 1
+            self.login_attempts[username]['time'] = datetime.now()
+
+    def can_try_to_login_again(self, username):
+        login_attempts = self.login_attempts.get(username)
+        if not login_attempts:
+            return True
+
+        time_last_attempt = datetime.now() - login_attempts['time']
+        if time_last_attempt.seconds > self.seconds_before_next_try:
+            return True
+
+        return False
+
+    def is_blocked(self, username):
+        logins = self.login_attempts.get(username)
+
+        if not logins or logins['count'] < self.allowed_failed_logins:
+            return False
+
+        if self.can_try_to_login_again(username):
+            return False
+        return True
+
+    def successful_login(self, username):
+        if self.login_attempts.get(username):
+            self.login_attempts.pop(username)
+
     @gen.coroutine
     def authenticate(self, handler, data):
-        user = UserInfo.find(self.db, data['username'])
+        username = data['username']
+        password = data['password']
+
+        user = UserInfo.find(self.db, username)
         if not user:
             return
-        if user.is_authorized and user.is_valid_password(data['password']):
-            return data['username']
+
+        if self.allowed_failed_logins:
+            if self.is_blocked(username):
+                return
+
+        if user.is_authorized and user.is_valid_password(password):
+            self.successful_login(username)
+            return username
+
+        self.add_login_attempt(username)
 
     def is_password_common(self, password):
         common_credentials_file = os.path.join(


Test patch:
diff --git a/nativeauthenticator/tests/test_authenticator.py b/nativeauthenticator/tests/test_authenticator.py
index 0c025ed..f3b34e0 100644
--- a/nativeauthenticator/tests/test_authenticator.py
+++ b/nativeauthenticator/tests/test_authenticator.py
@@ -1,4 +1,5 @@
 import pytest
+import time
 from jupyterhub.tests.mocking import MockHub
 
 from nativeauthenticator import NativeAuthenticator
@@ -72,3 +73,54 @@ async def test_handlers(app):
     handlers = auth.get_handlers(app)
     assert handlers[1][0] == '/signup'
     assert handlers[2][0] == '/authorize'
+
+
+async def test_add_new_attempt_of_login(tmpcwd, app):
+    auth = NativeAuthenticator(db=app.db)
+
+    assert not auth.login_attempts
+    auth.add_login_attempt('username')
+    assert auth.login_attempts['username']['count'] == 1
+    auth.add_login_attempt('username')
+    assert auth.login_attempts['username']['count'] == 2
+
+
+async def test_authentication_login_count(tmpcwd, app):
+    auth = NativeAuthenticator(db=app.db)
+    infos = {'username': 'johnsnow', 'password': 'password'}
+    wrong_infos = {'username': 'johnsnow', 'password': 'wrong_password'}
+    auth.get_or_create_user(infos['username'], infos['password'])
+    UserInfo.change_authorization(app.db, 'johnsnow')
+
+    assert not auth.login_attempts
+
+    await auth.authenticate(app, wrong_infos)
+    assert auth.login_attempts['johnsnow']['count'] == 1
+
+    await auth.authenticate(app, wrong_infos)
+    assert auth.login_attempts['johnsnow']['count'] == 2
+
+    await auth.authenticate(app, infos)
+    assert not auth.login_attempts.get('johnsnow')
+
+
+async def test_authentication_with_exceed_atempts_of_login(tmpcwd, app):
+    auth = NativeAuthenticator(db=app.db)
+    auth.allowed_failed_logins = 3
+    auth.secs_before_next_try = 10
+
+    infos = {'username': 'John Snow', 'password': 'wrongpassword'}
+    auth.get_or_create_user(infos['username'], 'password')
+    UserInfo.change_authorization(app.db, 'John Snow')
+
+    for i in range(3):
+        response = await auth.authenticate(app, infos)
+        assert not response
+
+    infos['password'] = 'password'
+    response = await auth.authenticate(app, infos)
+    assert not response
+
+    time.sleep(12)
+    response = await auth.authenticate(app, infos)
+    assert response