authenticate.py 708 B

12345678910111213141516171819
  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. #1,先判断username是否是手机号
  8. if re.match(r'^1[3-9]\d{9}$',username):
  9. user = User.objects.get(mobile=username)
  10. else:
  11. #2,然后在通过用户名查询,用户
  12. user = User.objects.get(username=username)
  13. except User.DoesNotExist:
  14. return None
  15. else:
  16. #3,校验密码
  17. if not user.check_password(password): return None
  18. return user