Spaces:
Runtime error
Runtime error
Download apps/auth/views.py from junaidte14/django-admin-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 3.14 kB
-
https://huggingface.co/spaces/junaidte14/django-admin-dashboard/resolve/main/apps/auth/views.py
- Command line
-
hf download hf://spaces/junaidte14/django-admin-dashboard/apps/auth/views.py
-
curl -L -o views.py https://huggingface.co/spaces/junaidte14/django-admin-dashboard/resolve/main/apps/auth/views.py
3.14 kB
| """ | |
| Authentication views | |
| """ | |
| import logging | |
| import requests | |
| from django.conf import settings | |
| from django.shortcuts import render, redirect | |
| from django.contrib import messages | |
| from django.views.decorators.http import require_http_methods | |
| logger = logging.getLogger(__name__) | |
| def login_view(request): | |
| if request.method == "POST": | |
| username = request.POST.get("username") | |
| password = request.POST.get("password") | |
| try: | |
| url = f"{settings.FASTAPI_BASE_URL}/auth/login" | |
| payload = { | |
| "username": username, | |
| "password": password, | |
| } | |
| res = requests.post( | |
| url, | |
| json={ | |
| "username": username, | |
| "password": password, | |
| }, | |
| timeout=settings.FASTAPI_TIMEOUT, | |
| ) | |
| # Try parsing JSON safely | |
| try: | |
| response_data = res.json() | |
| except Exception: | |
| response_data = None | |
| if res.status_code != 200: | |
| error_message = "Authentication failed" | |
| if response_data: | |
| error_message = ( | |
| response_data.get("detail") | |
| or response_data.get("message") | |
| or error_message | |
| ) | |
| return render( | |
| request, | |
| "auth/login.html", | |
| {"error": error_message} | |
| ) | |
| token = response_data.get("access_token") | |
| if not token: | |
| return render( | |
| request, | |
| "auth/login.html", | |
| {"error": "Authentication token missing"} | |
| ) | |
| response = redirect("dashboard:home") | |
| COOKIES_LIFESPAN = 24 * 60 * 60 # 86400 seconds (1 day) | |
| response.set_cookie( | |
| "access_token", | |
| token, | |
| max_age=COOKIES_LIFESPAN, | |
| httponly=True, | |
| secure=False, | |
| samesite="Lax", | |
| ) | |
| return response | |
| except requests.exceptions.Timeout: | |
| return render( | |
| request, | |
| "auth/login.html", | |
| {"error": "Authentication server timeout"} | |
| ) | |
| except requests.exceptions.ConnectionError: | |
| return render( | |
| request, | |
| "auth/login.html", | |
| {"error": "Authentication server unavailable"} | |
| ) | |
| except Exception as e: | |
| return render( | |
| request, | |
| "auth/login.html", | |
| {"error": str(e)} | |
| ) | |
| return render(request, "auth/login.html") | |
| def logout_view(request): | |
| response = redirect("auth:login") | |
| response.delete_cookie("access_token") | |
| messages.success( | |
| request, | |
| "You have been logged out successfully." | |
| ) | |
| return response |