我正在使用django 2.1.7和python 3.6.5版本,使用'AbstractUser'扩展了django用户模型,并覆盖了django authenticate方法。在登录之前一切似乎都工作正常,但是当页面重定向到home request.user变为null时。
我尝试呈现而不是重定向,这似乎可行,但是当我在其他选项卡中打开同一页面或刷新页面时,出现403禁止错误(CSRF验证失败。请求中止。) 尝试了以下设置,但似乎仍然无法正常工作 CSRF_COOKIE_SECURE =假 SESSION_COOKIE_SECURE = False
settings.py
LOGIN_URL = '/'
LOGIN_REDIRECT_URL = 'home'
AUTH_USER_MODEL = 'hygie_portal.CustomUser'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hygie_portal',
'django_assets',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
AUTHENTICATION_BACKENDS = (
'hygie_portal.mybackend.MyBackEnd',
)
models.py
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
is_admin = models.IntegerField(blank=True, null=True)
role = models.CharField(max_length=256, blank=True, null=True)
def set_is_admin(self, is_admin):
self.is_admin = is_admin
def set_role(self, role):
self.last_update = datetime.now()
self.role = role
forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.forms import TextInput,EmailInput,PasswordInput
CustomUser = get_user_model()
class LoginForm(forms.Form):
"""Login form."""
username = forms.CharField(label='Username', max_length=100)
password = forms.CharField( widget=forms.PasswordInput())
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email')
admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
CustomUser = get_user_model()
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['username',]
admin.site.register(CustomUser, CustomUserAdmin)
urls.py
app_name = "hygie_portal"
urlpatterns = [
path("", views.login_request, name='login'),
path(r'login/', RedirectView.as_view(url='/login/')),
path('home/', views.home, name='home'),
]
view.py
from django.contrib.auth import get_user_model
CustomUser = get_user_model()
@csrf_protect
def login_request(request):
if request.user.is_authenticated:
return render(request, 'users/home_public.html')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user_info = MyBackEnd.authenticate(encode(username), encode(password), request=request)
if not user_info:
messages.error(request,'Invalid username or password. Please try again.')
return redirect('hygie_portal:login')
is_admin = True if 'manager' in user_info['role'] else False
try:
user_profile = CustomUser.objects.get(username=username)
except:
user_profile = ''
if not user_profile:
if 'name' in user_info:
try:
fname = user_info['name'].split()[0]
except IndexError:
fname = ''
try:
sname = user_info['name'].split()[1]
except IndexError:
sname = ''
else:
fname, sname = '', ''
user_profile = CustomUser(username=username, email=user_info['email'], first_name=fname, last_name=sname, role=user_info['role'])
user_profile.save()
try:
user_profile.set_is_admin(is_admin)
user_profile.set_role(user_info['role'])
user_profile.save()
except Exception as e:
logger.error('Exception updating user****' % e)
login(request, user_profile, backend='hygie_portal.mybackend.MyBackEnd')
#After login request.user.is_authenticated returns true
#return redirect('hygie_portal:home') #when redirected to home request.user.is_authenticated returns False
return render(request, 'users/home_public.html') #works fine, but throws 403 error when page is refreshed or url accessed in different tab
form = LoginForm()
if form.errors:
messages.error(form.errors, 'danger')
flash(form.errors, 'danger')
# default to login page if not authenticated or no form submit.
return render(request, 'public/login.html',{'form': form})
def home(request):
if request.user.is_authenticated:
return render(request, 'users/home_public.html')
else:
return redirect('hygie_portal:login')
mybackend.py
class MyBackEnd(object):
def authenticate(username, password, request=None):
bind_attr = settings.AD_BIND_ATTR
user_dn = settings.AD_DN
login_attr = '(%s=%s)' % (settings.AD_LOGIN_ATTR, username)
data = get_bind_user(username) #returns the user info with role permissions
if len(data) == 0:
return None
if 'mail' not in data:
logger.warning('No email found in AD, adding dummy email')
info['name'] = data['cn'][0] if 'cn' in data else None
info['email'] = data['mail'][0] if 'mail' in data else 'nomail@xx.com'
try:
info['phone'] = data['telephoneNumber'][0]
except KeyError:
info['phone'] = 'Not Available'
try:
info['role'] = data['role']
except KeyError:
info['role'] = False
conn = ldap.initialize(settings.AD_URL)
conn.set_option(ldap.OPT_REFERRALS,0)
conn.set_option(ldap.OPT_PROTOCOL_VERSION, settings.LDAP_PROTOCOL_VERSION)
try:
conn.bind_s(data[bind_attr][0].decode(), password)
conn.search(user_dn, ldap.SCOPE_SUBTREE, login_attr, None)
conn.result()
return info
except (ldap.INVALID_CREDENTIALS, ldap.OPERATIONS_ERROR):
logger.info('Invalid credentials for :%s' % username)
return None
def get_user(self, username):
try:
return CustomUser.objects.get(username=username)
except CustomUser.DoesNotExist:
return None
我在Django文档中看到过login()将保存整个会话的用户ID。我希望用户登录后可以通过不同的选项卡访问会话。
我尝试使用request.session检查会话详细信息,但是我不知道如何在我的代码中使用它。
答案 0 :(得分:1)
我认为问题在于您的get_user
方法。它应该接受用户ID而不是用户名,并使用该ID查找模型实例。
def get_user(self, user_id):
try:
return CustomUser.objects.get(pk=user_id)
except CustomUser.DoesNotExist:
return None
答案 1 :(得分:0)
您是否在'django.contrib.sessions'
的{{1}}中添加了INSTALLED_APPS
?
您应该考虑使用Django Sessions。
默认情况下,Django将会话信息保存在数据库(django_session表或集合)中,但是您可以将引擎配置为使用其他方式存储信息,例如:在文件或缓存中。启用会话后,每个请求(Django中任何视图的第一个参数)都具有会话(dict)属性。
您可以使用会话字典来手动存储settings.py
信息,例如
User
答案 2 :(得分:0)
Django使用AuthenticationMiddleware
将用户对象附加到httpRequest
对象。
login()
用户时,它将保存users.id
和对会话的backend
引用:
login(request, user, backend='your.auth.backend')
这允许AuthenticationMiddleware
以后使用相同的后端来提取user
对象并将其附加到httpRequest
。
它是通过调用get_user()
方法并传递user_id
作为参数来实现的。
重要的是,不要覆盖get_user()
以接受主键或用户ID以外的任何内容
更多信息可以在这里找到
https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#writing-an-authentication-backend][2]