jumpserver/apps/users/models.py

267 lines
8.6 KiB
Python
Raw Normal View History

2016-08-13 16:40:21 +00:00
# ~*~ coding: utf-8 ~*~
2016-08-08 16:43:11 +00:00
from __future__ import unicode_literals
from django.conf import settings
2016-08-20 17:16:30 +00:00
from django.contrib.auth.hashers import make_password
2016-09-19 07:47:58 +00:00
from django.utils import timezone
from django.db import models
2016-09-08 13:51:44 +00:00
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
2016-09-19 07:47:58 +00:00
from django.db import IntegrityError
2016-09-03 16:51:36 +00:00
from django.utils.translation import ugettext_lazy as _
2016-09-19 07:47:58 +00:00
from django.core import signing
2016-08-30 17:00:20 +00:00
from rest_framework.authtoken.models import Token
2016-08-09 17:30:19 +00:00
2016-09-10 13:08:10 +00:00
from common.utils import encrypt, decrypt, date_expired_default
2016-09-19 07:47:58 +00:00
from common.mixins import NoDeleteModelMixin
2016-08-14 09:21:04 +00:00
2016-08-13 16:40:21 +00:00
2016-09-19 07:47:58 +00:00
class UserGroup(NoDeleteModelMixin):
2016-09-03 16:51:36 +00:00
name = models.CharField(max_length=100, unique=True, verbose_name=_('Name'))
comment = models.TextField(blank=True, verbose_name=_('Comment'))
2016-09-06 08:50:19 +00:00
date_created = models.DateTimeField(auto_now_add=True)
2016-08-13 16:40:21 +00:00
created_by = models.CharField(max_length=100)
2016-08-09 17:30:19 +00:00
2016-08-13 16:40:21 +00:00
def __unicode__(self):
return self.name
2016-09-07 16:40:59 +00:00
def has_member(self, user):
if user in self.users.all():
return True
return False
2016-09-19 07:47:58 +00:00
def delete(self):
if self.name != 'Default':
self.users.clear()
return super(UserGroup, self).delete()
return True
2016-08-13 16:40:21 +00:00
class Meta:
2016-09-19 17:13:50 +00:00
db_table = 'user_group'
2016-08-13 16:40:21 +00:00
@classmethod
2016-08-22 11:53:01 +00:00
def initial(cls):
2016-09-19 07:47:58 +00:00
group, created = cls.objects.get_or_create(name='Default', comment='Default user group for all user',
created_by='System')
return group
2016-08-18 17:39:08 +00:00
@classmethod
def generate_fake(cls, count=100):
2016-09-08 13:51:44 +00:00
from random import seed, choice
2016-08-18 17:39:08 +00:00
import forgery_py
seed()
for i in range(count):
group = cls(name=forgery_py.name.full_name(),
comment=forgery_py.lorem_ipsum.sentence(),
2016-09-19 07:47:58 +00:00
created_by=choice(User.objects.all()).username)
2016-08-18 17:39:08 +00:00
try:
group.save()
except IntegrityError:
print('Error continue')
continue
2016-08-13 16:40:21 +00:00
class User(AbstractUser):
2016-08-24 09:14:21 +00:00
ROLE_CHOICES = (
2016-09-03 16:51:36 +00:00
('Admin', _('Administrator')),
('User', _('User')),
2016-08-24 09:14:21 +00:00
)
2016-09-03 16:51:36 +00:00
username = models.CharField(max_length=20, unique=True, verbose_name=_('Username'))
name = models.CharField(max_length=20, blank=True, verbose_name=_('Name'))
email = models.EmailField(max_length=30, unique=True, verbose_name=_('Email'))
2016-09-06 07:09:00 +00:00
groups = models.ManyToManyField(UserGroup, related_name='users', blank=True, verbose_name=_('User group'))
2016-09-03 16:51:36 +00:00
role = models.CharField(choices=ROLE_CHOICES, default='User', max_length=10, blank=True, verbose_name=_('Role'))
avatar = models.ImageField(upload_to="avatar", verbose_name=_('Avatar'))
wechat = models.CharField(max_length=30, blank=True, verbose_name=_('Wechat'))
phone = models.CharField(max_length=20, blank=True, verbose_name=_('Phone'))
enable_otp = models.BooleanField(default=False, verbose_name=_('Enable OTP'))
2016-08-20 17:16:30 +00:00
secret_key_otp = models.CharField(max_length=16, blank=True)
2016-09-07 16:40:59 +00:00
_private_key = models.CharField(max_length=5000, blank=True, verbose_name=_('ssh private key'))
_public_key = models.CharField(max_length=1000, blank=True, verbose_name=_('ssh public key'))
2016-09-03 16:51:36 +00:00
comment = models.TextField(max_length=200, blank=True, verbose_name=_('Comment'))
2016-09-19 07:47:58 +00:00
is_first_login = models.BooleanField(default=False)
2016-09-03 16:51:36 +00:00
date_expired = models.DateTimeField(default=date_expired_default, blank=True, null=True,
verbose_name=_('Date expired'))
2016-09-04 09:15:26 +00:00
created_by = models.CharField(max_length=30, default='', verbose_name=_('Created by'))
2016-08-09 17:30:19 +00:00
2016-08-22 11:53:01 +00:00
@property
def password_raw(self):
raise AttributeError('Password raw is not readable attribute')
#: Use this attr to set user object password, example
#: user = User(username='example', password_raw='password', ...)
#: It's equal:
#: user = User(username='example', ...)
#: user.set_password('password')
@password_raw.setter
2016-09-07 16:40:59 +00:00
def password_raw(self, password_raw_):
self.set_password(password_raw_)
2016-08-18 17:39:08 +00:00
2016-08-24 09:14:21 +00:00
@property
2016-08-20 17:16:30 +00:00
def is_expired(self):
if self.date_expired > timezone.now():
return False
else:
return True
2016-09-07 16:40:59 +00:00
@property
def private_key(self):
return decrypt(self._private_key)
@private_key.setter
def private_key(self, private_key_raw):
self._private_key = encrypt(private_key_raw)
@property
def public_key(self):
return decrypt(self._public_key)
@public_key.setter
def public_key(self, public_key_raw):
self._public_key = encrypt(public_key_raw)
2016-08-24 09:14:21 +00:00
@property
def is_superuser(self):
if self.role == 'Admin':
return True
else:
return False
@is_superuser.setter
def is_superuser(self, value):
if value is True:
self.role = 'Admin'
else:
self.role = 'User'
@property
def is_staff(self):
2016-08-25 16:51:05 +00:00
if self.is_authenticated and self.is_active and not self.is_expired and self.is_superuser:
2016-08-24 09:14:21 +00:00
return True
else:
return False
@is_staff.setter
def is_staff(self, value):
pass
2016-08-22 11:53:01 +00:00
def save(self, *args, **kwargs):
if not self.name:
self.name = self.username
2016-08-24 09:14:21 +00:00
2016-08-23 11:36:15 +00:00
super(User, self).save(*args, **kwargs)
2016-09-19 07:47:58 +00:00
# Add the current user to the default group.
2016-08-22 11:53:01 +00:00
group = UserGroup.initial()
2016-09-19 07:47:58 +00:00
self.groups.add(group)
2016-08-22 11:53:01 +00:00
@property
2016-08-31 11:28:06 +00:00
def private_token(self):
return self.get_private_token()
2016-08-31 11:28:06 +00:00
def get_private_token(self):
try:
token = Token.objects.get(user=self)
except Token.DoesNotExist:
2016-08-31 11:28:06 +00:00
token = Token.objects.create(user=self)
return token.key
def refresh_private_token(self):
Token.objects.filter(user=self).delete()
return Token.objects.create(user=self)
2016-09-01 15:09:58 +00:00
def generate_reset_token(self):
return signing.dumps({'reset': self.id, 'email': self.email})
2016-08-31 11:28:06 +00:00
2016-09-07 16:40:59 +00:00
def is_member_of(self, user_group):
if user_group in self.groups.all():
return True
return False
2016-08-31 11:28:06 +00:00
@classmethod
2016-09-02 10:10:26 +00:00
def validate_reset_token(cls, token, max_age=3600):
2016-08-31 11:28:06 +00:00
try:
data = signing.loads(token, max_age=max_age)
user_id = data.get('reset', None)
user_email = data.get('email', '')
user = cls.objects.get(id=user_id, email=user_email)
2016-09-03 16:51:36 +00:00
except (signing.BadSignature, cls.DoesNotExist):
2016-09-02 10:10:26 +00:00
user = None
return user
def reset_password(self, new_password):
self.set_password(new_password)
self.save()
2016-08-22 11:53:01 +00:00
class Meta:
db_table = 'user'
#: Use this method initial user
2016-08-20 17:16:30 +00:00
@classmethod
2016-08-22 11:53:01 +00:00
def initial(cls):
2016-08-20 17:16:30 +00:00
user = cls(username='admin',
email='admin@jumpserver.org',
2016-09-03 16:51:36 +00:00
name=_('Administrator'),
2016-08-22 11:53:01 +00:00
password_raw='admin',
2016-08-24 09:14:21 +00:00
role='Admin',
2016-09-03 16:51:36 +00:00
comment=_('Administrator is the super user of system'),
created_by=_('System'))
2016-08-20 17:16:30 +00:00
user.save()
2016-08-22 11:53:01 +00:00
user.groups.add(UserGroup.initial())
2016-08-20 17:16:30 +00:00
2016-09-23 08:30:59 +00:00
def delete(self):
if self.is_superuser:
return
return super(User, self).delete()
2016-08-18 17:39:08 +00:00
@classmethod
def generate_fake(cls, count=100):
2016-08-20 17:16:30 +00:00
from random import seed, choice
2016-08-18 17:39:08 +00:00
import forgery_py
from django.db import IntegrityError
seed()
for i in range(count):
user = cls(username=forgery_py.internet.user_name(True),
email=forgery_py.internet.email_address(),
name=forgery_py.name.full_name(),
password=make_password(forgery_py.lorem_ipsum.word()),
2016-08-24 09:14:21 +00:00
role=choice(dict(User.ROLE_CHOICES).keys()),
2016-08-18 17:39:08 +00:00
wechat=forgery_py.internet.user_name(True),
comment=forgery_py.lorem_ipsum.sentence(),
2016-09-19 07:47:58 +00:00
created_by=choice(cls.objects.all()).username)
2016-08-18 17:39:08 +00:00
try:
user.save()
except IntegrityError:
2016-08-22 11:53:01 +00:00
print('Duplicate Error, continue ...')
2016-08-18 17:39:08 +00:00
continue
user.groups.add(choice(UserGroup.objects.all()))
user.save()
2016-08-20 17:16:30 +00:00
def init_all_models():
2016-08-24 09:14:21 +00:00
for model in (UserGroup, User):
2016-09-19 07:47:58 +00:00
if hasattr(model, 'initial'):
2016-08-22 11:53:01 +00:00
model.initial()
2016-08-18 17:39:08 +00:00
2016-08-20 17:16:30 +00:00
def generate_fake():
2016-08-24 09:14:21 +00:00
for model in (UserGroup, User):
2016-09-19 07:47:58 +00:00
if hasattr(model, 'generate_fake'):
2016-08-20 17:16:30 +00:00
model.generate_fake()
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
2016-08-30 17:00:20 +00:00
try:
Token.objects.create(user=instance)
except IntegrityError:
pass