[英]logged out users are accessing views which logged in users can only access in django
I am quite new to Django and came across this error. 我对Django很陌生,并且遇到了此错误。 When ever I input a url directly ( '/accounts/admin2@outlook.com/'), django shows the user the view which only logged in users can see.
每当我直接输入网址('/accounts/admin2@outlook.com/')时,django就会向用户显示仅登录用户才能看到的视图。 I am using LoginRequiredMixin but it is not helping.
我正在使用LoginRequiredMixin,但没有帮助。
My view file is : ` 我的查看文件是:
from django.shortcuts import render,redirect
from django.views.generic import View
from .forms import UserCreationForm,SignInForm
from django.contrib.auth import login,logout,get_backends,authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.decorators import method_decorator
from .backend import ClientAuthBackend
from .models import MyUser
class UserHomeView(LoginRequiredMixin,View):
def get(self,request,email):
print(request.user.is_authenticated())
return render(request,'user_home_view.html',{'title':'Home','user':MyUser.objects.get(email=email)})
class SignOutView(View):
def get(self,request):
logout(request)
return redirect(to='/accounts/signin/')
class SignInView(View):
def get(self,request):
return render(request,'log_in.html',{'title':'Sign In','form':SignInForm()})
def post(self,request):
form = SignInForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(username=email,password=password)
if user is not None:
login(request,user)
return redirect(to='/accounts/' + str(email) + '/')
else:
form.add_error(None,"Couldn't authenticate your credentials !")
return render(request,'log_in.html',{'title':'Sign In','form':form})
else:
return render(request, 'log_in.html', {'title': 'Sign In', 'form': form})
class SignUpView(View):
def get(self,request):
return render(request,'sign_up.html',{'title':'Sign Up','form':UserCreationForm()})
def post(self,request):
form = UserCreationForm(request.POST)
try:
if form.is_valid():
user = MyUser.objects.create_user(email=form.cleaned_data['email'],date_of_birth=
form.cleaned_data['date_of_birth'],first_name=form.cleaned_data['first_name'],last_name=
form.cleaned_data['last_name'],password=form.clean_password2())
return redirect(to='/accounts/signin')
else:
return render(request,'sign_up.html',{'title':'Sign Up','form':form})
except ValueError:
form.add_error(None,"Passwords don't match !!!")
return render(request, 'sign_up.html', {'title': 'Sign Up', 'form': form})
` `
And that print statement in userhomeview also returns True each time a not logged in user accesses the url directly. 每当未登录的用户直接访问url时,userhomeview中的print语句也会返回True。 My url file is : `
我的网址文件是:
from django.conf.urls import url,include
from django.contrib import admin
from .views import SignUpView,SignInView,SignOutView,UserHomeView
urlpatterns = [
url(r'^signup/$',SignUpView.as_view()),
url(r'^signin/$',SignInView.as_view()),
url(r'^signout/$',SignOutView.as_view()),
url(r'^(?P<email>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)/',UserHomeView.as_view()),
]
` `
My settings file is : ` 我的设置文件是:
"""
Django settings for django_3 project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ac=6)v&jf(90%!op*$ttf29+qw_51n+(5#(jas&f&*(!=q310u'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
STATIC_URL = '/static/'
STATIC_ROOT = '/Users/waqarahmed/Desktop/Python Projects/learning_django/django_3/assets'
STATICFILES_DIRS = (
os.path.join(
BASE_DIR,'static',
),
)
AUTH_USER_MODEL = 'users.MyUser'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend','users.backend.ClientAuthBackend')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_3.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_3.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
My custom backend file is :
from .models import MyUser
from django.contrib.auth.backends import ModelBackend
class ClientAuthBackend(ModelBackend):
def authenticate(self,username=None,password=None):
try:
user = MyUser.objects.get(email=username)
if user.check_password(password):
return user
else:
return None
except MyUser.DoesNotExist:
return None
def get_user(self,email):
try:
user = MyUser.objects.get(email=email)
return user
except MyUser.DoesNotExist:
return None
` `
And my model file is : ` 我的模型文件是:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager,AbstractBaseUser
)
import time
from django.utils.dateparse import parse_date
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, first_name, last_name, password=None):
if not email:
raise ValueError('User must have an email id !')
email = str(email).lower()
date_of_birth = str(date_of_birth)
user = self.model(
email = self.normalize_email(email=email),
date_of_birth = parse_date(date_of_birth),
first_name = first_name,
last_name = last_name,
join_date = time.strftime('%Y-%m-%d'),
)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, date_of_birth, first_name, last_name, password=None):
if not email:
raise ValueError('User must have an email id !')
user = self.model(
email = self.normalize_email(email=email),
date_of_birth = date_of_birth,
first_name = first_name,
last_name = last_name,
join_date = time.strftime('%Y-%m-%d'),
)
user.is_admin = True
user.set_password(password)
user.save()
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(verbose_name='email address',max_length=255,unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
join_date = models.DateField(auto_now_add=True)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name','last_name','date_of_birth']
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
` `
Please correct following things first. 请先更正以下内容。
self
. self
使用request对象。 self.request.user.is_authenticated()
(It will return the what request does have) self.request.user.is_authenticated()
检查auth的使用(它将返回请求的内容) django.contrib.auth.middleware.AuthenticationMiddleware
django.contrib.auth.middleware.RemoteUserMiddleware
(add thes two in settings installed_apps) with following decorator from django.contrib.auth.decorators import login_required
. django.contrib.auth.middleware.AuthenticationMiddleware
django.contrib.auth.middleware.RemoteUserMiddleware
(添加在设置INSTALLED_APPS THES二)与from django.contrib.auth.decorators import login_required
以下装饰器from django.contrib.auth.decorators import login_required
。 Add @login_required
above the view. @login_required
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.