12
votes

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.

2

2 Answers

17
votes

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.

3
votes

You can use this decorator as well.

def login_excluded(redirect_to):
    """ This decorator kicks authenticated users out of a view """ 
    def _method_wrapper(view_method):
        def _arguments_wrapper(request, *args, **kwargs):
            if request.user.is_authenticated:
                return redirect(redirect_to) 
            return view_method(request, *args, **kwargs)
        return _arguments_wrapper
    return _method_wrapper

Then call it in your views.py.

@login_excluded('app:redirect_to_view')
def someview(request):
    # ...