authenticate.py 764 B

123456789101112131415161718192021
  1. from django.contrib.auth.backends import ModelBackend
  2. import re
  3. from users.models import User
  4. class MyAuthenticateBackend(ModelBackend):
  5. def authenticate(self, request, username=None, password=None, **kwargs):
  6. try:
  7. print(username)
  8. print(password)
  9. #1,先判断username是否是手机号
  10. if re.match(r'^1[3-9]\d{9}$',username):
  11. user = User.objects.get(mobile=username)
  12. else:
  13. #2,然后在通过用户名查询,用户
  14. user = User.objects.get(username=username)
  15. except User.DoesNotExist:
  16. return None
  17. else:
  18. #3,校验密码
  19. if not user.check_password(password): return None
  20. return user