In my django application, user can access login/signup pages through URL even after logged-in. How to prevent them from accessing these pages?
urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'account'
urlpatterns = [
path('signup/', views.register, name='register'),
path('', auth_views.LoginView.as_view(), name='login'),
]
Though I can write if-else statement for checking authenticated users in views.py, but I haven't used any function for login in views.py. I am using django's default login sysyem and an authentication.py page for custom login (Authentication using an e-mail address).
authentication.py
from django.contrib.auth.models import User
class EmailAuthBackend(object):
"""
Authenticate using an e-mail address.
"""
def authenticate(self, request, username=None, password=None):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
return None
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Please suggest me an efficient way of redirecting already authenticated users to the home page whenever they try to access login or signup pages through typing its URL on the browser.
You can redirect users by modifying your urls.py file like below:
This will redirect already authenticated users from the login page. For the signup you will have to customize your register function add an if user is authenticated check.