jumpserver/apps/users/forms.py

339 lines
10 KiB
Python
Raw Normal View History

2016-08-14 11:18:41 +00:00
# ~*~ coding: utf-8 ~*~
2016-08-16 14:13:06 +00:00
from django import forms
2016-09-03 16:51:36 +00:00
from django.utils.translation import gettext_lazy as _
2016-11-09 15:49:10 +00:00
from common.utils import validate_ssh_public_key
2018-07-14 16:55:05 +00:00
from orgs.mixins import OrgModelForm
from orgs.utils import current_org
2016-08-21 14:37:55 +00:00
from .models import User, UserGroup
2016-08-14 11:18:41 +00:00
2018-04-18 04:48:07 +00:00
class UserCheckPasswordForm(forms.Form):
username = forms.CharField(label=_('Username'), max_length=100)
password = forms.CharField(
label=_('Password'), widget=forms.PasswordInput,
max_length=128, strip=False
)
class UserCheckOtpCodeForm(forms.Form):
otp_code = forms.CharField(label=_('MFA code'), max_length=6)
2018-04-18 04:48:07 +00:00
class UserCreateUpdateFormMixin(OrgModelForm):
role_choices = ((i, n) for i, n in User.ROLE_CHOICES if i != User.ROLE_APP)
2017-12-18 10:38:30 +00:00
password = forms.CharField(
label=_('Password'), widget=forms.PasswordInput,
max_length=128, strip=False, required=False,
)
2018-04-23 13:04:46 +00:00
role = forms.ChoiceField(
choices=role_choices, required=True,
initial=User.ROLE_USER, label=_("Role")
)
public_key = forms.CharField(
2018-03-27 09:47:53 +00:00
label=_('ssh public key'), max_length=5000, required=False,
widget=forms.Textarea(attrs={'placeholder': _('ssh-rsa AAAA...')}),
help_text=_('Paste user id_rsa.pub here.')
)
2017-12-18 10:38:30 +00:00
2016-08-14 11:18:41 +00:00
class Meta:
model = User
fields = [
2016-08-17 14:17:16 +00:00
'username', 'name', 'email', 'groups', 'wechat',
'phone', 'role', 'date_expired', 'comment', 'otp_level'
2016-08-14 11:18:41 +00:00
]
2016-08-19 16:42:50 +00:00
widgets = {
'otp_level': forms.RadioSelect(),
2018-07-14 16:55:05 +00:00
'groups': forms.SelectMultiple(
attrs={
'class': 'select2',
'data-placeholder': _('Join user groups')
}
)
2016-08-19 16:42:50 +00:00
}
2016-08-16 14:13:06 +00:00
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
super(UserCreateUpdateFormMixin, self).__init__(*args, **kwargs)
roles = []
# Super admin user
if self.request.user.is_superuser:
roles.append((User.ROLE_ADMIN, dict(User.ROLE_CHOICES).get(User.ROLE_ADMIN)))
roles.append((User.ROLE_USER, dict(User.ROLE_CHOICES).get(User.ROLE_USER)))
# Org admin user
else:
user = kwargs.get('instance')
# Update
if user:
role = kwargs.get('instance').role
roles.append((role, dict(User.ROLE_CHOICES).get(role)))
# Create
else:
roles.append((User.ROLE_USER, dict(User.ROLE_CHOICES).get(User.ROLE_USER)))
field = self.fields['role']
field.choices = set(roles)
def clean_public_key(self):
public_key = self.cleaned_data['public_key']
2018-03-27 09:47:53 +00:00
if not public_key:
return public_key
if self.instance.public_key and public_key == self.instance.public_key:
msg = _('Public key should not be the same as your old one.')
raise forms.ValidationError(msg)
if not validate_ssh_public_key(public_key):
raise forms.ValidationError(_('Not a valid ssh public key'))
return public_key
2017-12-18 10:38:30 +00:00
def save(self, commit=True):
2018-01-10 07:15:29 +00:00
password = self.cleaned_data.get('password')
otp_level = self.cleaned_data.get('otp_level')
public_key = self.cleaned_data.get('public_key')
2017-12-18 10:38:30 +00:00
user = super().save(commit=commit)
if password:
user.reset_password(password)
if otp_level:
user.otp_level = otp_level
user.save()
if public_key:
user.public_key = public_key
user.save()
2017-12-18 10:38:30 +00:00
return user
2016-08-16 14:13:06 +00:00
class UserCreateForm(UserCreateUpdateFormMixin):
EMAIL_SET_PASSWORD = _('Reset link will be generated and sent to the user')
CUSTOM_PASSWORD = _('Set password')
PASSWORD_STRATEGY_CHOICES = (
(0, EMAIL_SET_PASSWORD),
(1, CUSTOM_PASSWORD)
)
password_strategy = forms.ChoiceField(
choices=PASSWORD_STRATEGY_CHOICES, required=True, initial=0,
widget=forms.RadioSelect(), label=_('Password strategy')
)
class UserUpdateForm(UserCreateUpdateFormMixin):
pass
2017-03-29 16:51:36 +00:00
class UserProfileForm(forms.ModelForm):
username = forms.CharField(disabled=True)
name = forms.CharField(disabled=True)
email = forms.CharField(disabled=True)
2017-03-29 16:51:36 +00:00
class Meta:
model = User
fields = [
2017-03-30 08:28:00 +00:00
'username', 'name', 'email',
'wechat', 'phone',
2017-03-29 16:51:36 +00:00
]
UserProfileForm.verbose_name = _("Profile")
2018-04-23 13:04:46 +00:00
class UserMFAForm(forms.ModelForm):
mfa_description = _(
'Tip: when enabled, '
'you will enter the MFA binding process the next time you log in. '
'you can also directly bind in '
'"personal information -> quick modification -> change MFA Settings"!')
class Meta:
model = User
fields = ['otp_level']
widgets = {'otp_level': forms.RadioSelect()}
help_texts = {
'otp_level': _('* Enable MFA authentication '
'to make the account more secure.'),
}
UserMFAForm.verbose_name = _("MFA")
class UserFirstLoginFinishForm(forms.Form):
finish_description = _(
'In order to protect you and your company, '
'please keep your account, '
'password and key sensitive information properly. '
'(for example: setting complex password, enabling MFA authentication)'
)
UserFirstLoginFinishForm.verbose_name = _("Finish")
2017-03-30 08:28:00 +00:00
class UserPasswordForm(forms.Form):
old_password = forms.CharField(
2017-12-21 03:31:13 +00:00
max_length=128, widget=forms.PasswordInput,
label=_("Old password")
)
2017-03-30 08:28:00 +00:00
new_password = forms.CharField(
2017-12-21 03:31:13 +00:00
min_length=5, max_length=128,
widget=forms.PasswordInput,
label=_("New password")
)
2017-03-30 08:28:00 +00:00
confirm_password = forms.CharField(
2017-12-21 03:31:13 +00:00
min_length=5, max_length=128,
widget=forms.PasswordInput,
label=_("Confirm password")
)
2017-03-30 08:28:00 +00:00
def __init__(self, *args, **kwargs):
self.instance = kwargs.pop('instance')
2017-12-21 03:31:13 +00:00
super().__init__(*args, **kwargs)
2017-03-30 08:28:00 +00:00
def clean_old_password(self):
old_password = self.cleaned_data['old_password']
if not self.instance.check_password(old_password):
raise forms.ValidationError(_('Old password error'))
return old_password
def clean_confirm_password(self):
new_password = self.cleaned_data['new_password']
confirm_password = self.cleaned_data['confirm_password']
if new_password != confirm_password:
raise forms.ValidationError(_('Password does not match'))
return confirm_password
def save(self):
password = self.cleaned_data['new_password']
self.instance.reset_password(new_password=password)
2017-03-30 08:28:00 +00:00
return self.instance
class UserPublicKeyForm(forms.Form):
2018-04-23 13:04:46 +00:00
pubkey_description = _('Automatically configure and download the SSH key')
2017-03-30 08:28:00 +00:00
public_key = forms.CharField(
label=_('ssh public key'), max_length=5000, required=False,
2017-03-30 08:28:00 +00:00
widget=forms.Textarea(attrs={'placeholder': _('ssh-rsa AAAA...')}),
2017-12-21 03:31:13 +00:00
help_text=_('Paste your id_rsa.pub here.')
)
2017-03-30 08:28:00 +00:00
def __init__(self, *args, **kwargs):
2017-03-31 15:46:00 +00:00
if 'instance' in kwargs:
self.instance = kwargs.pop('instance')
else:
self.instance = None
2017-12-21 03:31:13 +00:00
super().__init__(*args, **kwargs)
2017-03-30 08:28:00 +00:00
def clean_public_key(self):
public_key = self.cleaned_data['public_key']
if self.instance.public_key and public_key == self.instance.public_key:
2017-12-21 03:31:13 +00:00
msg = _('Public key should not be the same as your old one.')
raise forms.ValidationError(msg)
2017-03-30 08:28:00 +00:00
if public_key and not validate_ssh_public_key(public_key):
2017-03-30 08:28:00 +00:00
raise forms.ValidationError(_('Not a valid ssh public key'))
return public_key
def save(self):
public_key = self.cleaned_data['public_key']
if public_key:
self.instance.public_key = public_key
self.instance.save()
2017-03-30 08:28:00 +00:00
return self.instance
UserPublicKeyForm.verbose_name = _("Public key")
class UserBulkUpdateForm(OrgModelForm):
2017-12-21 03:31:13 +00:00
users = forms.ModelMultipleChoiceField(
2017-04-12 03:50:15 +00:00
required=True,
label=_('Select users'),
queryset=User.objects.all(),
2017-04-12 03:50:15 +00:00
widget=forms.SelectMultiple(
attrs={
'class': 'select2',
'data-placeholder': _('Select users')
}
)
)
class Meta:
model = User
fields = ['users', 'groups', 'date_expired']
2017-04-12 03:50:15 +00:00
widgets = {
2017-12-18 10:38:30 +00:00
"groups": forms.SelectMultiple(
attrs={
'class': 'select2',
'data-placeholder': _('User group')
2017-12-18 10:38:30 +00:00
}
)
2017-04-12 03:50:15 +00:00
}
def save(self, commit=True):
2017-12-18 10:38:30 +00:00
changed_fields = []
for field in self._meta.fields:
if self.data.get(field) is not None:
changed_fields.append(field)
cleaned_data = {k: v for k, v in self.cleaned_data.items()
if k in changed_fields}
2017-12-21 03:31:13 +00:00
users = cleaned_data.pop('users', '')
2017-12-18 10:38:30 +00:00
groups = cleaned_data.pop('groups', [])
2017-12-21 03:31:13 +00:00
users = User.objects.filter(id__in=[user.id for user in users])
2017-04-12 03:50:15 +00:00
users.update(**cleaned_data)
if groups:
for user in users:
user.groups.set(groups)
return users
2018-07-14 16:55:05 +00:00
def user_limit_to():
return {"orgs": current_org}
2018-07-14 16:55:05 +00:00
2018-08-16 08:32:49 +00:00
class UserGroupForm(OrgModelForm):
2017-12-18 10:38:30 +00:00
users = forms.ModelMultipleChoiceField(
Dev2 (#1766) * [Update] 初始化操作日志 * [Feature] 完成操作日志记录 * [Update] 修改mfa失败提示 * [Update] 修改增加created by内容 * [Update] 增加改密日志 * [Update] 登录日志迁移到日志审计中 * [Update] change block user logic, if login success, clean block limit * [Update] 更新中/英文翻译(ALL) (#1662) * Revert "授权页面分页问题" * 增加命令导出 (#1566) * [Update] gunicorn不使用eventlet * [Update] 添加eventlet * 替换淘宝IP查询接口 * [Feature] 添加命令记录下载功能 (#1559) * [Feature] 添加命令记录下载功能 * [Update] 文案修改,导出记录、提交,取消全部命令导出 * [Update] 命令导出,修复时间问题 * [Update] paramiko => 2.4.1 * [Update] 修改settings * [Update] 修改权限判断 * Dev (#1646) * [Update] 添加org * [Update] 修改url * [Update] 完成基本框架 * [Update] 修改一些逻辑 * [Update] 修改用户view * [Update] 修改资产 * [Update] 修改asset api * [Update] 修改协议小问题 * [Update] stash it * [Update] 修改约束 * [Update] 修改外键为org_id * [Update] 删掉Premiddleware * [Update] 修改Node * [Update] 修改get_current_org 为 proxy对象 current_org * [Bugfix] 解决Node.root() 死循环,移动AdminRequired到permission中 (#1571) * [Update] 修改permission (#1574) * Tmp org (#1579) * [Update] 添加org api, 升级到django 2.0 * [Update] fix some bug * [Update] 修改一些bug * [Update] 添加授权规则org (#1580) * [Update] 修复创建授权规则,显示org_name不是有效UUID的bug * [Update] 更新org之间隔离授权规则,解决QuerySet与Manager问题;修复创建用户,显示org_name不是有效UUID之bug; * Tmp org (#1583) * [Update] 修改一些内容 * [Update] 修改datatable 支持process * [Bugfix] 修复asset queryset 没有valid方法的bug * [Update] 在线/历史/命令model添加org;修复命令记录保存org失败bug (#1584) * [Update] 修复创建授权规则,显示org_name不是有效UUID的bug * [Update] 更新org之间隔离授权规则,解决QuerySet与Manager问题;修复创建用户,显示org_name不是有效UUID之bug; * [Update] 在线/历史/命令model添加org * [Bugfix] 修复命令记录,保存org不成功bug * [Update] Org功能修改 * [Bugfix] 修复merge带来的问题 * [Update] org admin显示资产详情右侧选项卡;修复资产授权添加用户,会显示其他org用户的bug (#1594) * [Bugfix] 修复资产授权添加用户,显示其他org的用户bug * [Update] org admin 显示资产详情右侧选项卡 * Tmp org (#1596) * [Update] 修改index view * [Update] 修改nav * [Update] 修改profile * [Bugfix] 修复org下普通用户打开web终端看不到已被授权的资产和节点bug * [Update] 修改get_all_assets * [Bugfix] 修复节点前面有个空目录 * [Bugfix] 修复merge引起的bug * [Update] Add init * [Update] Node get_all_assets 过滤游离资产,条件nodes_key=None -> nodes=None * [Update] 恢复原来的api地址 * [Update] 修改api * [Bugfix] 修复org下用户查看我的资产不显示已授权节点/资产的bug * [Bugfix] Fix perm name unique * [Bugfix] 修复校验失败api * [Update] Merge with org * [Merge] 修改一下bug * [Update] 暂时修改一些url * [Update] 修改url 为django 2.0 path * [Update] 优化datatable 和显示组织优化 * [Update] 升级url * [Bugfix] 修复coco启动失败(load_config_from_server)、硬件刷新,测试连接,str 没有 decode(… (#1613) * [Bugfix] 修复coco启动失败(load_config_from_server)、硬件刷新,测试连接,str 没有 decode() method的bug * [Bugfix] (task任务系统)修复资产连接性测试、硬件刷新和系统用户连接性测试失败等bug * [Bugfix] 修复一些bug * [Bugfix] 修复一些bug * [Update] 更新org下普通用户的资产详情 (#1619) * [Update] 更新org下普通用户查看资产详情,只显示数据 * [Update] 优化org下普通用户查看资产详情前端代码 * [Update] 创建/更新用户的role选项;密码强度提示信息中英文; (#1623) * [Update] 修改 超级管理员/组织管理员 在 创建/更新 用户时role的选项 问题 * [Update] 用户密码强度提示信息支持中英文 * [Update] 修改token返回 * [Update] Asset返回org name * [Update] 修改支持xpack * [Update] 修改url * [Bugfix] 修复不登录就能查看资产的bug * [Update] 用户修改 * [Bugfix] ... * [Bugfix] 修复跳转错误的问题 * [Update] xpack/orgs组织添加删除功能-js; 修复Label继承Org后bug; (#1644) * [Update] 更新xpack下orgs的翻译信息 * [Update] 更新model Label,继承OrgModelMixin; * [Update] xpack/orgs组织添加删除功能-js; 修复Label继承Org后bug; * [Bugfix] 修复小bug * [Update] 优化一些api * [Update] 优化用户资产页面 * [Update] 更新 xpack/orgs 删除功能:限制在当前org下删除当前org (#1645) * [Update] 修改版本号 * [Update] 添加功能: 语言切换(中/英);修改 header_bar <商业支持、文档>显示方式 * [Update] 中/英切换文案修改;修改django_language key 从 settings 中获取 * [Update] 修改Dashboard页面文案,支持英文 * [Update] 更新中/英文翻译(ALL) * [Update] 解决翻译文件冲突 * [Update] 系统用户支持单独隋松 * [Update] 重置用户MFA * [Update] 设置session空闲时间 * [Update] 加密setting配置 * [Update] 修改单独推送和测试资产可连接性 * [Update] 添加功能:用户个人详情页添加 更改MFA操作 (#1748) * [Update] 添加功能:用户个人详情页添加 更改MFA操作 * [Update] 删除print * [Bugfix] 添加部分views的权限控制;从组织移除用户,同时从授权规则和用户组中移除此用户。 (#1746) * [Bugfix] 修复上传command log 为空 * [Update] 修复执行任务的bug * [Bugfix] 修复将用户从组内移除,其依然具有之前的组权限的bug, perms and user_groups * [Bugfix] 修复组管理员可以访问部分url-views的bug(如: /settings/)添加views权限控制 * [Update] 修改日志滚动 * [Bugfix] 修复组织权限控制的bug (#1763) * [Bugfix] 修复将用户从组内移除,其依然具有之前的组权限的bug, perms and user_groups * [Bugfix] 修复组管理员可以访问部分url-views的bug(如: /settings/)添加views权限控制
2018-09-03 03:24:25 +00:00
queryset=User.objects.all(),
label=_("User"),
2017-12-18 10:38:30 +00:00
widget=forms.SelectMultiple(
attrs={
'class': 'select2',
'data-placeholder': _('Select users')
}
),
required=False,
2018-07-14 16:55:05 +00:00
limit_choices_to=user_limit_to
2017-12-18 10:38:30 +00:00
)
2016-09-08 13:51:44 +00:00
2017-12-18 10:38:30 +00:00
def __init__(self, **kwargs):
instance = kwargs.get('instance')
if instance:
initial = kwargs.get('initial', {})
2018-07-20 05:25:50 +00:00
initial.update({'users': instance.users.all()})
2017-12-18 10:38:30 +00:00
kwargs['initial'] = initial
super().__init__(**kwargs)
2018-07-18 04:57:08 +00:00
if 'initial' not in kwargs:
return
users_field = self.fields.get('users')
if hasattr(users_field, 'queryset'):
2018-07-20 05:25:50 +00:00
users_field.queryset = current_org.get_org_users()
2016-09-08 13:51:44 +00:00
2016-09-16 17:04:52 +00:00
def save(self, commit=True):
2017-12-18 10:38:30 +00:00
group = super().save(commit=commit)
users = self.cleaned_data['users']
group.users.set(users)
return group
2016-09-16 17:04:52 +00:00
class Meta:
2017-12-18 10:38:30 +00:00
model = UserGroup
2016-09-16 17:04:52 +00:00
fields = [
2018-08-16 08:32:49 +00:00
'name', 'users', 'comment',
2016-09-16 17:04:52 +00:00
]
2016-11-09 15:49:10 +00:00
class FileForm(forms.Form):
2016-11-24 07:45:08 +00:00
file = forms.FileField()