def test_manager_create_super(self): manager = UserManager() user = manager.create_superuser(email='*****@*****.**', name='test', last_name='test', password='******') assert user.is_admin
class User(AbstractBaseUser, UUIDModel, CreationModel, ModificationModel, PermissionsMixin): first_name = models.CharField(_("First name"), max_length=120, blank=True, help_text=_('First name of the user.')) last_name = models.CharField(_("Last name"), max_length=120, blank=True, help_text=_('Last name of the user.')) email = models.EmailField( _("Email"), unique=True, db_index=True, help_text=_('Email of the user. It is used to log in.')) is_staff = models.BooleanField( _('Staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.')) is_active = models.BooleanField( _('Active'), default=True, help_text=_( 'Designates whether this user should be treated as active. Unselect ' 'this instead of deleting accounts.')) date_joined = models.DateTimeField(_('Date joined'), default=timezone.now) language = models.CharField(_('Language'), max_length=15, choices=LANGUAGES, help_text=_('Language of the user.')) objects = UserManager() logs = Loggable() USERNAME_FIELD = 'email' # Field to identify the user. class Meta: verbose_name = _('user') verbose_name_plural = _('user') ordering = ['-date_joined'] app_label = 'user' def __str__(self) -> str: return str(self.email) def get_full_name(self) -> str: """ Returns the first_name plus the last_name, with a space in between. """ full_name = '{} {}'.format(self.first_name, self.last_name) return full_name.strip() def get_short_name(self) -> str: """ Returns the short name for the user. """ return self.first_name.strip()
class User(AbstractUser): username = None email = models.EmailField('email address', unique=True) is_company = models.BooleanField('company status', default=False) avatar = models.ImageField(upload_to=upload_to, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email
class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=25, unique=True) USERNAME_FIELD = 'username' objects = UserManager() class Meta: db_table = 'user' verbose_name = _('user') verbose_name_plural = _('users') def __str__(self): return self.username
class Manager(User): ''' Прокси модель менеджера ''' objects = UserManager(role='MN') def save(self, *args, **kwargs): self.role = 'MN' super().save(*args, **kwargs) class Meta: proxy = True verbose_name = 'Менеджер' verbose_name_plural = 'Менеджеры'
class CustomUser(AbstractUser): email = models.EmailField(max_length=70,unique=True) phone_number = models.IntegerField(verbose_name="Phone Number", unique=True, blank=True, null=True) gender = models.CharField(choices=GENDER_CHOICES, max_length=6, blank=True, null=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'username'] def __str__(self): return self.email class Meta: verbose_name_plural = "Users"
class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=35, blank=False, unique=True) password = models.CharField(_('password'), max_length=100, blank=False, null=False) is_staff = models.BooleanField( _('Staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_superuser = models.BooleanField( _('Admin status'), default=False, help_text=_('Designates that this user has all permissions without ' 'explicitly assigning them.'), ) is_active = models.BooleanField( 'active', default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting account.'), ) is_delete = models.BooleanField( 'delete', default=False, help_text= _('Delete the user account and keep the data in the database as a deleted user' ), ) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [username, password] objects = UserManager() class Meta: db_table = 'USER' verbose_name = _('user') verbose_name_plural = _('users') def __str__(self): return f"{self.username}"
class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name='email address', max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Meta: db_table = "login"
class User(AbstractUser): email = models.EmailField( _('Email'), unique=True, blank=False, null=False, error_messages={ 'unique': _("A user with that email address already exists."), }, ) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() def __str__(self): full_name = self.get_full_name() if full_name: return full_name if self.email: return self.email return self.username @property def created_at(self): return self.date_joined @property def has_telegram(self) -> bool: return self.contacts.filter(has_telegram=True).exists() @property def has_whatsapp(self) -> bool: return self.contacts.filter(has_whatsapp=True).exists() @property def phone_list(self) -> list: return self.contacts.filter(phone__isnull=False).values_list('phone', flat=True) @property def email_list(self) -> list: return self.contacts.filter(email__isnull=False).values_list('email', flat=True) class Meta: verbose_name = _("User") verbose_name_plural = _("Users") ordering = ('date_joined',)
class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email"), unique=True) username = models.CharField(_("username"), max_length=50, primary_key=True) data_joined = models.DateTimeField(_("data_joined"), auto_now_add=True) is_active = models.BooleanField(_("is_active"), default=True) is_staff = models.BooleanField(_("is_staff"), default=True) objects = UserManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = [ "email", ] class Meta: verbose_name = _("username") verbose_name_plural = _("usernames") def get_name(self): return self.username.strip()
class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, blank=False, null=False) username = models.CharField(max_length=15, blank=True, null=True, default='', unique=True) is_staff = models.BooleanField( _('Staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_superuser = models.BooleanField( _('Admin status'), default=False, help_text=_('Designates that this user has all permissions without ' 'explicitly assigning them.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting account.'), ) is_delete = models.BooleanField(_('delete'), default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: db_table = 'USER' verbose_name = _('user') verbose_name_plural = _('users') def __str__(self): return self.email.__str__() def get_username(self): return self.username.__str__()
class Client(User): ''' Прокси модель клиента ''' objects = UserManager(role='CL') def save(self, *args, **kwargs): self.role = 'CL' super().save(*args, **kwargs) def get_name(self): return self.clientProfile.name def __str__(self): return self.get_name() class Meta: proxy = True verbose_name = 'Клиенты' verbose_name_plural = 'Клиент'
class BlogUser(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # password = models.CharField(max_length=20) email = models.EmailField(unique=True) # first_blog = models.ForeignKey(Blog, null=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): """ Returns the short name for the user. """ return self.first_name def __str__(self): return "{} {} {}".format(self.first_name, self.last_name, self.email) def save(self, *args, **kwargs): self.email = self.username result = super(BlogUser, self).save(*args, **kwargs) # create new blog for each user from blog.models import Blog number_of_blogs = Blog.objects.filter(user=self).count() if number_of_blogs == 0: newBlog = Blog(user=self) newBlog.save() return result
class User(AbstractUser): """ Overrides the default Django user model. """ username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() class Meta: """ Override the table name. """ db_table = 'user_user' def __str__(self): return self.email
class User(AbstractBaseUser, PermissionsMixin, BaseMixin): username = models.CharField( _('username'), max_length=150, unique=True, ) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField( _('email address'), blank=True, unique=True, ) is_staff = models.BooleanField( _('staff status'), default=False, ) is_active = models.BooleanField( _('active'), default=True, ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) profile = models.ForeignKey(Profile, null=True, blank=True, related_name='profile', on_delete=models.CASCADE) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' class Meta: swappable = 'AUTH_USER_MODEL' def get_full_name(self): return '%s %s'.format(self.first_name, self.last_name).strip()
class User(AbstractUser): """ Модель пользователя """ username = models.CharField(_('username'), max_length=150, blank=True) email = models.EmailField('Адрес электронной почты', unique=True) first_name = models.CharField('Иия', max_length=32, blank=True) last_name = models.CharField('Фимилия', max_length=32, blank=True) middle_name = models.CharField('Отчество', max_length=32, blank=True) role = models.CharField('Роль', max_length=10, choices=UserRole.CHOICES, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def __str__(self): return self.email @property def comment_author_name(self) -> str: """ Автор комментария """ if self.first_name and self.last_name and self.middle_name: return f'{self.last_name} {self.first_name[:1].upper()}.{self.middle_name[:1].upper()}.' return 'Пользователь'
class User(AbstractBaseUser, PermissionsMixin): """ User database model. """ email = models.EmailField(unique=True, blank=False) username = models.CharField(unique=True, max_length=25, blank=False) created = models.DateTimeField(auto_now_add=True) is_email_confirmed = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: """ Meta. """ ordering = ('created', ) verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): """ Return the first name plus the last name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): """ Return the short name for the user. """ return self.username @classmethod def create_with_email(cls, email, username, password): """ Create a user with specified e-mail address and password. """ user = cls.objects.create_user(email=email, username=username, password=password) Profile.objects.create(user=user) @classmethod def does_exist_by_email(cls, email): """ Check if user exists by e-mail address. """ if cls.objects.filter(email=email).exists(): return True return False @classmethod def does_exist_by_username(cls, username): """ Check if user exists by username. """ if cls.objects.filter(username=username).exists(): return True return False @classmethod def verify_password(cls, email, password): """ Check if the user's password is equal to the encrypted user password. """ encrypted_user_password = cls.objects.get(email=email).password return check_password(password=password, encoded=encrypted_user_password) @classmethod def set_new_password(cls, email, password): """ Set new user password by specified e-mail. """ user = cls.objects.get(email=email) user.set_password(password) user.save() @classmethod def get(cls, username): """ Get user. """ user_as_dict = cls.objects.filter(username=username).values().first() del user_as_dict['password'] del user_as_dict['created'] return UserDto(**user_as_dict) @classmethod def delete_(cls, username): """ Delete user. """ cls.objects.filter(username=username).delete() @classmethod def set_new_email(cls, username, email): """ Set new user e-mail by specified username. """ user = cls.objects.get(username=username) user.email = email user.save() @classmethod def is_email_confirmed_(cls, user_identifier): """ Check if user email confirmed by identifier. """ email = EmailConfirmState.get_email(user_identifier=user_identifier) if cls.objects.get(email=email).is_email_confirmed: return True return False @classmethod def set_email_as_confirmed(cls, user_identifier): """ Set email as confirmed by identifier. """ email = EmailConfirmState.get_email(user_identifier=user_identifier) user_state = cls.objects.get(email=email) user_state.is_email_confirmed = True user_state.save()
class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=255, unique=True) name = models.CharField(verbose_name="First name", max_length=255) surname = models.CharField(verbose_name="Last name", max_length=255, blank=True, null=True) email_verified = models.BooleanField(default=False) verify_key = models.CharField(max_length=127, blank=True, null=True) verify_expiration = models.DateTimeField(default=timezone.now) registration_finished = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(auto_now=True) type = models.PositiveSmallIntegerField( choices=((u.value, u.name) for u in UserType), default=UserType.PARTICIPANT.value, ) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # Personal information picture = VersatileImageField( "Image", upload_to="user/picture/", default="user/picture/profile.png", storage=OverwriteStorage(), ) gender = models.PositiveSmallIntegerField(choices=((t.value, t.name) for t in GenderType), default=GenderType.NONE) birthday = models.DateField(blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) # University university = models.CharField(max_length=255, blank=True, null=True) degree = models.CharField(max_length=255, blank=True, null=True) graduation_year = models.PositiveIntegerField(default=timezone.now().year, blank=True, null=True) # Details website = models.CharField(max_length=255, blank=True, null=True) resume = models.FileField(upload_to="user/resume/", blank=True, null=True) # Slack # TODO: Should somehow be unique if not null slack_id = models.CharField(max_length=255, blank=True, null=True) slack_token = models.CharField(max_length=255, blank=True, null=True) slack_scopes = models.CharField(max_length=255, blank=True, null=True) slack_status_text = models.CharField(max_length=255, blank=True, null=True) slack_status_emoji = models.CharField(max_length=255, blank=True, null=True) slack_display_name = models.CharField(max_length=255, blank=True, null=True) slack_picture = VersatileImageField( "Slack image", upload_to="user/slack/picture/", blank=True, null=True, storage=OverwriteStorage(), ) slack_picture_hash = models.CharField(max_length=255, blank=True, null=True) objects = UserManager() USERNAME_FIELD = "email" EMAIL_FIELD = "email" REQUIRED_FIELDS = ["name", "surname"] @property def profile_picture(self): if self.slack_picture: return self.slack_picture return self.picture @property def slack_status(self): if self.slack_status_emoji: try: emoji = (EMOJIS[self.slack_status_emoji[1:-1]].encode( "utf-16", "surrogatepass").decode("utf-16")) return f"{emoji} {self.slack_status_text}" except KeyError: return f"{self.slack_status_text}" else: return "" @property def is_organiser(self): return self.type == UserType.ORGANISER.value @property def is_participant(self): return self.type == UserType.PARTICIPANT.value @property def is_staff(self): return self.is_admin @cached_property def role(self): return self.role_set.filter( ends_at__isnull=True).order_by("-is_head").first() @cached_property def event_registrations(self): return self.registrations.order_by("-created_at").all() @property def full_name(self): if self.surname: return self.name + " " + self.surname return self.name def __str__(self): if self.full_name: return f"{self.full_name} <{self.email}>" return f"<{self.email}>" def get_dict(self): return { "name": self.name, "surname": self.surname, "full_name": self.full_name, "email": self.email, "picture": self.picture, "gender": self.gender, "birthday": self.birthday, "phone": self.phone, "city": self.city, "country": self.country, "type": self.type, "description": (self.description if self.description else ""), "website": (self.website if self.website else ""), } def disable_verify(self): self.email_verified = False self.save() def update_verify(self, verify_key, verify_expiration: Optional[timezone.datetime] = None): if not verify_expiration: verify_expiration = timezone.now() + timezone.timedelta(days=1) self.verify_key = verify_key self.verify_expiration = verify_expiration self.save() def delete_verify_key(self): self.verify_key = None self.save() def verify(self, verify_key): if timezone.now( ) <= self.verify_expiration and self.verify_key == verify_key: self.email_verified = True self.delete_verify_key() self.save() from user.utils import send_slack send_slack(user=self) def mark_as_inactive(self): self.is_active = False self.save() def finish_registration( self, name, surname, phone, university, degree, graduation_year, birthday, gender, city, country, ): self.name = name self.surname = surname self.phone = phone self.university = university self.degree = degree self.graduation_year = graduation_year self.birthday = birthday self.gender = gender self.city = city self.country = country self.registration_finished = True self.save() @property def resume_name(self): return os.path.basename(self.resume.name) def clean(self): messages = dict() # TODO: Check properly if 14 already or not if self.birthday and (timezone.now().date() - self.birthday ) < timezone.timedelta(days=14 * 365): messages["age"] = "The minimum age is 14" if messages: raise ValidationError(messages) def save(self, *args, **kwargs): self.clean() if is_email_organiser(self.email): self.type = UserType.ORGANISER.value return super().save(*args, **kwargs)