# Path: apps/admin/fail_login/models.py
# class FailLogin(models.Model):
#     """ Protect admin login from brute-force attack
#     """
#     user = models.ForeignKey(User, editable = False, verbose_name=_('User'))
#     created_at = models.DateTimeField(auto_now_add=True)#(default=datetime.datetime.now())#
# 
#     def __unicode__(self):
#         return self.user
# 
#     class Meta:
#         db_table = 'FailLogin'
#         verbose_name = _('Fail login')
#         verbose_name_plural = _('Fail logins')


import datetime
import logging
from datetime import timedelta
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import PermissionDenied
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.core.mail import send_mail
from smtplib import SMTPRecipientsRefused
from apps.admin.fail_login.models import FailLogin
        # fail_login injection to django authenticate
        count_fl = self.login_failed(username)
        if count_fl < settings.MYSMILE_ADMIN_FAIL_LOGIN_ATTEMPTS:
            # code below is django authenticate(self, username=None, password=None, **kwargs): ----
            UserModel = get_user_model()
            if username is None:
                username = kwargs.get(UserModel.USERNAME_FIELD)
            try:
                user = UserModel._default_manager.get_by_natural_key(username)
                if user.check_password(password):
                    return user
            except UserModel.DoesNotExist:
                # Run the default password hasher once to reduce the timing
                # difference between an existing and a non-existing user (#20760).
                UserModel().set_password(password)
            # -------------------------------------------------------------------------------------
        else:
            raise PermissionDenied  # 403 error

    def login_failed(self, username):
        try:
            count_fl = 1 # TODO exception in User.objects.get cause returning unregistered variable count_fl
            user = User.objects.get(username=username)

            # delete records, older then MYSMILE_ADMIN_FAIL_LOGIN_TIMEOUT
            time = datetime.datetime.now() - timedelta(minutes=settings.MYSMILE_ADMIN_FAIL_LOGIN_TIMEOUT)
            FailLogin.objects.filter(created_at__lte=time).delete()

            count_fl = FailLogin.objects.filter(user=user).count()
            if count_fl < settings.MYSMILE_ADMIN_FAIL_LOGIN_ATTEMPTS:

# Path: apps/admin/fail_login/models.py
# class FailLogin(models.Model):
#     """ Protect admin login from brute-force attack
#     """
#     user = models.ForeignKey(User, editable = False, verbose_name=_('User'))
#     created_at = models.DateTimeField(auto_now_add=True)#(default=datetime.datetime.now())#
# 
#     def __unicode__(self):
#         return self.user
# 
#     class Meta:
#         db_table = 'FailLogin'
#         verbose_name = _('Fail login')
#         verbose_name_plural = _('Fail logins')


# Path: apps/admin/fail_login/backends.py
import datetime
import logging
from datetime import timedelta
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import PermissionDenied
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.core.mail import send_mail
from smtplib import SMTPRecipientsRefused
from apps.admin.fail_login.models import FailLogin

        # fail_login injection to django authenticate
        count_fl = self.login_failed(username)
        if count_fl < settings.MYSMILE_ADMIN_FAIL_LOGIN_ATTEMPTS:
            # code below is django authenticate(self, username=None, password=None, **kwargs): ----
            UserModel = get_user_model()
            if username is None:
                username = kwargs.get(UserModel.USERNAME_FIELD)
            try:
                user = UserModel._default_manager.get_by_natural_key(username)
                if user.check_password(password):
                    return user
            except UserModel.DoesNotExist:
                # Run the default password hasher once to reduce the timing
                # difference between an existing and a non-existing user (#20760).
                UserModel().set_password(password)
            # -------------------------------------------------------------------------------------
        else:
            raise PermissionDenied  # 403 error

    def login_failed(self, username):
        try:
            count_fl = 1 # TODO exception in User.objects.get cause returning unregistered variable count_fl
            user = User.objects.get(username=username)

            # delete records, older then MYSMILE_ADMIN_FAIL_LOGIN_TIMEOUT
            time = datetime.datetime.now() - timedelta(minutes=settings.MYSMILE_ADMIN_FAIL_LOGIN_TIMEOUT)
            FailLogin.objects.filter(created_at__lte=time).delete()

            count_fl = FailLogin.objects.filter(user=user).count()
            if count_fl < settings.MYSMILE_ADMIN_FAIL_LOGIN_ATTEMPTS:

                FailLogin(user=user).save()