我是django的初学者,我想使用自定义用户模型构建身份验证。 我已提出问题Here。有人建议我继承用户模型
我创建了自定义用户模型。由于所有密码都是使用bcrypt函数存储的,所以我创建了自己的自定义身份验证。现在,每次我登录时,即使我的密码是正确的,我也不会得到任何信息。我想知道我错过了什么
models.py
class AdminUserManager(BaseUserManager):
def create_user(self, username, password):
if username is None or password is None:
raise ValueError("Username and Password is Required")
else:
user = self.model(
username = username,
password = str(bcrypt.hashpw(password.encode('utf8'),bcrypt.gensalt()),'utf-8')
)
user.save(using=self.db)
return user
class AdminUsers(AbstractBaseUser):
username=models.CharField(max_length=50,unique=True)
firstname=models.CharField(max_length=50)
department=models.CharField(max_length=50)
mail=models.CharField(max_length=50)
id=models.IntegerField(primary_key=True)
password=models.CharField(max_length=200)
# some more field
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['mail']
objects = AdminUserManager()
class Meta:
db_table="admin_users"
def __str__(self):
return self.username
backend.py
from .models import AdminUsers
import bcrypt
class CustomAuthentication(object):
def authenticate(self,username,password):
if username is not None and password is not None:
user = AdminUsers.objects.get(username=username)
hashed_password = user.password
is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
if is_check == True:
return user
else:
return None
else:
return None
def get_user(self,id):
user = AdminUsers.objects.get(id=id)
if user is not None:
return user
else:
return None
views.py
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username is not None and password is not None:
is_check = authenticate(username=username,password=password)
# user=AdminUsers.objects.get(username=username)
# print(user.username,user.password)
# hashed_password = user.password
# is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
print(is_check)
if is_check==True:
return render(request,'Layouts/nav-side-bar.html',context={"User":is_check})
else:
return render(request,'AdminUsers/login.html')
return render(request,'AdminUsers/login.html')
我在设置中添加了AUTHENTICATION_BACKENDS
和 AUTH_USER_MODEL
***编辑1***
为了检查我的CustomAuthentication是否正常工作,在Authentication函数中,我对一些部分进行了注释,并在不检查密码的情况下返回用户。我还是一无所获。 据我所知,我的customauthentication没有用于身份验证
def authenticate(self,username,password):
if username is not None and password is not None:
user = AdminUsers.objects.get(username=username)
return user
# hashed_password = user.password
# is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
# if is_check == True:
# return user
# else:
# return None
else:
return None
我犯了个错误。 在创建
CustomAuthentication
时,我必须继承Documentation中给出的BaseBackend。 所以backend.py应该是这样的相关问题 更多 >
编程相关推荐