dashboard/accounts/views.py

76 lines
2.4 KiB
Python
Raw Normal View History

# 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/>.
2022-06-10 11:52:54 +00:00
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model
2022-06-10 11:52:54 +00:00
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
2022-06-10 11:52:54 +00:00
@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"],
)
2022-06-10 11:52:54 +00:00
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"))
2022-06-10 11:52:54 +00:00
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)
2022-06-10 11:52:54 +00:00
2022-06-10 11:52:54 +00:00
@login_required
def protected_view(request):
return render(request, "accounts/protected.html")
2022-06-10 11:52:54 +00:00
@login_required
def logout_view(request):
logout(request)
return redirect(reverse("accounts.login"))
2022-06-10 11:52:54 +00:00
def public_view(request):
return render(request, "accounts/public.html")