summaryrefslogtreecommitdiffstats
path: root/core/views/auth.py
blob: 689e6456c5eea2c342c2c84b3621781f1635721a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import forms as auth_forms
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.utils.http import url_has_allowed_host_and_scheme

"""This enforces the login requirement for non-public pages using 
the decorator mechanism. 
https://www.fullstackpython.com/django-contrib-auth-decorators-login-required-examples.html
"""


class login_required_if_public(object):
    def __init__(self, f):
        if settings.PUBLIC_SITE:
            self.f = login_required(f)
        else:
            self.f = f

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)
 
"""The login and logout functions.

TO DO : check that we don't have another set of these active somewhere
"""

############################
# Authentication Functions #
############################


def expologout(request):
    login_form = auth_forms.AuthenticationForm()
    logout(request)

    return render(request, "login/logout.html", {"form": login_form})


def expologin(request):
    # GET
    if not request.method == "POST":
        if (not request.user.is_authenticated) or (not request.user.is_active):
            return render(request, "login/index.html", {})
        else:
            # going to login page when you are already logged in
            from django.contrib.admin.templatetags import log
            return render(request, "login/tasks.html", {})

    # POST
    username = request.POST["username"]
    password = request.POST["password"]

    user = authenticate(username=username, password=password)
    if user is None:
        return render(request, "login/index.html", {"invalid": True, "username": username})
    if not user.is_active:
        return render(request, "login/enable.html", {"login_state": "notenabled"})

    try:
        login(request, user)
        # Should do the ?next= stuff here..
        return redirect_after_login(request)
    except:
        return render(request, "errors/generic.html", {})


def redirect_after_login(request):
    nxt = request.GET.get("next", None)
    if nxt is None:
        return redirect(settings.LOGIN_REDIRECT_URL)
    elif not url_has_allowed_host_and_scheme(url=nxt, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
        return redirect(settings.LOGIN_REDIRECT_URL)
    else:
        return redirect(nxt)