2016-12-20 15:06:27 +00:00
|
|
|
|
#!/usr/bin/env python
|
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
2018-11-23 02:25:35 +00:00
|
|
|
|
import base64
|
2021-04-25 10:13:41 +00:00
|
|
|
|
import datetime
|
2022-12-05 10:54:12 +00:00
|
|
|
|
import random
|
|
|
|
|
import string
|
|
|
|
|
import uuid
|
2022-02-17 12:13:31 +00:00
|
|
|
|
from typing import Callable
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2023-08-07 09:00:01 +00:00
|
|
|
|
import sshpubkeys
|
2017-01-26 12:24:50 +00:00
|
|
|
|
from django.conf import settings
|
2021-10-18 10:41:41 +00:00
|
|
|
|
from django.contrib.auth.hashers import check_password
|
2022-12-05 10:54:12 +00:00
|
|
|
|
from django.contrib.auth.models import AbstractUser
|
|
|
|
|
from django.core.cache import cache
|
|
|
|
|
from django.db import models
|
2022-03-25 06:45:08 +00:00
|
|
|
|
from django.shortcuts import reverse
|
2022-12-05 10:54:12 +00:00
|
|
|
|
from django.utils import timezone
|
2022-11-04 06:29:15 +00:00
|
|
|
|
from django.utils.module_loading import import_string
|
2023-07-24 03:52:25 +00:00
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
|
from common.db import fields, models as jms_models
|
2022-03-25 06:45:08 +00:00
|
|
|
|
from common.utils import (
|
2022-12-05 10:54:12 +00:00
|
|
|
|
date_expired_default, get_logger, lazyproperty,
|
|
|
|
|
random_string, bulk_create_with_signal
|
|
|
|
|
)
|
|
|
|
|
from orgs.utils import current_org
|
|
|
|
|
from rbac.const import Scope
|
|
|
|
|
from ..signals import (
|
|
|
|
|
post_user_change_password, post_user_leave_org, pre_user_leave_org
|
2022-03-25 06:45:08 +00:00
|
|
|
|
)
|
2016-12-20 16:43:52 +00:00
|
|
|
|
|
2021-11-10 03:30:48 +00:00
|
|
|
|
__all__ = ['User', 'UserPasswordHistory']
|
2019-04-15 06:37:45 +00:00
|
|
|
|
|
|
|
|
|
logger = get_logger(__file__)
|
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
class AuthMixin:
|
2021-04-25 10:13:41 +00:00
|
|
|
|
date_password_last_updated: datetime.datetime
|
2021-11-10 03:30:48 +00:00
|
|
|
|
history_passwords: models.Manager
|
|
|
|
|
need_update_password: bool
|
|
|
|
|
public_key: str
|
2021-04-25 10:13:41 +00:00
|
|
|
|
is_local: bool
|
2022-02-17 12:13:31 +00:00
|
|
|
|
set_password: Callable
|
|
|
|
|
save: Callable
|
|
|
|
|
history_passwords: models.Manager
|
2023-08-08 02:16:23 +00:00
|
|
|
|
sect_cache_tpl = 'user_sect_{}'
|
2023-08-09 09:25:54 +00:00
|
|
|
|
id: str
|
2021-04-25 10:13:41 +00:00
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
|
@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_)
|
|
|
|
|
|
2018-09-03 03:24:25 +00:00
|
|
|
|
def set_password(self, raw_password):
|
2018-12-27 08:47:40 +00:00
|
|
|
|
if self.can_update_password():
|
2019-07-11 10:12:14 +00:00
|
|
|
|
self.date_password_last_updated = timezone.now()
|
2019-12-16 08:53:29 +00:00
|
|
|
|
post_user_change_password.send(self.__class__, user=self)
|
2019-07-11 10:12:14 +00:00
|
|
|
|
super().set_password(raw_password)
|
2018-12-27 08:47:40 +00:00
|
|
|
|
|
2020-05-28 09:47:18 +00:00
|
|
|
|
def set_public_key(self, public_key):
|
2020-06-04 09:02:43 +00:00
|
|
|
|
if self.can_update_ssh_key():
|
|
|
|
|
self.public_key = public_key
|
|
|
|
|
self.save()
|
2020-05-28 09:47:18 +00:00
|
|
|
|
|
2018-12-27 08:47:40 +00:00
|
|
|
|
def can_update_password(self):
|
|
|
|
|
return self.is_local
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
2019-07-24 04:50:39 +00:00
|
|
|
|
def can_update_ssh_key(self):
|
2019-07-26 02:46:43 +00:00
|
|
|
|
return self.can_use_ssh_key_login()
|
|
|
|
|
|
2021-04-26 02:21:22 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def can_use_ssh_key_login():
|
|
|
|
|
return settings.TERMINAL_PUBLIC_KEY_AUTH
|
2019-07-24 04:50:39 +00:00
|
|
|
|
|
2021-04-28 09:03:20 +00:00
|
|
|
|
def is_history_password(self, password):
|
|
|
|
|
allow_history_password_count = settings.OLD_PASSWORD_HISTORY_LIMIT_COUNT
|
2021-11-10 03:30:48 +00:00
|
|
|
|
history_passwords = self.history_passwords.all() \
|
2022-04-07 02:11:16 +00:00
|
|
|
|
.order_by('-date_created')[:int(allow_history_password_count)]
|
2021-04-28 09:03:20 +00:00
|
|
|
|
|
|
|
|
|
for history_password in history_passwords:
|
|
|
|
|
if check_password(password, history_password.password):
|
|
|
|
|
return True
|
|
|
|
|
else:
|
|
|
|
|
return False
|
|
|
|
|
|
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.
|
|
|
|
|
"""
|
2019-06-25 03:22:17 +00:00
|
|
|
|
if self.public_key:
|
2017-02-09 13:19:49 +00:00
|
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
|
2018-12-17 12:09:25 +00:00
|
|
|
|
@property
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def public_key_obj(self):
|
|
|
|
|
class PubKey(object):
|
|
|
|
|
def __getattr__(self, item):
|
|
|
|
|
return ''
|
|
|
|
|
|
|
|
|
|
if self.public_key:
|
|
|
|
|
try:
|
|
|
|
|
return sshpubkeys.SSHKey(self.public_key)
|
|
|
|
|
except (TabError, TypeError):
|
|
|
|
|
pass
|
|
|
|
|
return PubKey()
|
|
|
|
|
|
2020-05-28 09:47:18 +00:00
|
|
|
|
def get_public_key_comment(self):
|
|
|
|
|
return self.public_key_obj.comment
|
|
|
|
|
|
|
|
|
|
def get_public_key_hash_md5(self):
|
|
|
|
|
if not callable(self.public_key_obj.hash_md5):
|
|
|
|
|
return ''
|
2020-06-03 04:32:52 +00:00
|
|
|
|
try:
|
|
|
|
|
return self.public_key_obj.hash_md5()
|
|
|
|
|
except:
|
|
|
|
|
return ''
|
2020-05-28 09:47:18 +00:00
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def reset_password(self, new_password):
|
|
|
|
|
self.set_password(new_password)
|
2021-04-28 11:25:30 +00:00
|
|
|
|
self.need_update_password = False
|
2019-07-12 07:43:36 +00:00
|
|
|
|
self.save()
|
2018-12-17 12:09:25 +00:00
|
|
|
|
|
|
|
|
|
@property
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def date_password_expired(self):
|
|
|
|
|
interval = settings.SECURITY_PASSWORD_EXPIRATION_TIME
|
|
|
|
|
date_expired = self.date_password_last_updated + timezone.timedelta(
|
|
|
|
|
days=int(interval))
|
|
|
|
|
return date_expired
|
2018-12-17 12:09:25 +00:00
|
|
|
|
|
|
|
|
|
@property
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def password_expired_remain_days(self):
|
|
|
|
|
date_remain = self.date_password_expired - timezone.now()
|
|
|
|
|
return date_remain.days
|
2018-12-17 12:09:25 +00:00
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
|
@property
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def password_has_expired(self):
|
|
|
|
|
if self.is_local and self.password_expired_remain_days < 0:
|
2016-12-20 15:06:27 +00:00
|
|
|
|
return True
|
2019-07-11 10:12:14 +00:00
|
|
|
|
return False
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
|
|
@property
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def password_will_expired(self):
|
2019-07-30 04:52:45 +00:00
|
|
|
|
if self.is_local and 0 <= self.password_expired_remain_days < 5:
|
2016-12-20 15:06:27 +00:00
|
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
|
2019-11-11 04:43:00 +00:00
|
|
|
|
@staticmethod
|
2023-08-07 09:00:01 +00:00
|
|
|
|
def get_public_key_md5(key):
|
|
|
|
|
try:
|
|
|
|
|
key_obj = sshpubkeys.SSHKey(key)
|
|
|
|
|
return key_obj.hash_md5()
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return ''
|
2019-11-11 04:43:00 +00:00
|
|
|
|
|
|
|
|
|
def check_public_key(self, key):
|
|
|
|
|
if not self.public_key:
|
|
|
|
|
return False
|
2023-08-07 09:00:01 +00:00
|
|
|
|
key_md5 = self.get_public_key_md5(key)
|
|
|
|
|
if not key_md5:
|
2019-11-11 04:43:00 +00:00
|
|
|
|
return False
|
2023-08-07 09:00:01 +00:00
|
|
|
|
self_key_md5 = self.get_public_key_md5(self.public_key)
|
|
|
|
|
return key_md5 == self_key_md5
|
2019-11-11 04:43:00 +00:00
|
|
|
|
|
2023-08-08 02:16:23 +00:00
|
|
|
|
def cache_login_password_if_need(self, password):
|
|
|
|
|
from common.utils import signer
|
|
|
|
|
if not settings.CACHE_LOGIN_PASSWORD_ENABLED:
|
|
|
|
|
return
|
|
|
|
|
backend = getattr(self, 'backend', '')
|
|
|
|
|
if backend.lower().find('ldap') < 0:
|
|
|
|
|
return
|
|
|
|
|
if not password:
|
|
|
|
|
return
|
|
|
|
|
key = self.sect_cache_tpl.format(self.id)
|
|
|
|
|
ttl = settings.CACHE_LOGIN_PASSWORD_TTL
|
|
|
|
|
if not isinstance(ttl, int) or ttl <= 0:
|
|
|
|
|
return
|
|
|
|
|
secret = signer.sign(password)
|
|
|
|
|
cache.set(key, secret, ttl)
|
|
|
|
|
|
|
|
|
|
def get_cached_password_if_has(self):
|
|
|
|
|
from common.utils import signer
|
|
|
|
|
if not settings.CACHE_LOGIN_PASSWORD_ENABLED:
|
|
|
|
|
return ''
|
|
|
|
|
key = self.sect_cache_tpl.format(self.id)
|
|
|
|
|
secret = cache.get(key)
|
|
|
|
|
if not secret:
|
|
|
|
|
return ''
|
|
|
|
|
password = signer.unsign(secret)
|
|
|
|
|
return password
|
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
class RoleManager(models.Manager):
|
|
|
|
|
scope = None
|
2022-02-22 04:51:06 +00:00
|
|
|
|
_cache = None
|
2020-07-20 02:42:22 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def __init__(self, user, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
self.user = user
|
2022-03-21 08:40:14 +00:00
|
|
|
|
|
2022-03-25 06:45:08 +00:00
|
|
|
|
@lazyproperty
|
|
|
|
|
def role_binding_cls(self):
|
2022-03-21 08:40:14 +00:00
|
|
|
|
from rbac.models import SystemRoleBinding, OrgRoleBinding
|
2022-03-23 02:56:23 +00:00
|
|
|
|
if self.scope == Scope.org:
|
2022-03-21 08:40:14 +00:00
|
|
|
|
return OrgRoleBinding
|
|
|
|
|
else:
|
|
|
|
|
return SystemRoleBinding
|
|
|
|
|
|
2022-03-25 06:45:08 +00:00
|
|
|
|
@lazyproperty
|
|
|
|
|
def role_cls(self):
|
2022-03-21 08:40:14 +00:00
|
|
|
|
from rbac.models import SystemRole, OrgRole
|
2022-03-23 02:56:23 +00:00
|
|
|
|
if self.scope == Scope.org:
|
2022-03-21 08:40:14 +00:00
|
|
|
|
return OrgRole
|
|
|
|
|
else:
|
|
|
|
|
return SystemRole
|
2020-07-20 02:42:22 +00:00
|
|
|
|
|
|
|
|
|
@property
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def display(self):
|
|
|
|
|
roles = sorted(list(self.all()), key=lambda r: r.scope)
|
|
|
|
|
roles_display = [role.display_name for role in roles]
|
|
|
|
|
return ', '.join(roles_display)
|
2020-05-13 03:05:58 +00:00
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
|
@property
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def role_bindings(self):
|
2022-03-21 08:40:14 +00:00
|
|
|
|
queryset = self.role_binding_cls.objects.filter(user=self.user)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
if self.scope:
|
|
|
|
|
queryset = queryset.filter(scope=self.scope)
|
|
|
|
|
return queryset
|
|
|
|
|
|
2022-02-22 04:51:06 +00:00
|
|
|
|
def _get_queryset(self):
|
2022-03-21 08:40:14 +00:00
|
|
|
|
queryset = self.role_binding_cls.get_user_roles(self.user)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
if self.scope:
|
|
|
|
|
queryset = queryset.filter(scope=self.scope)
|
|
|
|
|
return queryset
|
|
|
|
|
|
2022-02-22 04:51:06 +00:00
|
|
|
|
def get_queryset(self):
|
|
|
|
|
if self._cache is not None:
|
|
|
|
|
return self._cache
|
|
|
|
|
return self._get_queryset()
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def clear(self):
|
|
|
|
|
if not self.scope:
|
|
|
|
|
return
|
|
|
|
|
return self.role_bindings.delete()
|
|
|
|
|
|
2022-03-21 08:40:14 +00:00
|
|
|
|
def _clean_roles(self, roles_or_ids):
|
|
|
|
|
if not roles_or_ids:
|
|
|
|
|
return
|
|
|
|
|
is_model = isinstance(roles_or_ids[0], models.Model)
|
|
|
|
|
if not is_model:
|
|
|
|
|
roles = self.role_cls.objects.filter(id__in=roles_or_ids)
|
|
|
|
|
else:
|
|
|
|
|
roles = roles_or_ids
|
|
|
|
|
roles = list([r for r in roles if r.scope == self.scope])
|
|
|
|
|
return roles
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def add(self, *roles):
|
2022-03-21 08:40:14 +00:00
|
|
|
|
if not roles:
|
|
|
|
|
return
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
2022-03-21 08:40:14 +00:00
|
|
|
|
roles = self._clean_roles(roles)
|
|
|
|
|
old_ids = self.role_bindings.values_list('role', flat=True)
|
|
|
|
|
need_adds = [r for r in roles if r.id not in old_ids]
|
|
|
|
|
|
|
|
|
|
items = []
|
|
|
|
|
for role in need_adds:
|
2022-03-25 06:45:08 +00:00
|
|
|
|
kwargs = {'role': role, 'user': self.user, 'scope': self.scope}
|
|
|
|
|
if self.scope == Scope.org:
|
|
|
|
|
if current_org.is_root():
|
|
|
|
|
continue
|
|
|
|
|
else:
|
|
|
|
|
kwargs['org_id'] = current_org.id
|
2022-03-21 08:40:14 +00:00
|
|
|
|
items.append(self.role_binding_cls(**kwargs))
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
try:
|
2022-03-25 06:45:08 +00:00
|
|
|
|
result = bulk_create_with_signal(self.role_binding_cls, items, ignore_conflicts=True)
|
|
|
|
|
self.user.expire_users_rbac_perms_cache()
|
|
|
|
|
return result
|
2022-02-17 12:13:31 +00:00
|
|
|
|
except Exception as e:
|
2022-10-19 03:39:11 +00:00
|
|
|
|
logger.error('\tCreate role binding error: {}'.format(e))
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2022-03-21 08:40:14 +00:00
|
|
|
|
def set(self, roles, clear=False):
|
|
|
|
|
if clear:
|
|
|
|
|
self.clear()
|
|
|
|
|
self.add(*roles)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
role_ids = set([r.id for r in roles])
|
|
|
|
|
old_ids = self.role_bindings.values_list('role', flat=True)
|
|
|
|
|
old_ids = set(old_ids)
|
|
|
|
|
|
|
|
|
|
del_ids = old_ids - role_ids
|
|
|
|
|
add_ids = role_ids - old_ids
|
|
|
|
|
self.remove(*del_ids)
|
|
|
|
|
self.add(*add_ids)
|
|
|
|
|
|
|
|
|
|
def remove(self, *roles):
|
|
|
|
|
if not roles:
|
|
|
|
|
return
|
|
|
|
|
roles = self._clean_roles(roles)
|
2022-03-25 06:45:08 +00:00
|
|
|
|
deleted = self.role_bindings.filter(role__in=roles).delete()
|
|
|
|
|
self.user.expire_users_rbac_perms_cache()
|
|
|
|
|
return deleted
|
2019-09-12 10:56:26 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def cache_set(self, roles):
|
2022-02-22 04:51:06 +00:00
|
|
|
|
query = self._get_queryset()
|
|
|
|
|
query._result_cache = roles
|
|
|
|
|
self._cache = query
|
2019-09-12 10:56:26 +00:00
|
|
|
|
|
2022-03-21 08:40:14 +00:00
|
|
|
|
@property
|
|
|
|
|
def builtin_role(self):
|
|
|
|
|
from rbac.builtin import BuiltinRole
|
|
|
|
|
return BuiltinRole
|
|
|
|
|
|
2020-07-09 07:41:02 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
class OrgRoleManager(RoleManager):
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
from rbac.const import Scope
|
|
|
|
|
self.scope = Scope.org
|
2022-03-22 08:14:25 +00:00
|
|
|
|
super().__init__(*args, **kwargs)
|
2019-09-12 10:56:26 +00:00
|
|
|
|
|
2018-07-13 07:05:46 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
class SystemRoleManager(RoleManager):
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
from rbac.const import Scope
|
|
|
|
|
self.scope = Scope.system
|
2022-03-22 08:14:25 +00:00
|
|
|
|
super().__init__(*args, **kwargs)
|
2019-09-12 10:56:26 +00:00
|
|
|
|
|
2022-03-25 06:45:08 +00:00
|
|
|
|
def remove_role_system_admin(self):
|
|
|
|
|
role = self.builtin_role.system_admin.get_role()
|
|
|
|
|
return self.remove(role)
|
|
|
|
|
|
|
|
|
|
def add_role_system_admin(self):
|
|
|
|
|
role = self.builtin_role.system_admin.get_role()
|
|
|
|
|
return self.add(role)
|
|
|
|
|
|
|
|
|
|
def add_role_system_user(self):
|
|
|
|
|
role = self.builtin_role.system_user.get_role()
|
|
|
|
|
return self.add(role)
|
|
|
|
|
|
|
|
|
|
def add_role_system_component(self):
|
|
|
|
|
role = self.builtin_role.system_component.get_role()
|
|
|
|
|
self.add(role)
|
|
|
|
|
|
2019-09-12 10:56:26 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
class RoleMixin:
|
|
|
|
|
objects: models.Manager
|
|
|
|
|
is_authenticated: bool
|
|
|
|
|
is_valid: bool
|
2022-03-08 05:35:40 +00:00
|
|
|
|
id: str
|
2022-02-17 12:13:31 +00:00
|
|
|
|
_org_roles = None
|
|
|
|
|
_system_roles = None
|
2023-02-07 08:21:26 +00:00
|
|
|
|
PERM_CACHE_KEY = 'USER_PERMS_ROLES_{}_{}'
|
2023-02-08 02:30:06 +00:00
|
|
|
|
PERM_ORG_KEY = 'USER_PERMS_ORG_{}'
|
2022-03-21 08:40:14 +00:00
|
|
|
|
_is_superuser = None
|
2022-03-21 10:06:33 +00:00
|
|
|
|
_update_superuser = False
|
2018-07-13 07:05:46 +00:00
|
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
|
@lazyproperty
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def roles(self):
|
|
|
|
|
return RoleManager(self)
|
2019-06-19 02:47:26 +00:00
|
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
|
@lazyproperty
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def org_roles(self):
|
|
|
|
|
return OrgRoleManager(self)
|
2019-07-01 03:22:05 +00:00
|
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
|
@lazyproperty
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def system_roles(self):
|
|
|
|
|
return SystemRoleManager(self)
|
2019-09-12 10:56:26 +00:00
|
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
|
@lazyproperty
|
2023-02-07 08:21:26 +00:00
|
|
|
|
def console_orgs(self):
|
2023-02-08 02:30:06 +00:00
|
|
|
|
return self.cached_orgs['console_orgs']
|
2023-02-07 08:21:26 +00:00
|
|
|
|
|
|
|
|
|
@lazyproperty
|
|
|
|
|
def audit_orgs(self):
|
2023-02-08 02:30:06 +00:00
|
|
|
|
return self.cached_orgs['audit_orgs']
|
2023-02-07 08:21:26 +00:00
|
|
|
|
|
|
|
|
|
@lazyproperty
|
|
|
|
|
def workbench_orgs(self):
|
2023-02-08 02:30:06 +00:00
|
|
|
|
return self.cached_orgs['workbench_orgs']
|
2023-02-07 08:21:26 +00:00
|
|
|
|
|
2023-08-08 02:16:23 +00:00
|
|
|
|
@lazyproperty
|
|
|
|
|
def joined_orgs(self):
|
|
|
|
|
from rbac.models import RoleBinding
|
|
|
|
|
return RoleBinding.get_user_joined_orgs(self)
|
|
|
|
|
|
2023-02-07 08:21:26 +00:00
|
|
|
|
@lazyproperty
|
2023-02-08 02:30:06 +00:00
|
|
|
|
def cached_orgs(self):
|
2023-02-07 08:21:26 +00:00
|
|
|
|
from rbac.models import RoleBinding
|
2023-02-08 02:30:06 +00:00
|
|
|
|
key = self.PERM_ORG_KEY.format(self.id)
|
2023-02-07 08:21:26 +00:00
|
|
|
|
data = cache.get(key)
|
|
|
|
|
if data:
|
|
|
|
|
return data
|
|
|
|
|
data = {
|
|
|
|
|
'console_orgs': RoleBinding.get_user_has_the_perm_orgs('rbac.view_console', self),
|
|
|
|
|
'audit_orgs': RoleBinding.get_user_has_the_perm_orgs('rbac.view_audit', self),
|
|
|
|
|
'workbench_orgs': RoleBinding.get_user_has_the_perm_orgs('rbac.view_workbench', self),
|
2023-02-08 02:30:06 +00:00
|
|
|
|
}
|
|
|
|
|
cache.set(key, data, 60 * 60)
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
@lazyproperty
|
|
|
|
|
def cached_role_and_perms(self):
|
|
|
|
|
key = self.PERM_CACHE_KEY.format(self.id, current_org.id)
|
|
|
|
|
data = cache.get(key)
|
|
|
|
|
if data:
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
data = {
|
2023-02-07 08:21:26 +00:00
|
|
|
|
'org_roles': self.org_roles.all(),
|
|
|
|
|
'system_roles': self.system_roles.all(),
|
|
|
|
|
'perms': self.get_all_permissions(),
|
|
|
|
|
}
|
|
|
|
|
cache.set(key, data, 60 * 60)
|
|
|
|
|
return data
|
2022-03-08 05:35:40 +00:00
|
|
|
|
|
2022-03-17 06:08:16 +00:00
|
|
|
|
def expire_rbac_perms_cache(self):
|
2022-03-08 05:35:40 +00:00
|
|
|
|
key = self.PERM_CACHE_KEY.format(self.id, '*')
|
|
|
|
|
cache.delete_pattern(key)
|
2023-02-08 02:30:06 +00:00
|
|
|
|
key = self.PERM_ORG_KEY.format(self.id)
|
|
|
|
|
cache.delete(key)
|
2019-11-25 07:30:11 +00:00
|
|
|
|
|
2022-03-17 06:08:16 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def expire_users_rbac_perms_cache(cls):
|
|
|
|
|
key = cls.PERM_CACHE_KEY.format('*', '*')
|
|
|
|
|
cache.delete_pattern(key)
|
2023-02-08 02:30:06 +00:00
|
|
|
|
key = cls.PERM_ORG_KEY.format('*')
|
|
|
|
|
cache.delete_pattern(key)
|
2022-03-17 06:08:16 +00:00
|
|
|
|
|
2023-02-07 08:21:26 +00:00
|
|
|
|
@lazyproperty
|
|
|
|
|
def perms(self):
|
|
|
|
|
return self.cached_role_and_perms['perms']
|
|
|
|
|
|
2022-03-21 08:40:14 +00:00
|
|
|
|
@property
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def is_superuser(self):
|
2022-02-22 03:48:06 +00:00
|
|
|
|
"""
|
2022-02-22 04:51:06 +00:00
|
|
|
|
由于这里用了 cache ,所以不能改成 self.system_roles.filter().exists() 会查询的
|
2022-02-22 03:48:06 +00:00
|
|
|
|
"""
|
2022-03-30 03:08:50 +00:00
|
|
|
|
if self._is_superuser is not None:
|
2022-03-21 08:40:14 +00:00
|
|
|
|
return self._is_superuser
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
from rbac.builtin import BuiltinRole
|
2022-02-22 03:48:06 +00:00
|
|
|
|
ids = [str(r.id) for r in self.system_roles.all()]
|
|
|
|
|
yes = BuiltinRole.system_admin.id in ids
|
2022-03-21 08:40:14 +00:00
|
|
|
|
self._is_superuser = yes
|
2022-02-22 03:48:06 +00:00
|
|
|
|
return yes
|
2022-02-18 08:25:54 +00:00
|
|
|
|
|
2022-03-21 08:40:14 +00:00
|
|
|
|
@is_superuser.setter
|
|
|
|
|
def is_superuser(self, value):
|
2022-03-21 10:06:33 +00:00
|
|
|
|
self._is_superuser = value
|
|
|
|
|
self._update_superuser = True
|
2022-03-21 08:40:14 +00:00
|
|
|
|
if value:
|
|
|
|
|
self.system_roles.add_role_system_admin()
|
|
|
|
|
else:
|
|
|
|
|
self.system_roles.remove_role_system_admin()
|
|
|
|
|
|
2022-02-18 08:25:54 +00:00
|
|
|
|
@lazyproperty
|
|
|
|
|
def is_org_admin(self):
|
|
|
|
|
from rbac.builtin import BuiltinRole
|
|
|
|
|
if self.is_superuser:
|
|
|
|
|
return True
|
2022-02-22 03:48:06 +00:00
|
|
|
|
ids = [str(r.id) for r in self.org_roles.all()]
|
|
|
|
|
yes = BuiltinRole.org_admin.id in ids
|
|
|
|
|
return yes
|
2016-12-25 15:10:53 +00:00
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
|
@property
|
|
|
|
|
def is_staff(self):
|
2022-02-17 12:13:31 +00:00
|
|
|
|
return self.is_authenticated and self.is_valid
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
|
|
@is_staff.setter
|
|
|
|
|
def is_staff(self, value):
|
|
|
|
|
pass
|
|
|
|
|
|
2022-03-30 11:07:49 +00:00
|
|
|
|
service_account_email_suffix = '@local.domain'
|
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
@classmethod
|
2022-03-30 11:07:49 +00:00
|
|
|
|
def create_service_account(cls, name, email, comment):
|
2019-07-11 10:12:14 +00:00
|
|
|
|
app = cls.objects.create(
|
2022-03-30 11:07:49 +00:00
|
|
|
|
username=name, name=name, email=email,
|
2022-02-18 08:25:54 +00:00
|
|
|
|
comment=comment, is_first_login=False,
|
|
|
|
|
created_by='System', is_service_account=True,
|
2019-07-11 10:12:14 +00:00
|
|
|
|
)
|
|
|
|
|
access_key = app.create_access_key()
|
|
|
|
|
return app, access_key
|
2018-11-22 10:02:12 +00:00
|
|
|
|
|
2019-12-09 03:50:52 +00:00
|
|
|
|
def remove(self):
|
2021-03-02 06:57:48 +00:00
|
|
|
|
if current_org.is_root():
|
2019-12-09 03:50:52 +00:00
|
|
|
|
return
|
2022-02-17 12:13:31 +00:00
|
|
|
|
kwargs = dict(sender=self.__class__, user=self, org=current_org)
|
|
|
|
|
pre_user_leave_org.send(**kwargs)
|
|
|
|
|
self.org_roles.clear()
|
|
|
|
|
post_user_leave_org.send(**kwargs)
|
2019-12-09 03:50:52 +00:00
|
|
|
|
|
2020-12-29 16:19:59 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def get_super_admins(cls):
|
2022-02-17 12:13:31 +00:00
|
|
|
|
from rbac.models import Role, RoleBinding
|
|
|
|
|
system_admin = Role.BuiltinRole.system_admin.get_role()
|
|
|
|
|
return RoleBinding.get_role_users(system_admin)
|
2020-12-29 16:19:59 +00:00
|
|
|
|
|
|
|
|
|
@classmethod
|
2022-03-10 03:26:34 +00:00
|
|
|
|
def get_org_admins(cls):
|
2022-02-17 12:13:31 +00:00
|
|
|
|
from rbac.models import Role, RoleBinding
|
|
|
|
|
org_admin = Role.BuiltinRole.org_admin.get_role()
|
|
|
|
|
return RoleBinding.get_role_users(org_admin)
|
|
|
|
|
|
2022-03-10 03:26:34 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def get_super_and_org_admins(cls):
|
|
|
|
|
super_admins = cls.get_super_admins()
|
|
|
|
|
org_admins = cls.get_org_admins()
|
|
|
|
|
admins = org_admins | super_admins
|
|
|
|
|
return admins.distinct()
|
|
|
|
|
|
2022-03-09 03:17:28 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def filter_not_service_account(queryset):
|
2022-03-07 12:09:52 +00:00
|
|
|
|
return queryset.filter(is_service_account=False)
|
2020-12-29 16:19:59 +00:00
|
|
|
|
|
2022-03-09 03:17:28 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def get_nature_users(cls):
|
|
|
|
|
queryset = cls.objects.all()
|
|
|
|
|
return cls.filter_not_service_account(queryset)
|
|
|
|
|
|
2020-12-29 16:19:59 +00:00
|
|
|
|
@classmethod
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def get_org_users(cls, org=None):
|
2022-03-09 03:17:28 +00:00
|
|
|
|
queryset = cls.objects.all()
|
2022-02-17 12:13:31 +00:00
|
|
|
|
if org is None:
|
|
|
|
|
org = current_org
|
|
|
|
|
if not org.is_root():
|
2022-04-19 10:06:52 +00:00
|
|
|
|
queryset = org.get_members()
|
2022-03-09 03:17:28 +00:00
|
|
|
|
queryset = cls.filter_not_service_account(queryset)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
|
|
def get_all_permissions(self):
|
|
|
|
|
from rbac.models import RoleBinding
|
|
|
|
|
perms = RoleBinding.get_user_perms(self)
|
|
|
|
|
return perms
|
2020-12-29 16:19:59 +00:00
|
|
|
|
|
2018-11-22 10:02:12 +00:00
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
class TokenMixin:
|
|
|
|
|
CACHE_KEY_USER_RESET_PASSWORD_PREFIX = "_KEY_USER_RESET_PASSWORD_{}"
|
|
|
|
|
email = ''
|
|
|
|
|
id = None
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def private_token(self):
|
2019-08-21 12:27:21 +00:00
|
|
|
|
return self.create_private_token()
|
2019-03-05 11:47:14 +00:00
|
|
|
|
|
|
|
|
|
def create_private_token(self):
|
|
|
|
|
from authentication.models import PrivateToken
|
2019-08-21 12:27:21 +00:00
|
|
|
|
token, created = PrivateToken.objects.get_or_create(user=self)
|
2019-03-05 11:47:14 +00:00
|
|
|
|
return token
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
def delete_private_token(self):
|
|
|
|
|
from authentication.models import PrivateToken
|
|
|
|
|
PrivateToken.objects.filter(user=self).delete()
|
|
|
|
|
|
2018-11-23 02:25:35 +00:00
|
|
|
|
def refresh_private_token(self):
|
2019-08-21 12:27:21 +00:00
|
|
|
|
self.delete_private_token()
|
2019-03-05 11:47:14 +00:00
|
|
|
|
return self.create_private_token()
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
|
def create_bearer_token(self, request=None):
|
|
|
|
|
expiration = settings.TOKEN_EXPIRATION or 3600
|
|
|
|
|
if request:
|
|
|
|
|
remote_addr = request.META.get('REMOTE_ADDR', '')
|
|
|
|
|
else:
|
|
|
|
|
remote_addr = '0.0.0.0'
|
|
|
|
|
if not isinstance(remote_addr, bytes):
|
|
|
|
|
remote_addr = remote_addr.encode("utf-8")
|
|
|
|
|
remote_addr = base64.b16encode(remote_addr) # .replace(b'=', '')
|
2019-03-04 12:45:57 +00:00
|
|
|
|
cache_key = '%s_%s' % (self.id, remote_addr)
|
|
|
|
|
token = cache.get(cache_key)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
if not token:
|
2021-03-01 10:40:07 +00:00
|
|
|
|
token = random_string(36)
|
2019-02-19 02:29:25 +00:00
|
|
|
|
cache.set(token, self.id, expiration)
|
|
|
|
|
cache.set('%s_%s' % (self.id, remote_addr), token, expiration)
|
2019-08-21 12:27:21 +00:00
|
|
|
|
date_expired = timezone.now() + timezone.timedelta(seconds=expiration)
|
|
|
|
|
return token, date_expired
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
|
def refresh_bearer_token(self, token):
|
|
|
|
|
pass
|
|
|
|
|
|
2018-01-09 05:10:28 +00:00
|
|
|
|
def create_access_key(self):
|
2019-03-04 09:07:51 +00:00
|
|
|
|
access_key = self.access_keys.create()
|
2018-01-09 05:10:28 +00:00
|
|
|
|
return access_key
|
|
|
|
|
|
2018-11-23 02:25:35 +00:00
|
|
|
|
@property
|
|
|
|
|
def access_key(self):
|
|
|
|
|
return self.access_keys.first()
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
|
|
|
|
def generate_reset_token(self):
|
2019-04-15 06:37:45 +00:00
|
|
|
|
letter = string.ascii_letters + string.digits
|
2019-06-25 03:22:17 +00:00
|
|
|
|
token = ''.join([random.choice(letter) for _ in range(50)])
|
2019-04-15 06:37:45 +00:00
|
|
|
|
self.set_cache(token)
|
|
|
|
|
return token
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def validate_reset_password_token(cls, token):
|
2020-09-29 07:31:45 +00:00
|
|
|
|
if not token:
|
|
|
|
|
return None
|
|
|
|
|
key = cls.CACHE_KEY_USER_RESET_PASSWORD_PREFIX.format(token)
|
|
|
|
|
value = cache.get(key)
|
|
|
|
|
if not value:
|
|
|
|
|
return None
|
2019-04-15 06:37:45 +00:00
|
|
|
|
try:
|
|
|
|
|
user_id = value.get('id', '')
|
|
|
|
|
email = value.get('email', '')
|
|
|
|
|
user = cls.objects.get(id=user_id, email=email)
|
2020-09-29 07:31:45 +00:00
|
|
|
|
return user
|
2019-04-15 06:37:45 +00:00
|
|
|
|
except (AttributeError, cls.DoesNotExist) as e:
|
|
|
|
|
logger.error(e, exc_info=True)
|
2020-09-29 07:31:45 +00:00
|
|
|
|
return None
|
2019-04-15 06:37:45 +00:00
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def set_cache(self, token):
|
|
|
|
|
key = self.CACHE_KEY_USER_RESET_PASSWORD_PREFIX.format(token)
|
|
|
|
|
cache.set(key, {'id': self.id, 'email': self.email}, 3600)
|
|
|
|
|
|
2019-04-15 06:37:45 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def expired_reset_password_token(cls, token):
|
|
|
|
|
key = cls.CACHE_KEY_USER_RESET_PASSWORD_PREFIX.format(token)
|
|
|
|
|
cache.delete(key)
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
|
|
|
|
|
class MFAMixin:
|
2019-11-18 08:30:26 +00:00
|
|
|
|
mfa_level = 0
|
2019-07-11 10:12:14 +00:00
|
|
|
|
otp_secret_key = ''
|
2019-11-18 08:30:26 +00:00
|
|
|
|
MFA_LEVEL_CHOICES = (
|
2019-07-11 10:12:14 +00:00
|
|
|
|
(0, _('Disable')),
|
|
|
|
|
(1, _('Enable')),
|
|
|
|
|
(2, _("Force enable")),
|
|
|
|
|
)
|
2021-07-30 07:19:00 +00:00
|
|
|
|
is_org_admin: bool
|
2021-09-16 11:06:16 +00:00
|
|
|
|
username: str
|
2022-02-17 12:13:31 +00:00
|
|
|
|
phone: str
|
2019-07-11 10:12:14 +00:00
|
|
|
|
|
2018-04-10 13:02:07 +00:00
|
|
|
|
@property
|
2019-11-18 08:30:26 +00:00
|
|
|
|
def mfa_enabled(self):
|
2021-07-30 07:19:00 +00:00
|
|
|
|
if self.mfa_force_enabled:
|
|
|
|
|
return True
|
|
|
|
|
return self.mfa_level > 0
|
2018-04-10 13:02:07 +00:00
|
|
|
|
|
2018-04-18 04:48:07 +00:00
|
|
|
|
@property
|
2019-11-18 08:30:26 +00:00
|
|
|
|
def mfa_force_enabled(self):
|
2021-11-10 03:30:48 +00:00
|
|
|
|
force_level = settings.SECURITY_MFA_AUTH
|
|
|
|
|
if force_level in [True, 1]:
|
2021-07-30 07:19:00 +00:00
|
|
|
|
return True
|
2021-11-10 03:30:48 +00:00
|
|
|
|
# 2 管理员强制开启
|
|
|
|
|
if force_level == 2 and self.is_org_admin:
|
2018-06-06 07:35:26 +00:00
|
|
|
|
return True
|
2019-11-18 08:30:26 +00:00
|
|
|
|
return self.mfa_level == 2
|
2018-04-18 04:48:07 +00:00
|
|
|
|
|
2019-11-18 08:30:26 +00:00
|
|
|
|
def enable_mfa(self):
|
|
|
|
|
if not self.mfa_level == 2:
|
|
|
|
|
self.mfa_level = 1
|
2018-04-10 13:04:56 +00:00
|
|
|
|
|
2019-11-18 08:30:26 +00:00
|
|
|
|
def force_enable_mfa(self):
|
|
|
|
|
self.mfa_level = 2
|
2018-04-10 13:04:56 +00:00
|
|
|
|
|
2019-11-18 08:30:26 +00:00
|
|
|
|
def disable_mfa(self):
|
|
|
|
|
self.mfa_level = 0
|
2021-08-24 06:20:54 +00:00
|
|
|
|
|
2021-11-10 03:30:48 +00:00
|
|
|
|
def no_active_mfa(self):
|
|
|
|
|
return len(self.active_mfa_backends) == 0
|
2021-08-24 06:20:54 +00:00
|
|
|
|
|
2021-11-10 03:30:48 +00:00
|
|
|
|
@lazyproperty
|
|
|
|
|
def active_mfa_backends(self):
|
|
|
|
|
backends = self.get_user_mfa_backends(self)
|
|
|
|
|
active_backends = [b for b in backends if b.is_active()]
|
|
|
|
|
return active_backends
|
2021-09-09 12:12:52 +00:00
|
|
|
|
|
2021-11-10 03:30:48 +00:00
|
|
|
|
@property
|
|
|
|
|
def active_mfa_backends_mapper(self):
|
|
|
|
|
return {b.name: b for b in self.active_mfa_backends}
|
2021-09-09 12:12:52 +00:00
|
|
|
|
|
2021-11-10 03:30:48 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def get_user_mfa_backends(user):
|
2022-11-04 06:29:15 +00:00
|
|
|
|
backends = []
|
|
|
|
|
for cls in settings.MFA_BACKENDS:
|
|
|
|
|
cls = import_string(cls)
|
|
|
|
|
if cls.global_enabled():
|
|
|
|
|
backends.append(cls(user))
|
2021-11-10 03:30:48 +00:00
|
|
|
|
return backends
|
|
|
|
|
|
2021-11-15 10:36:22 +00:00
|
|
|
|
def get_active_mfa_backend_by_type(self, mfa_type):
|
|
|
|
|
backend = self.get_mfa_backend_by_type(mfa_type)
|
|
|
|
|
if not backend or not backend.is_active():
|
|
|
|
|
return None
|
|
|
|
|
return backend
|
|
|
|
|
|
2021-11-10 03:30:48 +00:00
|
|
|
|
def get_mfa_backend_by_type(self, mfa_type):
|
2021-11-15 10:36:22 +00:00
|
|
|
|
mfa_mapper = {b.name: b for b in self.get_user_mfa_backends(self)}
|
2021-11-10 03:30:48 +00:00
|
|
|
|
backend = mfa_mapper.get(mfa_type)
|
|
|
|
|
if not backend:
|
|
|
|
|
return None
|
|
|
|
|
return backend
|
2019-11-18 08:30:26 +00:00
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2023-05-18 05:14:32 +00:00
|
|
|
|
class JSONFilterMixin:
|
|
|
|
|
"""
|
|
|
|
|
users = JSONManyToManyField('users.User', blank=True, null=True)
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def get_json_filter_attr_q(name, value, match):
|
|
|
|
|
from rbac.models import RoleBinding
|
|
|
|
|
from orgs.utils import current_org
|
|
|
|
|
|
|
|
|
|
if name == 'system_roles':
|
|
|
|
|
user_id = RoleBinding.objects \
|
|
|
|
|
.filter(role__in=value, scope='system') \
|
|
|
|
|
.values_list('user_id', flat=True)
|
|
|
|
|
return models.Q(id__in=user_id)
|
|
|
|
|
elif name == 'org_roles':
|
|
|
|
|
kwargs = dict(role__in=value, scope='org')
|
|
|
|
|
if not current_org.is_root():
|
|
|
|
|
kwargs['org_id'] = current_org.id
|
|
|
|
|
|
|
|
|
|
user_id = RoleBinding.objects.filter(**kwargs) \
|
|
|
|
|
.values_list('user_id', flat=True)
|
|
|
|
|
return models.Q(id__in=user_id)
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class User(AuthMixin, TokenMixin, RoleMixin, MFAMixin, JSONFilterMixin, AbstractUser):
|
2022-03-23 02:56:23 +00:00
|
|
|
|
class Source(models.TextChoices):
|
2020-12-09 10:43:13 +00:00
|
|
|
|
local = 'local', _('Local')
|
|
|
|
|
ldap = 'ldap', 'LDAP/AD'
|
|
|
|
|
openid = 'openid', 'OpenID'
|
|
|
|
|
radius = 'radius', 'Radius'
|
|
|
|
|
cas = 'cas', 'CAS'
|
2021-12-09 07:47:21 +00:00
|
|
|
|
saml2 = 'saml2', 'SAML2'
|
2022-08-04 06:40:33 +00:00
|
|
|
|
oauth2 = 'oauth2', 'OAuth2'
|
2023-04-28 06:01:44 +00:00
|
|
|
|
wecom = 'wecom', _('WeCom')
|
|
|
|
|
dingtalk = 'dingtalk', _('DingTalk')
|
|
|
|
|
feishu = 'feishu', _('FeiShu')
|
2022-08-24 03:41:48 +00:00
|
|
|
|
custom = 'custom', 'Custom'
|
2016-12-20 17:17:36 +00:00
|
|
|
|
|
2021-02-26 09:33:11 +00:00
|
|
|
|
SOURCE_BACKEND_MAPPING = {
|
2021-03-24 11:01:35 +00:00
|
|
|
|
Source.local: [
|
2022-02-25 11:23:59 +00:00
|
|
|
|
settings.AUTH_BACKEND_MODEL,
|
|
|
|
|
settings.AUTH_BACKEND_PUBKEY,
|
|
|
|
|
],
|
|
|
|
|
Source.ldap: [
|
|
|
|
|
settings.AUTH_BACKEND_LDAP
|
|
|
|
|
],
|
|
|
|
|
Source.openid: [
|
|
|
|
|
settings.AUTH_BACKEND_OIDC_PASSWORD,
|
|
|
|
|
settings.AUTH_BACKEND_OIDC_CODE
|
|
|
|
|
],
|
|
|
|
|
Source.radius: [
|
|
|
|
|
settings.AUTH_BACKEND_RADIUS
|
|
|
|
|
],
|
|
|
|
|
Source.cas: [
|
|
|
|
|
settings.AUTH_BACKEND_CAS
|
|
|
|
|
],
|
|
|
|
|
Source.saml2: [
|
|
|
|
|
settings.AUTH_BACKEND_SAML2
|
2021-03-24 11:01:35 +00:00
|
|
|
|
],
|
2022-08-04 06:40:33 +00:00
|
|
|
|
Source.oauth2: [
|
|
|
|
|
settings.AUTH_BACKEND_OAUTH2
|
|
|
|
|
],
|
2023-04-28 06:01:44 +00:00
|
|
|
|
Source.wecom: [
|
|
|
|
|
settings.AUTH_BACKEND_WECOM
|
|
|
|
|
],
|
|
|
|
|
Source.feishu: [
|
|
|
|
|
settings.AUTH_BACKEND_FEISHU
|
|
|
|
|
],
|
|
|
|
|
Source.dingtalk: [
|
|
|
|
|
settings.AUTH_BACKEND_DINGTALK
|
|
|
|
|
],
|
2022-08-24 03:41:48 +00:00
|
|
|
|
Source.custom: [
|
|
|
|
|
settings.AUTH_BACKEND_CUSTOM
|
|
|
|
|
]
|
2021-02-26 09:33:11 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
|
|
|
|
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')
|
|
|
|
|
)
|
|
|
|
|
groups = models.ManyToManyField(
|
|
|
|
|
'users.UserGroup', related_name='users',
|
|
|
|
|
blank=True, verbose_name=_('User group')
|
|
|
|
|
)
|
|
|
|
|
role = models.CharField(
|
2022-02-17 12:13:31 +00:00
|
|
|
|
default='User', max_length=10,
|
2019-07-11 10:12:14 +00:00
|
|
|
|
blank=True, verbose_name=_('Role')
|
|
|
|
|
)
|
2022-02-18 08:25:54 +00:00
|
|
|
|
is_service_account = models.BooleanField(default=False, verbose_name=_("Is service account"))
|
2019-07-11 10:12:14 +00:00
|
|
|
|
avatar = models.ImageField(
|
|
|
|
|
upload_to="avatar", null=True, verbose_name=_('Avatar')
|
|
|
|
|
)
|
|
|
|
|
wechat = models.CharField(
|
|
|
|
|
max_length=128, blank=True, verbose_name=_('Wechat')
|
|
|
|
|
)
|
|
|
|
|
phone = models.CharField(
|
|
|
|
|
max_length=20, blank=True, null=True, verbose_name=_('Phone')
|
|
|
|
|
)
|
2019-11-18 08:30:26 +00:00
|
|
|
|
mfa_level = models.SmallIntegerField(
|
|
|
|
|
default=0, choices=MFAMixin.MFA_LEVEL_CHOICES, verbose_name=_('MFA')
|
2019-07-11 10:12:14 +00:00
|
|
|
|
)
|
2022-11-04 06:22:38 +00:00
|
|
|
|
otp_secret_key = fields.EncryptCharField(
|
|
|
|
|
max_length=128, blank=True, null=True, verbose_name=_('OTP secret key')
|
|
|
|
|
)
|
2019-07-11 10:12:14 +00:00
|
|
|
|
# Todo: Auto generate key, let user download
|
|
|
|
|
private_key = fields.EncryptTextField(
|
|
|
|
|
blank=True, null=True, verbose_name=_('Private key')
|
|
|
|
|
)
|
|
|
|
|
public_key = fields.EncryptTextField(
|
|
|
|
|
blank=True, null=True, verbose_name=_('Public key')
|
|
|
|
|
)
|
2021-12-03 07:50:04 +00:00
|
|
|
|
secret_key = fields.EncryptCharField(
|
|
|
|
|
max_length=256, blank=True, null=True, verbose_name=_('Secret key')
|
|
|
|
|
)
|
2019-07-11 10:12:14 +00:00
|
|
|
|
comment = models.TextField(
|
|
|
|
|
blank=True, null=True, verbose_name=_('Comment')
|
|
|
|
|
)
|
2022-11-04 06:22:38 +00:00
|
|
|
|
is_first_login = models.BooleanField(default=True, verbose_name=_('Is first login'))
|
2019-07-11 10:12:14 +00:00
|
|
|
|
date_expired = models.DateTimeField(
|
|
|
|
|
default=date_expired_default, blank=True, null=True,
|
|
|
|
|
db_index=True, verbose_name=_('Date expired')
|
|
|
|
|
)
|
2023-02-03 04:22:27 +00:00
|
|
|
|
created_by = models.CharField(max_length=30, default='', blank=True, verbose_name=_('Created by'))
|
|
|
|
|
updated_by = models.CharField(max_length=30, default='', blank=True, verbose_name=_('Updated by'))
|
2019-07-11 10:12:14 +00:00
|
|
|
|
source = models.CharField(
|
2021-02-26 09:33:11 +00:00
|
|
|
|
max_length=30, default=Source.local,
|
|
|
|
|
choices=Source.choices,
|
2021-06-04 03:38:00 +00:00
|
|
|
|
verbose_name=_('Source')
|
2019-07-11 10:12:14 +00:00
|
|
|
|
)
|
|
|
|
|
date_password_last_updated = models.DateTimeField(
|
|
|
|
|
auto_now_add=True, blank=True, null=True,
|
|
|
|
|
verbose_name=_('Date password last updated')
|
|
|
|
|
)
|
2021-05-22 09:00:01 +00:00
|
|
|
|
need_update_password = models.BooleanField(
|
|
|
|
|
default=False, verbose_name=_('Need update password')
|
|
|
|
|
)
|
2023-02-03 04:22:27 +00:00
|
|
|
|
date_updated = models.DateTimeField(auto_now=True, verbose_name=_('Date updated'))
|
2023-06-28 07:01:25 +00:00
|
|
|
|
wecom_id = models.CharField(null=True, default=None, max_length=128, verbose_name=_('WeCom'))
|
|
|
|
|
dingtalk_id = models.CharField(null=True, default=None, max_length=128, verbose_name=_('DingTalk'))
|
|
|
|
|
feishu_id = models.CharField(null=True, default=None, max_length=128, verbose_name=_('FeiShu'))
|
2019-07-11 10:12:14 +00:00
|
|
|
|
|
2022-06-28 09:23:20 +00:00
|
|
|
|
DATE_EXPIRED_WARNING_DAYS = 5
|
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def __str__(self):
|
|
|
|
|
return '{0.name}({0.username})'.format(self)
|
|
|
|
|
|
2021-09-09 12:12:52 +00:00
|
|
|
|
@property
|
|
|
|
|
def receive_backends(self):
|
|
|
|
|
return self.user_msg_subscription.receive_backends
|
2021-05-31 09:20:38 +00:00
|
|
|
|
|
2021-09-16 10:59:15 +00:00
|
|
|
|
@property
|
|
|
|
|
def is_otp_secret_key_bound(self):
|
|
|
|
|
return bool(self.otp_secret_key)
|
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def get_absolute_url(self):
|
|
|
|
|
return reverse('users:user-detail', args=(self.id,))
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def source_display(self):
|
|
|
|
|
return self.get_source_display()
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def is_expired(self):
|
|
|
|
|
if self.date_expired and self.date_expired < timezone.now():
|
|
|
|
|
return True
|
|
|
|
|
else:
|
|
|
|
|
return False
|
|
|
|
|
|
2019-07-31 08:57:21 +00:00
|
|
|
|
@property
|
|
|
|
|
def expired_remain_days(self):
|
|
|
|
|
date_remain = self.date_expired - timezone.now()
|
|
|
|
|
return date_remain.days
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def will_expired(self):
|
2022-06-28 09:23:20 +00:00
|
|
|
|
if 0 <= self.expired_remain_days <= self.DATE_EXPIRED_WARNING_DAYS:
|
2019-07-31 08:57:21 +00:00
|
|
|
|
return True
|
|
|
|
|
else:
|
|
|
|
|
return False
|
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
@property
|
|
|
|
|
def is_valid(self):
|
|
|
|
|
if self.is_active and not self.is_expired:
|
|
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def is_local(self):
|
2020-12-09 10:43:13 +00:00
|
|
|
|
return self.source == self.Source.local.value
|
2019-07-31 08:57:21 +00:00
|
|
|
|
|
2022-06-07 11:26:07 +00:00
|
|
|
|
def is_password_authenticate(self):
|
|
|
|
|
cas = self.Source.cas
|
|
|
|
|
saml2 = self.Source.saml2
|
2022-08-18 02:30:20 +00:00
|
|
|
|
oauth2 = self.Source.oauth2
|
|
|
|
|
return self.source not in [cas, saml2, oauth2]
|
2022-06-07 11:26:07 +00:00
|
|
|
|
|
2023-02-07 08:21:26 +00:00
|
|
|
|
def set_required_attr_if_need(self):
|
2019-07-11 10:12:14 +00:00
|
|
|
|
if not self.name:
|
|
|
|
|
self.name = self.username
|
2020-03-12 08:24:38 +00:00
|
|
|
|
if not self.email or '@' not in self.email:
|
|
|
|
|
email = '{}@{}'.format(self.username, settings.EMAIL_SUFFIX)
|
|
|
|
|
if '@' in self.username:
|
|
|
|
|
email = self.username
|
|
|
|
|
self.email = email
|
|
|
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
2023-02-07 08:21:26 +00:00
|
|
|
|
self.set_required_attr_if_need()
|
2019-07-11 10:12:14 +00:00
|
|
|
|
if self.username == 'admin':
|
|
|
|
|
self.role = 'Admin'
|
|
|
|
|
self.is_active = True
|
2022-02-17 12:13:31 +00:00
|
|
|
|
return super().save(*args, **kwargs)
|
2019-07-11 10:12:14 +00:00
|
|
|
|
|
|
|
|
|
def is_member_of(self, user_group):
|
|
|
|
|
if user_group in self.groups.all():
|
|
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
|
2019-12-05 07:09:25 +00:00
|
|
|
|
def set_avatar(self, f):
|
|
|
|
|
self.avatar.save(self.username, f)
|
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def get_avatar_url(cls, username):
|
|
|
|
|
user_default = settings.STATIC_URL + "img/avatar/user.png"
|
|
|
|
|
return user_default
|
|
|
|
|
|
2019-07-11 10:12:14 +00:00
|
|
|
|
def avatar_url(self):
|
|
|
|
|
admin_default = settings.STATIC_URL + "img/avatar/admin.png"
|
|
|
|
|
user_default = settings.STATIC_URL + "img/avatar/user.png"
|
|
|
|
|
if self.avatar:
|
|
|
|
|
return self.avatar.url
|
|
|
|
|
if self.is_superuser:
|
|
|
|
|
return admin_default
|
|
|
|
|
else:
|
|
|
|
|
return user_default
|
2016-12-20 15:06:27 +00:00
|
|
|
|
|
2021-04-09 07:01:22 +00:00
|
|
|
|
def unblock_login(self):
|
|
|
|
|
from users.utils import LoginBlockUtil, MFABlockUtils
|
|
|
|
|
LoginBlockUtil.unblock_user(self.username)
|
|
|
|
|
MFABlockUtils.unblock_user(self.username)
|
|
|
|
|
|
2021-03-11 12:09:23 +00:00
|
|
|
|
@property
|
|
|
|
|
def login_blocked(self):
|
2021-04-08 04:47:49 +00:00
|
|
|
|
from users.utils import LoginBlockUtil, MFABlockUtils
|
|
|
|
|
if LoginBlockUtil.is_user_block(self.username):
|
|
|
|
|
return True
|
|
|
|
|
if MFABlockUtils.is_user_block(self.username):
|
|
|
|
|
return True
|
|
|
|
|
return False
|
2021-03-11 12:09:23 +00:00
|
|
|
|
|
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
|
2022-12-19 07:35:28 +00:00
|
|
|
|
return super(User, self).delete(using=using, keep_parents=keep_parents)
|
2016-12-20 16:43:52 +00:00
|
|
|
|
|
2021-03-16 08:57:56 +00:00
|
|
|
|
@classmethod
|
2022-02-28 11:28:58 +00:00
|
|
|
|
def get_user_allowed_auth_backend_paths(cls, username):
|
2021-03-16 08:57:56 +00:00
|
|
|
|
if not settings.ONLY_ALLOW_AUTH_FROM_SOURCE or not username:
|
|
|
|
|
return None
|
|
|
|
|
user = cls.objects.filter(username=username).first()
|
|
|
|
|
if not user:
|
|
|
|
|
return None
|
2022-02-28 11:28:58 +00:00
|
|
|
|
return user.get_allowed_auth_backend_paths()
|
2021-03-16 08:57:56 +00:00
|
|
|
|
|
2022-02-28 11:28:58 +00:00
|
|
|
|
def get_allowed_auth_backend_paths(self):
|
2021-03-16 08:57:56 +00:00
|
|
|
|
if not settings.ONLY_ALLOW_AUTH_FROM_SOURCE:
|
|
|
|
|
return None
|
|
|
|
|
return self.SOURCE_BACKEND_MAPPING.get(self.source, [])
|
|
|
|
|
|
2016-12-20 15:06:27 +00:00
|
|
|
|
class Meta:
|
2016-12-21 16:36:31 +00:00
|
|
|
|
ordering = ['username']
|
2018-03-05 04:59:14 +00:00
|
|
|
|
verbose_name = _("User")
|
2023-06-28 07:01:25 +00:00
|
|
|
|
unique_together = (
|
|
|
|
|
('dingtalk_id',),
|
|
|
|
|
('wecom_id',),
|
|
|
|
|
('feishu_id',),
|
|
|
|
|
)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
permissions = [
|
|
|
|
|
('invite_user', _('Can invite user')),
|
|
|
|
|
('remove_user', _('Can remove user')),
|
|
|
|
|
('match_user', _('Can match user')),
|
|
|
|
|
]
|
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())
|
|
|
|
|
|
2020-03-13 04:33:09 +00:00
|
|
|
|
def can_send_created_mail(self):
|
2020-12-09 10:43:13 +00:00
|
|
|
|
if self.email and self.source == self.Source.local.value:
|
2020-03-13 04:33:09 +00:00
|
|
|
|
return True
|
|
|
|
|
return False
|
2021-04-28 09:03:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class UserPasswordHistory(models.Model):
|
|
|
|
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
|
|
|
|
password = models.CharField(max_length=128)
|
|
|
|
|
user = models.ForeignKey("users.User", related_name='history_passwords',
|
2022-11-04 06:22:38 +00:00
|
|
|
|
on_delete=jms_models.CASCADE_SIGNAL_SKIP, verbose_name=_('User'))
|
2021-04-28 09:03:20 +00:00
|
|
|
|
date_created = models.DateTimeField(auto_now_add=True, verbose_name=_("Date created"))
|
2021-05-17 11:32:12 +00:00
|
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
|
return f'{self.user} set at {self.date_created}'
|
|
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
|
return self.__str__()
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
verbose_name = _("User password history")
|