# coding: utf-8 from django.contrib.auth.base_user import BaseUserManager from django.core import exceptions from django.core.validators import EmailValidator from pingcap_sso.validators.phone import ( PhoneNumberValidator, normalize_phone_number, ) class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, password, **extra_fields): """ Creates and saves a User with the given username, email and password. """ if not username: raise ValueError('The given username must be set') user = self.model(username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, password, **extra_fields) def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, password, **extra_fields) def find_user(self, identifier): # Try the following steps one by one: phone -> email -> phone # TODO: optimize this flow try: phone = normalize_phone_number(identifier) PhoneNumberValidator()(phone) return self.get(phone=phone) except exceptions.ValidationError: try: EmailValidator()(identifier) return self.get(email=identifier) except exceptions.ValidationError: return self.get(username=identifier)