76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
# Copyright © 2022 Aravinth Manivannan <realaravinth@batsense.net>
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU Affero General Public License as
|
|
# published by the Free Software Foundation, either version 3 of the
|
|
# License, or (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
from django.shortcuts import render, redirect
|
|
from django.contrib.auth import authenticate, login, logout
|
|
from django.contrib.auth import get_user_model
|
|
from django.contrib.auth.decorators import login_required
|
|
from django.http import HttpResponse
|
|
from django.views.decorators.csrf import csrf_protect
|
|
from django.urls import reverse
|
|
|
|
|
|
@csrf_protect
|
|
def login_view(request):
|
|
if request.method == "GET":
|
|
ctx = {}
|
|
if "next" in request.GET:
|
|
ctx["next"] = request.GET["next"]
|
|
return render(request, "accounts/auth/login.html", ctx)
|
|
|
|
login_cred = request.POST["login"]
|
|
user = None
|
|
|
|
if "@" in login_cred:
|
|
user = authenticate(
|
|
email=login_cred,
|
|
password=request.POST["password"],
|
|
)
|
|
else:
|
|
user = authenticate(
|
|
username=login_cred,
|
|
password=request.POST["password"],
|
|
)
|
|
|
|
if user is not None:
|
|
login(request, user)
|
|
if "next" in request.POST:
|
|
next_url = request.POST["next"]
|
|
if next_url:
|
|
return redirect(next_url)
|
|
return redirect(reverse("accounts.protected"))
|
|
|
|
ctx = {
|
|
"error": {
|
|
"title": "Login Failed",
|
|
"reason": "Username or passwrod is incorrect, please try again.",
|
|
}
|
|
}
|
|
return render(request, "accounts/auth/login.html", status=401, context=ctx)
|
|
|
|
|
|
@login_required
|
|
def protected_view(request):
|
|
return render(request, "accounts/protected.html")
|
|
|
|
|
|
@login_required
|
|
def logout_view(request):
|
|
logout(request)
|
|
return redirect(reverse("accounts.login"))
|
|
|
|
|
|
def public_view(request):
|
|
return render(request, "accounts/public.html")
|