Beispiel #1
0
class AbstractEmailUser(AbstractUser):
    """Abstract Email login user model."""

    username_validator = UnicodeUsernameValidator()
    username = models.CharField(
        _('username'),
        max_length=150,
        help_text=_(
            'Required. 150 characters or fewer.'
            ' Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
    )
    email = models.EmailField(
        _('email address'),
        unique=True,
        error_messages={
            'unique': _("A user with that email address already exists."),
        },
    )
    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta(AbstractUser.Meta):
        abstract = True
Beispiel #2
0
class User(AbstractUser):
    # USER_TYPES = (
    #     ('C', 'client'),
    #     ('E', 'employee'),
    #     ('S', 'SuperUser'),
    # )
    # user_type = models.CharField(max_length=1, choices=USER_TYPES)
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)
    avatar = models.ImageField(upload_to='avatars',
                               default=const.DEFAULT_PROFILE_IMAGE_USER)
    email = models.EmailField(unique=True, db_index=True)
    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{9,15}$',
        message=
        "Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
    )
    phone_number = models.CharField(validators=[phone_regex],
                                    max_length=17,
                                    blank=True)  # validators should be a list
    is_active = models.BooleanField(default=False)
    deleted = models.BooleanField(default=False)
    # activation_token = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True)

    username_validator = UnicodeUsernameValidator()
    username = models.CharField(
        # min_length=4,
        max_length=20,
        unique=True,
        help_text=
        'Required. 20 characters or fewer. Letters, digits and @/./+/-/_ only.',
        validators=[username_validator],
        error_messages={
            'unique': "A user with that username already exists.",
        },
    )

    @property
    def is_employee(self):
        return False

    @property
    def is_client(self):
        return False

    def save(self, *args, **kwargs):
        """
        Save user and if user is superuser, activate it.
        """
        if not self.id:
            if self.is_superuser:
                self.is_active = True
                super(User, self).save(*args, **kwargs)
            else:
                super(User, self).save(*args, **kwargs)
                token = Token(user=self)
                # send_activation_account_email(self)
                token.save()
        else:
            super(User, self).save(*args, **kwargs)
Beispiel #3
0
class Operator(models.Model):
    username = models.CharField(
        _('username'),
        max_length=55,
        unique=True,
        help_text=
        _('Required. 55 characters or fewer. Letters, digits and @/./+/-/_ only.'
          ),
        validators=[UnicodeUsernameValidator()],
        error_messages={
            'unique': _("An operator with that username already exists.")
        })

    date_joined = models.DateTimeField(_('date joined'),
                                       auto_now_add=True,
                                       editable=False)

    def get_type(self):
        for t in OperatorTypes:
            if hasattr(self, t.value):
                return t

    def get_display_name(self):
        operator_type = self.get_type().value
        return "%s: %s" % (operator_type.title(),
                           str(getattr(self, operator_type)))

    def __repr__(self):
        return self.get_display_name()

    def __str__(self):
        return self.__repr__()
Beispiel #4
0
class UserRegisterForm(forms.Form):

    full_name = forms.CharField(max_length=100, required=True)
    username = forms.CharField(
        max_length=150,
        help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
        validators=[UnicodeUsernameValidator()],
        required=True
    )
    email = forms.EmailField(required=True)
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError("Username is already taken")
        return username

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError("There is already an account "
                                        "associated with this email")
        return email

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2
Beispiel #5
0
class CustomUser(AbstractUser):
    username_validator = UnicodeUsernameValidator()
    password = models.CharField(max_length=128,
                                blank=True,
                                default=None,
                                null=True)
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=
        _('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'
          ),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    email = models.EmailField(_('email address'), unique=True)
    bio = models.TextField(blank=True)

    ROLE_CHOICES = [
        ('user', 'user'),
        ('admin', 'admin'),
        ('moderator', 'moderator'),
    ]

    role = models.CharField(max_length=20,
                            choices=ROLE_CHOICES,
                            default='users',
                            help_text=_('choose your destiny'))

    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)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

    def __str__(self):
        return self.username
Beispiel #6
0
class Login(PermissionsMixin, AbstractBaseUser):
    """How a user authenticates themself to the system.

    Custom class to excise the needless first_name/last_name fields.
    """
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        'username',
        max_length=150,
        unique=True,
        blank=False,
        help_text=
        'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
        validators=[username_validator],
        error_messages={
            'unique': "A user with that username already exists.",
        },
    )
    email = models.EmailField('email address', 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_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)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = [EMAIL_FIELD]

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Beispiel #7
0
class User(AbstractBaseUser, PermissionsMixin):

    username = models.CharField(
        max_length=150,
        unique=True,
        help_text='REQUIRED',
        validators=[UnicodeUsernameValidator()],
        error_messages={
            'unique': 'A user with that username already exists.',
        })

    email = models.EmailField(unique=True,
                              error_messages={
                                  'unique':
                                  'A user with that email already exists',
                              })

    is_staff = models.BooleanField(
        default=False,
        help_text='Designates whether the user can log into admin site')

    is_active = models.BooleanField(
        default=True,
        help_text='Designates whether the user is active.'
        'UnSelect this instead of deleting account')

    date_joined = models.DateTimeField(auto_now_add=True)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.username

    def get_email(self):
        return self.email

    @property
    def is_admin(self):
        return self.is_superuser

        # Enable staff users all the permissions to perform actions
        # in admin site

    def has_perm(self, perm, obj=None):
        return self.is_staff

    def has_perms(self, perm_list, obj=None):
        return self.is_staff

    def has_module_perms(self, app_label):
        return self.is_staff
Beispiel #8
0
class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    Username and password are required. Other fields are optional.
    """
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    last_login = None
    email = models.EmailField(_('email address'), blank=True)
    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.'
        ),
    )

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        abstract = True

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Beispiel #9
0
class UserRegistrationForm(forms.Form):

    full_name = forms.CharField(max_length=100, required=True)

    username = forms.CharField(max_length=150,
                               help_text='REQUIRED',
                               validators=[UnicodeUsernameValidator()],
                               required=True)

    email = forms.EmailField(required=True)

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm Password',
                                widget=forms.PasswordInput)

    def clean_username(self):

        username = self.cleaned_data.get('username')
        # if len(username < 4):
        #    raise forms.ValidationError('username must at least be 4 characters long')
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('username already exists')
        return username

    def clean_email(self):

        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError(
                'A user with this email already exists')
        return email

    def clean_password2(self):

        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        # At least 8 char long
        if len(password1) < 8:
            raise forms.ValidationError(
                "The new password must be at least 8 characters long.")
        # check for digit
        if not any(char.isdigit() for char in password1):
            raise forms.ValidationError(
                'Password must contain at least 1 digit.')
        # check for letter
        if not any(char.isalpha() for char in password1):
            raise forms.ValidationError(
                'Password must contain at least 1 letter.')
        # passwords should match
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError('Passwords do not match')
        return password2
Beispiel #10
0
class UserProfileUpdateForm(forms.Form):

    full_name = forms.CharField(max_length=100, required=True)
    username = forms.CharField(
        max_length=150,
        help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
        validators=[UnicodeUsernameValidator()],
        required=True
    )
    email = forms.EmailField(required=True)
    avatar = forms.ImageField(label='profile pic', required=False)
    bio = forms.CharField(max_length=200, required=False,
                          widget=forms.Textarea(attrs={'cols': 40,  'rows': 3}))
Beispiel #11
0
class User(AbstractUser):
    username = models.CharField(
        "username",
        max_length=150,
        unique=True,
        validators=[UnicodeUsernameValidator(),
                    MinLengthValidator(3)],
        help_text=
        ("Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
         ),
        error_messages={
            "unique": "A user with that username already exists.",
        },
    )
Beispiel #12
0
class User(AbstractUser):
    username = models.CharField(
        _("username"),
        max_length=150,
        unique=True,
        help_text=
        _("Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
          ),
        validators=[UnicodeUsernameValidator(),
                    MinLengthValidator(3)],
        error_messages={
            "unique": _("A user with that username already exists."),
        },
    )
    avatar = models.ForeignKey("Avatar",
                               null=True,
                               blank=True,
                               on_delete=models.PROTECT)
    is_guest = models.BooleanField(default=False)

    # exteneded properties to support mdclub
    answer_count = models.IntegerField(default=0)
    article_count = models.IntegerField(default=0)
    avatar_text = models.CharField(max_length=50, null=True)
    bio = models.CharField(max_length=160, default='')
    blog = models.CharField(max_length=255, default='')
    company = models.CharField(max_length=255, default='')
    cover = models.CharField(max_length=50, default='')
    create_ip = models.CharField(max_length=80, null=True)
    create_location = models.CharField(max_length=100, null=True)
    create_time = models.IntegerField(null=True)
    disable_time = models.IntegerField(default=0)
    followee_count = models.IntegerField(default=0)
    follower_count = models.IntegerField(default=0)
    following_article_count = models.IntegerField(default=0)
    following_question_count = models.IntegerField(default=0)
    following_topic_count = models.IntegerField(default=0)
    headline = models.CharField(max_length=40, default='')
    inbox_unread = models.IntegerField(default=0)
    last_login_ip = models.CharField(max_length=80, null=True)
    last_login_location = models.CharField(max_length=100, null=True)
    last_login_time = models.IntegerField(null=True)
    location = models.CharField(max_length=255, null=True)
    notification_unread = models.IntegerField(default=0)
    question_count = models.IntegerField(default=0)
    update_time = models.IntegerField(null=True)

    class Meta:
        ordering = ["-id"]
Beispiel #13
0
class User(AbstractUser):
    email = models.EmailField(max_length=254, unique=True)
    username = models.CharField(
        max_length=150,
        unique=True,
        validators=[UnicodeUsernameValidator(),
                    MinLengthValidator(3)],
    )
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ("username", "first_name", "last_name")

    class Meta:
        ordering = ["-id"]
Beispiel #14
0
class Buyer(AbstractUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [
        'username',
    ]

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

    username_validator = UnicodeUsernameValidator()
    username = models.SlugField(
        gettext_lazy('username'),
        unique=True,
        validators=[username_validator],
        max_length=50,
        error_messages={
            'unique': gettext_lazy('A user with that username already exists'),
        },
    )
Beispiel #15
0
class ShopUser(AbstractUser):
    username_validator = UnicodeUsernameValidator()
    gender_types = [('m', 'male'), ('f', 'female')]
    gender = models.CharField(max_length=1,
                              choices=gender_types,
                              null=True,
                              blank=True)
    email = models.EmailField(unique=True, null=False)
    phone_number = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email
Beispiel #16
0
class Travler(AbstractUser):
    avatar = models.ImageField(verbose_name='Аватар',
                               upload_to='user_avatars',
                               blank=True,
                               null=True)
    username_validator = UnicodeUsernameValidator()
    username = models.SlugField(
        _('username'),
        unique=True,
        validators=[username_validator],
        max_length=30,
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    info = JSONField()
    is_active = models.BooleanField(default=True)
    is_author = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return "User: %s" % self.username

    def serialize(self, username, detailed=True):
        if username:
            pass
        result = {
            'username':
            self.username,
            'modified':
            self.modified,
            'link':
            reverse_lazy('api_user:detail', kwargs={'username': self.username})
        }
        if not detailed:
            return result
        result.update({
            'is_active': self.is_active,
        })
        if self.avatar:
            result['image'] = self.avatar.url

        return result
Beispiel #17
0
class UserProfileUpdateForm(forms.Form):

    full_name = forms.CharField(max_length=100)

    username = forms.CharField(max_length=150,
                               help_text='REQUIRED',
                               validators=[UnicodeUsernameValidator()],
                               required=True)

    email = forms.EmailField(required=True)

    avatar = forms.ImageField(label='Profile Pic', required=False)

    bio = forms.CharField(max_length=200,
                          required=False,
                          widget=forms.Textarea(attrs={
                              'cols': 40,
                              'rows': 3
                          }))
Beispiel #18
0
def check_username_existing(request):
    username_validator = UnicodeUsernameValidator()
    try:
        user = get_object_or_404(Account,
                                 username=request.GET['picked_username'])
    except:
        user = None
    try:
        valid = username_validator(request.GET['picked_username'])
        valid = True
    except ValidationError:
        valid = None

    context = {
        'is_used': True if user else False,
        'is_valid': True if valid else False,
    }

    return JsonResponse(context, status=200)
Beispiel #19
0
class user(AbstractBaseUser, PermissionsMixin):

    id = models.AutoField(primary_key=True)
    username_validator = UnicodeUsernameValidator()
    username = models.CharField(max_length=150,
                                unique=True,
                                validators=[username_validator],
                                null=False)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)

    objects = UserManager()

    class Meta:
        db_table = 'user'

    USERNAME_FIELD = 'username'
Beispiel #20
0
class User(AbstractUser):
    username = models.CharField(
        _("username"),
        max_length=150,
        unique=True,
        help_text=
        _("Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
          ),
        validators=[UnicodeUsernameValidator(),
                    MinLengthValidator(3)],
        error_messages={
            "unique": _("A user with that username already exists."),
        },
    )
    avatar = models.ForeignKey("Avatar",
                               null=True,
                               blank=True,
                               on_delete=models.PROTECT)
    is_guest = models.BooleanField(default=False)

    class Meta:
        ordering = ["-id"]
Beispiel #21
0
class User(AbstractUser):
    email = models.EmailField(_('email address'), unique=True)
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=False,
        blank=True,
        help_text=_(
            'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[UnicodeUsernameValidator()],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    class Meta:
        db_table = 'auth_user'

    def __str__(self):
        return self.email
Beispiel #22
0
class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """
    Абстрактный класс пользователя.
    """
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    email = models.EmailField(_('email address'), blank=True)
    first_name = models.CharField(_('first name'), max_length=30)
    last_name = models.CharField(_('last name'), max_length=30)
    is_staff = models.BooleanField(_('is_staff'), default=True)
    is_superuser = models.BooleanField(_('is_superuser'), default=True)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    class Meta:
        abstract = True
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)
Beispiel #23
0
class CustomUser(AbstractBaseUser, PermissionsMixin):
    DEPT = (('CS', 'Computer Science And Engineering'),
            ('IT', 'Information Technology'),
            ('EEE', 'Electrical & Electronics Engineering'),
            ('EC', 'Electronics & Communication'),
            ('SFE', 'Safety & Fire Engineering'), ('CE', 'Civil Engineering'),
            ('ME', 'Mechanical Engineering'))

    username_validator = UnicodeUsernameValidator()
    category = models.CharField(max_length=20, default='General')
    username = models.CharField(
        max_length=150,
        unique=True,
        help_text=
        'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
        validators=[username_validator],
        error_messages={
            'unique': ("A user with that username already exists."),
        },
    )
    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)
    dept = models.CharField(max_length=70, choices=DEPT)
    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=django.utils.timezone.now)

    objects = CustomUserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = ('user')
        verbose_name_plural = ('users')
        # abstract = True

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    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.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Beispiel #24
0
class BoxAbstractUser(models.Model):
    gender_choices = [
      ["u",_("Невідомо")],
      ["m",_("Чоловік")],
      ["f",_("Жінка")],
    ]
    username_validator = UnicodeUsernameValidator()
    password     = models.CharField(
        _('password'), max_length=128,
    )
    phone_number = models.CharField(
        _("Номер телефону"), max_length=255, 
        blank=True, null=True,
    )
    address      = models.TextField(
        _("Адреса"), blank=True, null=True,
    )
    birth_date   = models.DateTimeField(
        _("Дата народження"), blank=True, null=True,
    )
    gender       = models.CharField(
        _("Стать"), choices=gender_choices, 
        max_length=20, default="m",
    )
    first_name   = models.CharField(
        _('first name'), 
        max_length=30, blank=True, null=True,
    )
    last_name    = models.CharField(
        _('last name'), 
        max_length=150, blank=True, null=True,
    )
    email        = models.EmailField(
        _('email address'), blank=True,
        unique=True, 
    )
    # if 'sw_shop.sw_customer' in settings.INSTALLED_APPS:
    #     group        = models.ForeignKey(
    #         to="sw_customer.CustomerGroup", 
    #         verbose_name=_("Група"), 
    #         blank=True, null=True, 
    #         on_delete=models.SET_NULL, 
    #         help_text=("Група з купонами на скидку"),
    #    )
    username     = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    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.'
        ),
    )
    is_superuser = models.BooleanField(
        _('superuser status'),
        default=False,
        help_text=_(
            'Designates that this user has all permissions without '
            'explicitly assigning them.'
        ),
    )
    groups       = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name="user_set",
        related_query_name="user",
    )
    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('user permissions'),
        blank=True,
        help_text=_('Specific permissions for this user.'),
        related_name="user_set",
        related_query_name="user",
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    last_login  = models.DateTimeField(_('last login'), blank=True, null=True)
    objects     = UserManager()
    _password   = None
    EMAIL_FIELD     = 'email'
    USERNAME_FIELD  = 'username'
    REQUIRED_FIELDS = ['email']
    
    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        abstract = True

    def __str__(self):
      return f"{self.username}, {self.get_full_name()}"
      return f"{self.first_name} {self.last_name} ({self.username}, {self.phone_number}, {self.email})"

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def email_user(self, subject, message, from_email=None, **kwargs):
        send_mail(subject, message, from_email, [self.email], **kwargs)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if self._password is not None:
            password_validation.password_changed(self._password, self)
            self._password = None

    def get_username(self):
        return getattr(self, self.USERNAME_FIELD)

    def clean(self):
        setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username()))

    def natural_key(self):
        return (self.get_username(),)

    def set_password(self, raw_password):
        self.password = make_password(raw_password)
        self._password = raw_password

    def check_password(self, raw_password):
        def setter(raw_password):
            self.set_password(raw_password)
            self._password = None
            self.save(update_fields=["password"])
        return check_password(raw_password, self.password, setter)

    def set_unusable_password(self):
        self.password = make_password(None)

    def has_usable_password(self):
        return is_password_usable(self.password)

    def get_session_auth_hash(self):
        key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
        return salted_hmac(key_salt, self.password).hexdigest()

    def get_user_permissions(self, obj=None):
        return _user_get_permissions(self, obj, 'user')

    def get_group_permissions(self, obj=None):
        return _user_get_permissions(self, obj, 'group')

    def get_all_permissions(self, obj=None):
        return _user_get_permissions(self, obj, 'all')

    def has_perm(self, perm, obj=None):
        if self.is_active and self.is_superuser:
            return True

        return _user_has_perm(self, perm, obj)

    def has_perms(self, perm_list, obj=None):
        return all(self.has_perm(perm, obj) for perm in perm_list)

    def has_module_perms(self, app_label):
        if self.is_active and self.is_superuser:
            return True

        return _user_has_module_perms(self, app_label)

    @classmethod
    def get_email_field_name(cls):
        try:
            return cls.EMAIL_FIELD
        except AttributeError:
            return 'email'

    @classmethod
    def normalize_username(cls, username):
        return unicodedata.normalize('NFKC', username) if isinstance(username, str) else username

    @property
    def is_anonymous(self):
        return False

    @property
    def is_authenticated(self):
        return True
Beispiel #25
0
from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
                                        PermissionsMixin,
                                        UnicodeUsernameValidator)
from django.utils.translation import ugettext_lazy as _
from django.core.validators import FileExtensionValidator
from django.contrib.auth.hashers import make_password
from django.core.mail import send_mail

from stdimage.models import StdImageField
from stdimage.validators import MinSizeValidator, MaxSizeValidator
from django_countries.fields import CountryField

from .model_addon import UploadToPathAndRename

USERNAME_VALIDATOR = UnicodeUsernameValidator()


class AccountManager(BaseUserManager):
    def create_user(self, username, email, password=None, **extra_fields):
        if not email:
            raise ValueError(_('Account must have an email address'))
        if not username:
            raise ValueError(_('Account must have an username'))

        user = self.model(username=username,
                          email=self.normalize_email(email),
                          **extra_fields)
        user.password = make_password(password)
        user.save(using=self._db)
        return user
Beispiel #26
0
class User(AbstractBaseUser, PermissionsMixin):
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=
        _('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'
          ),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    telegram = models.CharField(_('telegram'), max_length=30, blank=True)
    jabber = models.CharField(_('jabber'), max_length=30, blank=True)
    api_address = models.CharField(_('api address'),
                                   max_length=150,
                                   blank=True)
    email = models.EmailField(_('email address'), blank=True)
    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)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        abstract = False

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = self.username
        return full_name.strip()

    def get_short_name(self):
        """Return the short name for the user."""
        return self.username

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Beispiel #27
0
class User(AbstractBaseUser, PermissionsMixin):
    username_validator = UnicodeUsernameValidator()
    username = models.CharField(
        '用户名',
        max_length=150,
        unique=True,
        help_text='必填,小于150个字符。',
        validators=[username_validator],
        error_messages={'unique': "用户名已存在。"},
    )
    full_name = models.CharField('姓名',
                                 max_length=30,
                                 blank=True,
                                 help_text='姓名')
    email = models.EmailField('Email',
                              null=True,
                              blank=True,
                              help_text='Email')
    mobile = models.CharField('手机号码',
                              max_length=32,
                              null=True,
                              blank=True,
                              help_text='手机号码')
    phone = models.CharField('办公电话',
                             max_length=32,
                             null=True,
                             blank=True,
                             help_text='办公电话')
    is_staff = models.BooleanField('可进入后台管理',
                                   default=False,
                                   help_text='可进入后台管理')
    is_active = models.BooleanField('允许登录', default=True, help_text='允许登录')
    date_joined = models.DateTimeField('创建时间',
                                       default=timezone.now,
                                       help_text='创建时间')
    inner_code = models.CharField('内部工号',
                                  max_length=32,
                                  null=True,
                                  blank=True,
                                  help_text='内部工号')
    employee_position = models.CharField('职务',
                                         max_length=32,
                                         null=True,
                                         blank=True,
                                         help_text='职务')
    employee_rank = models.CharField('职级',
                                     help_text='职级',
                                     max_length=32,
                                     null=True,
                                     blank=True)
    sex = models.CharField('性别',
                           max_length=2,
                           choices=(
                               ('男', '男'),
                               ('女', '女'),
                           ),
                           null=True,
                           blank=True,
                           help_text='性别')
    marital_status = models.CharField('婚姻状况',
                                      help_text='婚姻状况',
                                      null=True,
                                      blank=True,
                                      max_length=5,
                                      choices=(
                                          ('已婚', '已婚'),
                                          ('未婚', '未婚'),
                                      ))
    home_address = models.CharField('家庭住址',
                                    help_text='家庭住址',
                                    max_length=200,
                                    null=True,
                                    blank=True)
    birthplace = models.CharField('籍贯',
                                  help_text='籍贯',
                                  max_length=100,
                                  null=True,
                                  blank=True)
    birthday = models.DateField('出生年月日',
                                help_text='出生年月日',
                                null=True,
                                blank=True)
    nationality = models.CharField('民族',
                                   help_text='民族',
                                   max_length=20,
                                   null=True,
                                   blank=True)
    political_status = models.CharField('政治面貌',
                                        help_text='政治面貌',
                                        max_length=50,
                                        blank=True,
                                        null=True)
    educational_level = models.CharField('文化程度',
                                         help_text='文化程度',
                                         max_length=20,
                                         blank=True,
                                         null=True)
    pid = models.CharField('身份证号',
                           help_text='身份证号',
                           max_length=20,
                           blank=True,
                           null=True)
    join_date = models.DateField('入职时间',
                                 null=True,
                                 blank=True,
                                 help_text='入职时间')
    out_date = models.DateField('离职时间',
                                null=True,
                                blank=True,
                                help_text='离职时间')
    description = models.TextField('备注', null=True, blank=True, help_text='备注')
    department = models.ForeignKey('Department',
                                   null=True,
                                   blank=True,
                                   related_name='users',
                                   on_delete=models.SET_NULL,
                                   verbose_name='部门',
                                   help_text='部门')
    sort_num = models.IntegerField('排序编号',
                                   help_text='排序编号',
                                   null=True,
                                   blank=True,
                                   default=0,
                                   db_index=True)
    readed_licence = models.BooleanField('已阅读用户协议',
                                         help_text='已阅读用户协议',
                                         default=False,
                                         null=True,
                                         blank=True)

    fuid = models.IntegerField('金蝶K3系统ID',
                               null=True,
                               blank=True,
                               help_text='金蝶K3系统ID(FItemID)')

    category = models.ManyToManyField('baseconfig.BaseConfigItem',
                                      blank=True,
                                      verbose_name='分类',
                                      help_text='分类',
                                      related_name='users')

    # 微信相关
    wechart_name = models.CharField('微信名称',
                                    max_length=64,
                                    null=True,
                                    blank=True,
                                    db_index=True,
                                    help_text='微信名称')
    wechart_avatar = models.ImageField('微信头像',
                                       upload_to='avatar/%Y/%m/%d/',
                                       null=True,
                                       blank=True,
                                       help_text='微信头像')
    wechart_oid = models.CharField('微信OID',
                                   max_length=64,
                                   null=True,
                                   blank=True,
                                   db_index=True,
                                   help_text='微信OID')
    wechart_uid = models.CharField('微信UID',
                                   max_length=64,
                                   null=True,
                                   blank=True,
                                   db_index=True,
                                   help_text='微信UID')
    wechart_access_token = models.CharField('微信 ACCESS TOKEN',
                                            max_length=128,
                                            null=True,
                                            blank=True,
                                            help_text='微信 ACCESS TOKEN')
    wechart_refresh_token = models.CharField('微信 REFRESH TOKEN',
                                             max_length=128,
                                             null=True,
                                             blank=True,
                                             help_text='微信 REFRESH TOKEN')
    wechart_session_key = models.CharField('微信会话密钥 SESSION_KEY',
                                           max_length=255,
                                           null=True,
                                           blank=True,
                                           help_text='微信会话密钥 SESSION_KEY')

    func_groups = models.ManyToManyField(
        FuncGroup,
        verbose_name='角色',
        blank=True,
        help_text='角色',
        related_name="user_set",
        related_query_name="user",
    )
    func_user_permissions = models.ManyToManyField(
        FuncPermission,
        verbose_name='功能权限',
        blank=True,
        help_text='功能权限',
        related_name="user_set",
        related_query_name="user",
    )

    number_01 = models.FloatField('数值内容01',
                                  null=True,
                                  blank=True,
                                  help_text='数值内容01')
    number_02 = models.FloatField('数值内容02',
                                  null=True,
                                  blank=True,
                                  help_text='数值内容02')
    number_03 = models.FloatField('数值内容03',
                                  null=True,
                                  blank=True,
                                  help_text='数值内容03')
    number_04 = models.FloatField('数值内容04',
                                  null=True,
                                  blank=True,
                                  help_text='数值内容04')
    number_05 = models.FloatField('数值内容05',
                                  null=True,
                                  blank=True,
                                  help_text='数值内容05')

    field_01 = models.TextField('附加内容01',
                                null=True,
                                blank=True,
                                help_text='附加内容01')
    field_02 = models.TextField('附加内容02',
                                null=True,
                                blank=True,
                                help_text='附加内容02')
    field_03 = models.TextField('附加内容03',
                                null=True,
                                blank=True,
                                help_text='附加内容03')
    field_04 = models.TextField('附加内容04',
                                null=True,
                                blank=True,
                                help_text='附加内容04')
    field_05 = models.TextField('附加内容05',
                                null=True,
                                blank=True,
                                help_text='附加内容05')

    fujian_01 = models.FileField('附件01',
                                 null=True,
                                 blank=True,
                                 help_text='附件01',
                                 upload_to='user/%Y/%m/%d/')
    fujian_02 = models.FileField('附件02',
                                 null=True,
                                 blank=True,
                                 help_text='附件02',
                                 upload_to='user/%Y/%m/%d/')
    fujian_03 = models.FileField('附件03',
                                 null=True,
                                 blank=True,
                                 help_text='附件03',
                                 upload_to='user/%Y/%m/%d/')
    fujian_04 = models.FileField('附件04',
                                 null=True,
                                 blank=True,
                                 help_text='附件04',
                                 upload_to='user/%Y/%m/%d/')
    fujian_05 = models.FileField('附件05',
                                 null=True,
                                 blank=True,
                                 help_text='附件05',
                                 upload_to='user/%Y/%m/%d/')
    fujian_06 = models.FileField('附件06',
                                 null=True,
                                 blank=True,
                                 help_text='附件06',
                                 upload_to='user/%Y/%m/%d/')
    fujian_07 = models.FileField('附件07',
                                 null=True,
                                 blank=True,
                                 help_text='附件07',
                                 upload_to='user/%Y/%m/%d/')
    fujian_08 = models.FileField('附件08',
                                 null=True,
                                 blank=True,
                                 help_text='附件08',
                                 upload_to='user/%Y/%m/%d/')
    fujian_09 = models.FileField('附件09',
                                 null=True,
                                 blank=True,
                                 help_text='附件09',
                                 upload_to='user/%Y/%m/%d/')
    fujian_10 = models.FileField('附件10',
                                 null=True,
                                 blank=True,
                                 help_text='附件10',
                                 upload_to='user/%Y/%m/%d/')

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = '02.用户'
        verbose_name_plural = verbose_name
        # permissions = (
        #     ("can_audit_task", "可审批任务"),
        #     ("can_audit_work", "可审批工作纪实"),
        # )
        ordering = ['department', 'sort_num', '-pk']

    def get_full_name(self):
        return self.full_name

    def get_short_name(self):
        return self.full_name

    @property
    def first_name(self):
        return self.full_name

    @property
    def last_name(self):
        return self.full_name

    @property
    def category_names(self):
        return ",".join(self.category.all().values_list('name', flat=True))

    def email_user(self, subject, message, from_email=None, **kwargs):
        if self.email:
            send_mail(subject, message, from_email, [self.email], **kwargs)

    def __str__(self):
        return self.full_name

    def move_to(self, target, position):
        users = target.department.users.exclude(pk=self.pk).values_list(
            'pk', flat=True).order_by('sort_num', '-pk')
        users = list(users)
        try:
            target_index = users.index(target.pk)
        except ValueError:
            return
        if position == 'left':
            users = users[:target_index] + [self.pk] + users[target_index:]
        elif position == 'right':
            users = users[:target_index + 1] + [self.pk
                                                ] + users[target_index + 1:]
        else:
            return
        for index, uid in enumerate(users):
            User.objects.filter(pk=uid).update(sort_num=index)

    @property
    def func_names(self):
        group_permission_names = self.func_groups.all().values(
            'permissions__name').distinct().values_list('permissions__name',
                                                        flat=True)
        permission_names = self.func_user_permissions.all().values_list(
            'name', flat=True)
        names = {*group_permission_names, *permission_names}
        return list(names)

    @property
    def func_codenames(self):
        group_permission_names = self.func_groups.all().values(
            'permissions__codename').distinct().values_list(
                'permissions__codename', flat=True)
        permission_names = self.func_user_permissions.all().values_list(
            'codename', flat=True)
        names = {*group_permission_names, *permission_names}
        return list(names)

    @property
    def func_group_names(self):
        return list(self.func_groups.values_list('name', flat=True))
Beispiel #28
0
class User(AbstractUser):
    username_validator = UnicodeUsernameValidator()

    COMMON = 0
    BANNED = 1
    STATUS_CHOICES = (
        (COMMON, 'common'),
        (BANNED, 'banned'),
    )
    # already in abstractUser
    # id
    # email (overwrite here)
    # first_name (overwrite here)
    # date_joined
    # is_active
    # is_staff
    # is_superuser
    # last_login
    # last_name (overwrite here)
    # password
    # username (overwrite here)
    id_status = models.IntegerField(
        choices=STATUS_CHOICES,
        default=COMMON,
    )
    first_name = models.CharField(_('first name'), max_length=255, blank=True)
    last_name = models.CharField(_('last name'), max_length=255, blank=True)
    username = models.CharField(
        _('username'),
        max_length=255,
        unique=True,
        help_text=
        _('Required. 255 characters or fewer. Letters, digits and @/./+/-/_ only.'
          ),
        validators=[username_validator,
                    NotEmailValidator()],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    email = models.EmailField(
        _('email address'),
        unique=True,
        error_messages={
            'unique': _("A user with that email already exists."),
        },
    )

    phone_number = models.CharField(
        _('phone number'),
        max_length=255,
        blank=True,
        validators=[GenericInternationalPhoneNumberValidator],
        help_text=
        _('Enter a phone number. This number must be in the generic international format.'
          ),
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )

    last_login = models.DateTimeField(_('last login'), default=timezone.now)
    is_email_confirmed = models.BooleanField(_('email confirmed'),
                                             default=False)
    city = models.CharField(_('city'), max_length=255, blank=True)
    profile_picture = models.URLField(_('Profile picture'),
                                      max_length=255,
                                      blank=True)  # Todo: link to our assets
    facebook = models.URLField(_('Facebook'), max_length=255, blank=True)
    linkedin = models.URLField(_('LinkedIn'), max_length=255, blank=True)
    google = models.URLField(_('Google'), max_length=255, blank=True)
    twitter = models.URLField(_('Twitter'), max_length=255, blank=True)
    website = models.URLField(_('website'), max_length=255, blank=True)

    objects = UserManager()

    class Meta:
        db_table = 'user'
        indexes = [
            models.Index(fields=['username'], name='username_idx'),
            models.Index(fields=['email'], name='email_idx'),
        ]

    def update_last_login(self):
        self.last_login = timezone.now()
        self.save()