2016-12-20 15:06:27 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2017-11-23 06:08:01 +00:00
|
|
|
import uuid
|
2016-12-20 15:06:27 +00:00
|
|
|
from collections import OrderedDict
|
|
|
|
|
2017-01-26 12:24:50 +00:00
|
|
|
from django.conf import settings
|
2016-12-20 15:06:27 +00:00
|
|
|
from django.contrib.auth.hashers import make_password
|
|
|
|
from django.contrib.auth.models import AbstractUser
|
|
|
|
from django.core import signing
|
2017-01-26 12:24:50 +00:00
|
|
|
from django.db import models
|
2016-12-20 15:06:27 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
from django.utils import timezone
|
|
|
|
from django.shortcuts import reverse
|
|
|
|
|
2017-12-24 10:53:07 +00:00
|
|
|
from common.utils import get_signer, date_expired_default
|
2016-12-20 16:43:52 +00:00
|
|
|
|
|
|
|
|
|
|
|
__all__ = ['User']
|
2017-12-24 10:53:07 +00:00
|
|
|
signer = get_signer()
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
class User(AbstractUser):
|
2017-12-29 18:29:29 +00:00
|
|
|
ROLE_ADMIN = 'Admin'
|
|
|
|
ROLE_USER = 'User'
|
|
|
|
ROLE_APP = 'App'
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
ROLE_CHOICES = (
|
2018-01-01 07:08:33 +00:00
|
|
|
(ROLE_ADMIN, _('Administrator')),
|
|
|
|
(ROLE_USER, _('User')),
|
|
|
|
(ROLE_APP, _('Application'))
|
2016-12-20 15:06:27 +00:00
|
|
|
)
|
2017-11-23 06:08:01 +00:00
|
|
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
2017-12-25 04:22:49 +00:00
|
|
|
username = models.CharField(max_length=128, unique=True, verbose_name=_('Username'))
|
|
|
|
name = models.CharField(max_length=128, verbose_name=_('Name'))
|
|
|
|
email = models.EmailField(max_length=128, unique=True, verbose_name=_('Email'))
|
2018-01-11 12:10:27 +00:00
|
|
|
groups = models.ManyToManyField('users.UserGroup', related_name='users', blank=True, verbose_name=_('User group'))
|
2016-12-20 15:06:27 +00:00
|
|
|
role = models.CharField(choices=ROLE_CHOICES, default='User', max_length=10, blank=True, verbose_name=_('Role'))
|
2017-03-31 03:25:25 +00:00
|
|
|
avatar = models.ImageField(upload_to="avatar", null=True, verbose_name=_('Avatar'))
|
2017-12-25 04:22:49 +00:00
|
|
|
wechat = models.CharField(max_length=128, blank=True, verbose_name=_('Wechat'))
|
2016-12-20 15:06:27 +00:00
|
|
|
phone = models.CharField(max_length=20, blank=True, null=True, verbose_name=_('Phone'))
|
|
|
|
enable_otp = models.BooleanField(default=False, verbose_name=_('Enable OTP'))
|
|
|
|
secret_key_otp = models.CharField(max_length=16, blank=True)
|
2017-12-14 13:27:14 +00:00
|
|
|
# Todo: Auto generate key, let user download
|
|
|
|
_private_key = models.CharField(max_length=5000, blank=True, verbose_name=_('Private key'))
|
|
|
|
_public_key = models.CharField(max_length=5000, blank=True, verbose_name=_('Public key'))
|
2016-12-20 15:06:27 +00:00
|
|
|
comment = models.TextField(max_length=200, blank=True, verbose_name=_('Comment'))
|
2017-12-31 16:45:12 +00:00
|
|
|
is_first_login = models.BooleanField(default=True)
|
2017-11-23 06:35:16 +00:00
|
|
|
date_expired = models.DateTimeField(default=date_expired_default, blank=True, null=True, verbose_name=_('Date expired'))
|
2016-12-20 15:06:27 +00:00
|
|
|
created_by = models.CharField(max_length=30, default='', verbose_name=_('Created by'))
|
|
|
|
|
|
|
|
@property
|
|
|
|
def password_raw(self):
|
2016-12-20 16:43:52 +00:00
|
|
|
raise AttributeError('Password raw is not a readable attribute')
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
#: 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
|
|
|
|
def password_raw(self, password_raw_):
|
|
|
|
self.set_password(password_raw_)
|
|
|
|
|
|
|
|
def get_absolute_url(self):
|
|
|
|
return reverse('users:user-detail', args=(self.id,))
|
|
|
|
|
2017-02-09 13:19:49 +00:00
|
|
|
def is_public_key_valid(self):
|
|
|
|
"""
|
|
|
|
Check if the user's ssh public key is valid.
|
|
|
|
This function is used in base.html.
|
|
|
|
"""
|
|
|
|
if self._public_key:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
@property
|
|
|
|
def is_expired(self):
|
2017-07-13 03:46:56 +00:00
|
|
|
if self.date_expired and self.date_expired < timezone.now():
|
2016-12-20 15:06:27 +00:00
|
|
|
return True
|
2016-12-20 16:43:52 +00:00
|
|
|
else:
|
|
|
|
return False
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_valid(self):
|
|
|
|
if self.is_active and not self.is_expired:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
@property
|
|
|
|
def private_key(self):
|
|
|
|
return signer.unsign(self._private_key)
|
|
|
|
|
|
|
|
@private_key.setter
|
|
|
|
def private_key(self, private_key_raw):
|
|
|
|
self._private_key = signer.sign(private_key_raw)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def public_key(self):
|
|
|
|
return signer.unsign(self._public_key)
|
|
|
|
|
|
|
|
@public_key.setter
|
|
|
|
def public_key(self, public_key_raw):
|
|
|
|
self._public_key = signer.sign(public_key_raw)
|
|
|
|
|
2017-03-29 16:51:36 +00:00
|
|
|
@property
|
2017-03-30 08:28:00 +00:00
|
|
|
def public_key_obj(self):
|
|
|
|
class PubKey(object):
|
|
|
|
def __getattr__(self, item):
|
|
|
|
return ''
|
2017-03-29 16:51:36 +00:00
|
|
|
if self.public_key:
|
|
|
|
import sshpubkeys
|
|
|
|
try:
|
2017-03-30 08:28:00 +00:00
|
|
|
return sshpubkeys.SSHKey(self.public_key)
|
2017-03-29 16:51:36 +00:00
|
|
|
except TabError:
|
|
|
|
pass
|
2017-03-30 08:28:00 +00:00
|
|
|
return PubKey()
|
2017-03-29 16:51:36 +00:00
|
|
|
|
2016-12-20 15:06:27 +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'
|
|
|
|
|
2016-12-25 15:10:53 +00:00
|
|
|
@property
|
|
|
|
def is_app(self):
|
|
|
|
return self.role == 'App'
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
@property
|
|
|
|
def is_staff(self):
|
|
|
|
if self.is_authenticated and self.is_valid:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
@is_staff.setter
|
|
|
|
def is_staff(self, value):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
if not self.name:
|
|
|
|
self.name = self.username
|
2017-12-21 03:31:13 +00:00
|
|
|
super().save(*args, **kwargs)
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def private_token(self):
|
2016-12-25 15:10:53 +00:00
|
|
|
return self.create_private_token()
|
2016-12-20 15:06:27 +00:00
|
|
|
|
2016-12-25 15:10:53 +00:00
|
|
|
def create_private_token(self):
|
|
|
|
from .authentication import PrivateToken
|
2016-12-20 15:06:27 +00:00
|
|
|
try:
|
2016-12-25 15:10:53 +00:00
|
|
|
token = PrivateToken.objects.get(user=self)
|
|
|
|
except PrivateToken.DoesNotExist:
|
|
|
|
token = PrivateToken.objects.create(user=self)
|
2016-12-20 15:06:27 +00:00
|
|
|
return token.key
|
|
|
|
|
2018-01-09 05:10:28 +00:00
|
|
|
def create_access_key(self):
|
|
|
|
from . import AccessKey
|
|
|
|
access_key = AccessKey.objects.create(user=self)
|
|
|
|
return access_key
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
def refresh_private_token(self):
|
2016-12-25 15:10:53 +00:00
|
|
|
from .authentication import PrivateToken
|
|
|
|
PrivateToken.objects.filter(user=self).delete()
|
|
|
|
return PrivateToken.objects.create(user=self)
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
def is_member_of(self, user_group):
|
|
|
|
if user_group in self.groups.all():
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def check_public_key(self, public_key):
|
2016-12-20 16:43:52 +00:00
|
|
|
if self.ssH_public_key == public_key:
|
2016-12-20 15:06:27 +00:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2017-01-26 12:24:50 +00:00
|
|
|
def avatar_url(self):
|
2017-12-21 03:31:13 +00:00
|
|
|
admin_default = settings.STATIC_URL + "img/avatar/admin.png"
|
|
|
|
user_default = settings.STATIC_URL + "img/avatar/user.png"
|
2017-01-26 12:24:50 +00:00
|
|
|
if self.avatar:
|
|
|
|
return self.avatar.url
|
2017-12-21 03:31:13 +00:00
|
|
|
if self.is_superuser:
|
|
|
|
return admin_default
|
2017-01-26 12:24:50 +00:00
|
|
|
else:
|
2017-12-21 03:31:13 +00:00
|
|
|
return user_default
|
2017-01-26 12:24:50 +00:00
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
def generate_reset_token(self):
|
2017-12-12 04:19:45 +00:00
|
|
|
return signer.sign_t({'reset': str(self.id), 'email': self.email}, expires_in=3600)
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
def to_json(self):
|
|
|
|
return OrderedDict({
|
|
|
|
'id': self.id,
|
|
|
|
'username': self.username,
|
|
|
|
'name': self.name,
|
|
|
|
'email': self.email,
|
|
|
|
'is_active': self.is_active,
|
|
|
|
'is_superuser': self.is_superuser,
|
|
|
|
'role': self.get_role_display(),
|
|
|
|
'groups': [group.name for group in self.groups.all()],
|
|
|
|
'wechat': self.wechat,
|
|
|
|
'phone': self.phone,
|
|
|
|
'comment': self.comment,
|
bugfix: 解决用户失效时间为空时,无法使用密码进行ssh登录跳板机的问题 (#659)
* bugfix: 解决用户失效时间为空时,无法使用密码进行ssh登录跳板机的问题
bugfix: 解决用户失效时间为空时,无法使用密码进行ssh登录跳板机的问题。
```
AttributeError at /api/users/v1/auth/
'NoneType' object has no attribute 'strftime'
Request Method: POST
Request URL: http://127.0.0.1:8080/api/users/v1/auth/
Django Version: 1.11.4
Python Executable: /opt/py3/bin/python
Python Version: 3.6.1
Python Path: ['/data/deployment/jumpserver/apps', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/opt/py3/lib/python3.6/site-packages', '/data/deployment/jumpserver', '/data/deployment/jumpserver/apps']
Server time: Wed, 30 Aug 2017 23:18:47 +0800
Installed Applications:
['users.apps.UsersConfig',
'assets.apps.AssetsConfig',
'perms.apps.PermsConfig',
'ops.apps.OpsConfig',
'audits.apps.AuditsConfig',
'common.apps.CommonConfig',
'applications.apps.ApplicationsConfig',
'rest_framework',
'rest_framework_swagger',
'django_filters',
'bootstrap3',
'captcha',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'jumpserver.middleware.TimezoneMiddleware',
'jumpserver.middleware.DemoMiddleware']
Traceback:
File "/opt/py3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/opt/py3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/opt/py3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/contextlib.py" in inner
53. return func(*args, **kwds)
File "/opt/py3/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/opt/py3/lib/python3.6/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/opt/py3/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
489. response = self.handle_exception(exc)
File "/opt/py3/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
449. self.raise_uncaught_exception(exc)
File "/opt/py3/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
486. response = handler(request, *args, **kwargs)
File "/data/deployment/jumpserver/apps/users/api.py" in post
166. return Response({'token': token, 'user': user.to_json()})
File "/data/deployment/jumpserver/apps/users/models/user.py" in to_json
207. 'date_expired': self.date_expired.strftime('%Y-%m-%d %H:%M:%S')
Exception Type: AttributeError at /api/users/v1/auth/
Exception Value: 'NoneType' object has no attribute 'strftime'
Request information:
USER: AnonymousUser
GET: No GET data
POST: No POST data
FILES: No FILES data
COOKIES: No cookie data
```
* bugfix: 个人信息页面个人信息pannel错位
bugfix: 个人信息页面个人信息pannel错位
2017-09-24 00:40:59 +00:00
|
|
|
'date_expired': self.date_expired.strftime('%Y-%m-%d %H:%M:%S') if self.date_expired is not None else None
|
2016-12-20 15:06:27 +00:00
|
|
|
})
|
|
|
|
|
2016-12-20 17:17:36 +00:00
|
|
|
@classmethod
|
|
|
|
def create_app_user(cls, name, comment):
|
2017-12-21 10:54:29 +00:00
|
|
|
app = cls.objects.create(
|
2017-12-25 04:22:49 +00:00
|
|
|
username=name, name=name, email='{}@local.domain'.format(name),
|
2017-12-21 10:54:29 +00:00
|
|
|
is_active=False, role='App', enable_otp=False, comment=comment,
|
|
|
|
is_first_login=False, created_by='System'
|
|
|
|
)
|
2018-01-09 05:10:28 +00:00
|
|
|
access_key = app.create_access_key()
|
2016-12-25 09:44:39 +00:00
|
|
|
return app, access_key
|
2016-12-20 17:17:36 +00:00
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
@classmethod
|
|
|
|
def validate_reset_token(cls, token):
|
|
|
|
try:
|
|
|
|
data = signer.unsign_t(token)
|
|
|
|
user_id = data.get('reset', None)
|
|
|
|
user_email = data.get('email', '')
|
|
|
|
user = cls.objects.get(id=user_id, email=user_email)
|
|
|
|
|
|
|
|
except (signing.BadSignature, cls.DoesNotExist):
|
|
|
|
user = None
|
|
|
|
return user
|
|
|
|
|
|
|
|
def reset_password(self, new_password):
|
|
|
|
self.set_password(new_password)
|
|
|
|
self.save()
|
|
|
|
|
2017-11-23 06:08:01 +00:00
|
|
|
def delete(self, using=None, keep_parents=False):
|
2016-12-20 16:43:52 +00:00
|
|
|
if self.pk == 1 or self.username == 'admin':
|
|
|
|
return
|
|
|
|
return super(User, self).delete()
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
class Meta:
|
2016-12-21 16:36:31 +00:00
|
|
|
ordering = ['username']
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
#: Use this method initial user
|
|
|
|
@classmethod
|
|
|
|
def initial(cls):
|
2018-01-12 07:43:26 +00:00
|
|
|
from .group import UserGroup
|
2016-12-20 15:06:27 +00:00
|
|
|
user = cls(username='admin',
|
|
|
|
email='admin@jumpserver.org',
|
|
|
|
name=_('Administrator'),
|
|
|
|
password_raw='admin',
|
|
|
|
role='Admin',
|
|
|
|
comment=_('Administrator is the super user of system'),
|
|
|
|
created_by=_('System'))
|
|
|
|
user.save()
|
|
|
|
user.groups.add(UserGroup.initial())
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def generate_fake(cls, count=100):
|
|
|
|
from random import seed, choice
|
|
|
|
import forgery_py
|
|
|
|
from django.db import IntegrityError
|
2018-01-12 07:43:26 +00:00
|
|
|
from .group import UserGroup
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
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()),
|
2017-11-23 06:08:01 +00:00
|
|
|
role=choice(list(dict(User.ROLE_CHOICES).keys())),
|
2016-12-20 15:06:27 +00:00
|
|
|
wechat=forgery_py.internet.user_name(True),
|
|
|
|
comment=forgery_py.lorem_ipsum.sentence(),
|
|
|
|
created_by=choice(cls.objects.all()).username)
|
|
|
|
try:
|
|
|
|
user.save()
|
|
|
|
except IntegrityError:
|
|
|
|
print('Duplicate Error, continue ...')
|
|
|
|
continue
|
|
|
|
user.groups.add(choice(UserGroup.objects.all()))
|
|
|
|
user.save()
|