Implement login logs

This commit is contained in:
Kumi 2020-05-23 15:30:21 +02:00
parent ee4999a0ba
commit da416ca08a
5 changed files with 35 additions and 12 deletions

View file

@ -1,7 +1,10 @@
from core.helpers.mail import get_template
from core.helpers.urls import relative_to_absolute as reltoabs
from core.models.auth import LoginLog
from core.helpers.request import get_client_ip
from django.urls import reverse
from django.contrib import messages
from dbsettings.functions import getValue
@ -10,5 +13,10 @@ def generate_pwreset_mail(user, token):
template = get_template("backend/auth/pwreset", first_name=user.first_name, link=link, sitename=getValue("core.title", "Expephalon"))
return template
def login_fail(user):
pass
def login_fail(request, user=None, message=None):
LoginLog.objects.create(user=user, ip=get_client_ip(request), success=False)
if message:
messages.error(request, message)
def login_success(request, user):
LoginLog.objects.create(user=user, ip=get_client_ip(request), success=True)

7
core/helpers/request.py Normal file
View file

@ -0,0 +1,7 @@
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
return x_forwarded_for.split(',')[0]
else:
return request.META.get('REMOTE_ADDR')

View file

@ -1,4 +1,4 @@
from django.db.models import Model, ForeignKey, CharField, DateTimeField, UUIDField, CASCADE, BooleanField, IPAddressField
from django.db.models import Model, ForeignKey, CharField, DateTimeField, UUIDField, CASCADE, SET_NULL, BooleanField, GenericIPAddressField
from django.contrib.auth import get_user_model
from uuid import uuid4
@ -14,7 +14,7 @@ class PWResetToken(Model):
creation = DateTimeField(auto_now_add=True)
class LoginLog(Model):
user = ForeignKey(get_user_model(), CASCADE)
ip = IPAddressField()
user = ForeignKey(get_user_model(), SET_NULL, null=True)
ip = GenericIPAddressField()
success = BooleanField()
timestamp = DateTimeField(auto_now_add=True)

View file

@ -19,7 +19,7 @@ for module in settings.EXPEPHALON_MODULES + [""]:
template_format = str(template).rsplit(".")[-1].lower()
if not template_name in templates.keys():
templates[template_name] = dict()
if template_format in templates[template_name].keys():
if template_format in templates[template_name].keys() and not templates[template_name][template_format] == template:
logger.warning("Mail Template %s, that was seen at %s, was also found at %s. Using latter.",
template_name, templates[template_name][template_format], str(template))
templates[template_name][template_format] = str(template)

View file

@ -10,7 +10,7 @@ from core.forms import LoginForm, OTPSelectorForm, OTPVerificationForm, PWResetF
from core.models.auth import LoginSession, PWResetToken
from core.helpers.otp import get_user_otps, get_otp_choices, get_otp_by_name
from core.helpers.mail import simple_send_mail
from core.helpers.auth import generate_pwreset_mail
from core.helpers.auth import generate_pwreset_mail, login_fail, login_success
from dbsettings.functions import getValue
@ -28,6 +28,14 @@ class LoginView(FormView):
context["title"] = "Login"
return context
def form_invalid(self, form):
try:
user = get_user_model().objects.get(username=form.cleaned_data["email"])
except get_user_model().DoesNotExist:
user = None
login_fail(self.request, user, "The credentials you entered are invalid. Please try again.")
return super().form_invalid(form)
def form_valid(self, form):
user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
if user:
@ -38,8 +46,7 @@ class LoginView(FormView):
self.request.session["otpsession"] = str(session.uuid)
self.request.session["next"] = self.request.GET.get("next", "dashboard")
return redirect("otpselector")
messages.error(self.request, "The credentials you entered are invalid. Please try again.")
return super().form_invalid(form)
return self.form_invalid(form)
class OTPSelectorView(FormView):
template_name = f"{settings.EXPEPHALON_BACKEND}/auth/otp_selector.html"
@ -68,6 +75,7 @@ class OTPSelectorView(FormView):
def form_invalid(self, form):
self.clean_session()
messages.error("Something went wrong selecting the OTP provider. Please try again.")
return redirect("login")
def get_context_data(self, **kwargs):
@ -112,7 +120,9 @@ class OTPValidatorView(FormView):
return super().post(request, *args, **kwargs)
def form_invalid(self, form):
user, provider = self.validate_session(self.request)
self.clean_session()
login_fail(self.request, user, "Incorrect token entered. Please try again. If the issue persists, contact support to regain access to your account.")
return redirect("login")
def form_valid(self, form):
@ -122,9 +132,7 @@ class OTPValidatorView(FormView):
ret = redirect(self.request.session.get("next", "dashboard"))
self.clean_session()
return ret
self.clean_session()
messages.error(self.request, "Incorrect token entered. Please try again. If the issue persists, contact support to regain access to your account.")
return redirect("login")
return self.form_invalid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)