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.
The Django authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do.
Add Permissions to a Group YourClassName' . This way, you are telling Django to use our custom user model instead of the default one. The code below should go in your admin.py file so that you can see your user model. You will see that you can select various permissions and attach them to a particular group.
Check the Logged in User in Views in Django We can use request. user. is_authenticated to check if the user is logged in or not. If the user is logged in, it will return True .
You can redirect users by modifying your urls.py file like below:
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(redirect_authenticated_user=True), name='login'),
]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With