How to prevent user to access login page in django when already logged in?

天涯浪子 提交于 2020-01-02 07:25:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/55062157/how-to-prevent-user-to-access-login-page-in-django-when-already-logged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!