Compare commits

...

294 Commits

Author SHA1 Message Date
fit2bot
79ff3b9423 feat: Update v3.8.2 2023-11-13 14:29:47 +08:00
fit2bot
11db46e61e fix:修复es6.8查询不到数据问题 (#12070)
Co-authored-by: feng <1304903146@qq.com>
2023-11-09 14:18:04 +08:00
ibuler
07bb44dfc3 fix: 修改可能迁移的问题 2023-11-01 03:41:20 -05:00
ibuler
1204a869a9 fix: 优化选择发布机 2023-10-30 16:06:40 +08:00
halo
0c8b36a6f4 fix: 修复DB2平台已经存在的问题 2023-10-26 01:25:26 -05:00
feng
d6cfda693f fix: 改密校验可连接性失败 2023-10-25 03:15:59 -05:00
Bai
7aa96462a4 fix: 修复登录日志和在线用户会话的 IP 地址获取方式 2023-10-25 01:39:15 -05:00
ibuler
1986653214 perf: 修复资产类型的 bug 2023-10-24 16:19:29 +08:00
fit2bot
4dc46cc754 fix: change secret perm 没有生成 (#11952)
Co-authored-by: feng <1304903146@qq.com>
2023-10-24 15:18:49 +08:00
fit2bot
dcb9270d02 fix: 改密切换至检测可连接性 失败 (#11951)
Co-authored-by: feng <1304903146@qq.com>
2023-10-24 15:18:27 +08:00
jiangweidong
f51d375f48 perf: 使用scan命令扫描在线用户 2023-10-23 04:33:17 -05:00
feng
cea24f0ccf fix: 删除错误的改密权限 2023-10-23 04:32:23 -05:00
ibuler
0292f2161f fix: 优化替换 DOMAINS 中端口 的问题 2023-10-22 22:32:30 -05:00
老广
778918be48 Merge pull request #11928 from jumpserver/pr@v3.8@database_list
fix: 资产数据库 不分页时list接口错误
2023-10-20 03:50:37 -05:00
feng
36fdf754e9 fix: 资产数据库 不分页时list接口错误 2023-10-20 16:40:00 +08:00
fit2bot
ce9515a19a perf: ticket 迁移文件 (#11921)
Co-authored-by: feng <1304903146@qq.com>
2023-10-19 20:00:54 +08:00
Bai
83108f84a3 fix: 修复账号改密密码规则提交不生效的问题 2023-10-19 04:30:28 -05:00
jiangweidong
e0b38fbcb6 fix: 可以清空云同步中的策略 2023-10-19 04:11:33 -05:00
Bryan
ce24c1c3fd Merge pull request #11914 from jumpserver/dev
v3.8.0
2023-10-19 03:37:39 -05:00
fit2bot
db9ee71ab3 perf: 翻译 (#11913)
Co-authored-by: feng <1304903146@qq.com>
2023-10-19 16:24:25 +08:00
fit2bot
db2331521d fix: 修复工单复合通知无账号信息 (#11912)
Co-authored-by: feng <1304903146@qq.com>
2023-10-19 15:56:14 +08:00
fit2bot
4aa4c6854b perf: 更新ops ticket announcement settings 权限 (#11911)
Co-authored-by: feng <1304903146@qq.com>
2023-10-19 15:15:02 +08:00
fit2bot
26a18a1f5c perf: 批量创建资产 账号格式错误提醒 (#11909)
Co-authored-by: feng <1304903146@qq.com>
2023-10-19 13:44:24 +08:00
fit2bot
6870df6d75 fix: cas ldap 登录失败 (#11908)
Co-authored-by: feng <1304903146@qq.com>
2023-10-19 12:24:56 +08:00
jiangweidong
03d1a187df perf: 工单直接审批者访问链接无认证跳转到登录页面 (#11902)
* perf: 工单直接审批者访问链接无认证跳转到登录页面

* perf: 修改重定向登录地址

* perf: 跳转字段标识更新
2023-10-18 22:21:08 -05:00
Eric_Lee
ca0dca26c7 Merge pull request #11900 from jumpserver/pr@dev@perf_task
perf: 完善僵尸会话清理
2023-10-18 19:17:04 +08:00
Eric
25a1989157 perf: 完善僵尸会话清理 2023-10-18 19:13:42 +08:00
ibuler
fef26c38fe perf: 去掉创建记录报错 2023-10-18 06:06:50 -05:00
fit2bot
a2fcc47436 fix: cas oidc 登录失败 (#11899)
Co-authored-by: feng <1304903146@qq.com>
2023-10-18 18:51:28 +08:00
fit2bot
00450121bc perf: 命令组加命令过滤搜索 (#11898)
Co-authored-by: feng <1304903146@qq.com>
2023-10-18 18:46:49 +08:00
ibuler
bdd885069f perf: 优化登录时创建 activity 的问题 2023-10-18 04:10:20 -05:00
老广
25d0c021e1 Merge pull request #11894 from jumpserver/pr@dev@perf_window_default_verify_account_by_rdp
perf: 修改windows校验账号的默认方式
2023-10-18 03:46:08 -05:00
ibuler
095c23ea4f perf: 修改windows校验账号的默认方式 2023-10-18 16:44:38 +08:00
fit2bot
3c3c112b07 perf: 更新appletpublication applethostdeployment 权限位 (#11893)
Co-authored-by: feng <1304903146@qq.com>
2023-10-18 16:35:08 +08:00
老广
d95a44fe44 Merge pull request #11892 from jumpserver/pr@dev@perf_bind_wecom_logout
perf: 企业微信绑定后退出
2023-10-18 03:10:41 -05:00
ibuler
e713bdab0b perf: 企业微信绑定后退出 2023-10-18 16:09:17 +08:00
fit2bot
78f1b2b002 perf: user session 表去掉过期时间字段 (#11890)
Co-authored-by: feng <1304903146@qq.com>
2023-10-18 16:04:02 +08:00
fit2bot
e0762573ae perf: 在线用户动态过期时间 (#11889)
Co-authored-by: feng <1304903146@qq.com>
2023-10-18 15:50:38 +08:00
老广
16e8c7faba Merge pull request #11888 from jumpserver/pr@dev@perf_protocols_lose
perf: 修复协议丢失的问题
2023-10-18 02:42:12 -05:00
ibuler
9b019e45ae perf: 修复协议丢失的问题 2023-10-18 15:40:52 +08:00
fit2bot
71d70501d6 perf: 优化数据库必填 (#11887)
Co-authored-by: ibuler <ibuler@qq.com>
2023-10-18 02:22:17 -05:00
老广
5cd44ebfce Merge pull request #11865 from jumpserver/pr@dev@fix_corntab
fix: 修复crontab语义
2023-10-18 01:13:15 -05:00
老广
03c27ab5b8 Merge pull request #11875 from jumpserver/pr@dev@perf_update_clients_version
perf: 更新clients版本
2023-10-18 01:12:36 -05:00
fit2bot
d3a283232f perf: 优化 xpack license 检查 (#11885)
Co-authored-by: ibuler <ibuler@qq.com>
2023-10-18 01:10:24 -05:00
fit2bot
f088bbce12 perf: 连接方式,动作去掉: 通知 (#11878)
Co-authored-by: feng <1304903146@qq.com>
2023-10-17 19:21:59 +08:00
fit2bot
b313598227 fix: 修复账号批量添加模版账号时name没同步过来,资产创建时使用模版账号没有切换自,资产克隆时生成的账号没有切换自 (#11877)
Co-authored-by: feng <1304903146@qq.com>
2023-10-17 19:15:46 +08:00
halo
3a118b6753 perf: 更新clients版本 2023-10-17 17:13:30 +08:00
Eric_Lee
578c2af57c Merge pull request #11870 from jumpserver/pr@dev@perf_acl_ip
perf: 增加针对 ip 的获取
2023-10-17 16:25:24 +08:00
Eric
b5ef239c6c perf: 增加针对 ip 的获取 2023-10-17 15:57:15 +08:00
fit2bot
e88e4438ba fix: acl 记录操作日志 账号信息为空 (#11869)
Co-authored-by: feng <1304903146@qq.com>
2023-10-17 15:01:21 +08:00
fit2bot
73b75df524 perf: 资产acl拒绝后没记录操作日志 (#11868)
Co-authored-by: feng <1304903146@qq.com>
2023-10-17 14:28:19 +08:00
Bai
772684d24c fix: 修复crontab语义 2023-10-17 11:19:13 +08:00
fit2bot
741705b85b perf: 修改定期清理日志默认时间180天 (#11864)
Co-authored-by: feng <1304903146@qq.com>
2023-10-17 11:11:55 +08:00
fit2bot
f5176bcc6f perf: 修改迁移文件 (#11863)
Co-authored-by: feng <1304903146@qq.com>
2023-10-17 11:04:05 +08:00
fit2bot
c917d8f346 fix: 系统设置 安全设置权限为错误 (#11860)
Co-authored-by: feng <1304903146@qq.com>
2023-10-16 19:33:13 +08:00
fit2bot
5c0905b3b5 fix: 操作日志全局组织数量不对 (#11859)
Co-authored-by: feng <1304903146@qq.com>
2023-10-16 18:51:26 +08:00
fit2bot
bda23b3d2a fix: 调API创建与父节点同名的子节点报错:同级别节点名称不能重复 (#11858)
Co-authored-by: feng <1304903146@qq.com>
2023-10-16 18:15:53 +08:00
fit2bot
8b6526211c perf: 工单动作添加操作日志 (#11857)
Co-authored-by: feng <1304903146@qq.com>
2023-10-16 16:40:21 +08:00
fit2bot
86e8f3a80b fix: 组织管理员不能创建用户 (#11856)
Co-authored-by: feng <1304903146@qq.com>
2023-10-16 15:06:47 +08:00
fit2bot
70661242c1 fix: 在线用户 下线权限错误 导致审计员无权限下线用户 (#11853)
Co-authored-by: feng <1304903146@qq.com>
2023-10-16 14:22:20 +08:00
fit2bot
7dcae1e05a perf: 命令过滤中 去掉通知动作 (#11851)
Co-authored-by: feng <1304903146@qq.com>
2023-10-16 13:27:37 +08:00
fit2bot
0a28c5650c perf: 三方用户登录通知 (#11846)
Co-authored-by: feng <1304903146@qq.com>
2023-10-16 11:28:53 +08:00
fit2bot
f55c84ce3b fix: 发布机500 (#11841)
Co-authored-by: feng <1304903146@qq.com>
2023-10-13 17:19:05 +08:00
fit2bot
ac11790192 perf: 替换iphone mfa 二维码图片 (#11839)
Co-authored-by: feng <1304903146@qq.com>
2023-10-13 16:51:34 +08:00
老广
f80ff279d0 perf: 用户确认和access key
Merge branch 'dev' of github.com:jumpserver/jumpserver into dev
2023-10-13 16:37:45 +08:00
ibuler
d7ac08f6d9 perf: 去掉 debug 2023-10-13 16:36:23 +08:00
ibuler
b5714f7e14 Merge branch 'pr@dev@perf_user_confirm' into pr@dev@perf_change_access_key_create 2023-10-13 16:34:19 +08:00
ibuler
d6b450f32a perf: 修改 ak 2023-10-13 16:33:25 +08:00
ibuler
1daf1acaf3 perf: 修改 access key 2023-10-13 16:31:05 +08:00
fit2bot
ea0e852412 fix: rdp 测试可连接性失败 (#11837)
Co-authored-by: feng <1304903146@qq.com>
2023-10-13 16:21:20 +08:00
ibuler
ce976f215f Merge branch 'dev' of github.com:jumpserver/jumpserver into dev 2023-10-13 16:10:40 +08:00
fit2bot
ffc057f844 fix: 账号改密-执行列表-详情-任务记录:模糊搜索500 (#11835)
Co-authored-by: feng <1304903146@qq.com>
2023-10-13 15:33:35 +08:00
fit2bot
588723a76c perf: 优化资产登录通知信息 (#11834)
Co-authored-by: feng <1304903146@qq.com>
2023-10-13 15:08:56 +08:00
ibuler
1ca912373f perf: 修改用户确认 2023-10-13 14:59:58 +08:00
ibuler
452ee1224c perf: 修改用户确认 2023-10-13 14:40:40 +08:00
fit2bot
7eb497f9d3 fix: 资产登录被限制,没有记录到当前组织的操作日志,而是记录到全局组织 (#11827)
Co-authored-by: feng <1304903146@qq.com>
2023-10-12 20:13:21 +08:00
fit2bot
58fd578ddd perf: 资产登录提示添加账号信息 (#11826)
Co-authored-by: feng <1304903146@qq.com>
2023-10-12 20:04:28 +08:00
fit2bot
e1278360af fix: 资产创建失败 (#11824)
Co-authored-by: feng <1304903146@qq.com>
2023-10-12 19:46:04 +08:00
fit2bot
c0de27ff7a perf: 资产批量更新平台字段,根据平台约束协议自动生效 (#11818)
Co-authored-by: feng <1304903146@qq.com>
2023-10-12 18:11:51 +08:00
ibuler
116d0ba5c6 perf: 优化任务记录 activity 2023-10-12 17:06:12 +08:00
fit2bot
9f042cfa04 Merge branch 'dev' into pr@dev@change_import (#11815)
* perf: 修改获取 ip

* perf: 修改导入

---------

Co-authored-by: ibuler <ibuler@qq.com>
2023-10-12 03:17:32 -05:00
Eric_Lee
ce63ea7528 Merge pull request #11812 from jumpserver/pr@dev@fix_get_real_ip
perf: 修改获取 ip
2023-10-12 16:13:57 +08:00
ibuler
8b3fd2c117 perf: 修改获取 ip 2023-10-12 16:09:22 +08:00
ibuler
23ccd6df8c perf: mysql mariadb 数据库不再必填 2023-10-12 14:50:09 +08:00
Bai
614e019f14 fix: 修改迁移文件choices和翻译文件 2023-10-11 21:15:47 -05:00
ibuler
38aa828eb8 perf: passkey 只允许本地用户开启 2023-10-11 04:52:54 -05:00
Bai
7cd2736e82 perf: 优化用户传递的 phone 处理 2023-10-11 04:50:45 -05:00
ibuler
443f6d25e8 perf: Windows 默认使用 rdping 测试 2023-10-11 04:22:08 -05:00
Eric
e8652af054 perf: 更新格式 2023-10-11 04:21:00 -05:00
Eric
fd6a8dd807 perf: 增加错误类型 2023-10-11 04:21:00 -05:00
Eric
499eedd83e perf: 会话新增 error_reason 字段 2023-10-11 04:21:00 -05:00
feng
ca7d164034 perf: 账号模版信息同步到所关联的账号 2023-10-11 04:20:11 -05:00
Bai
3ef8e9603a perf: 优化 otp windows 最小支持设置 0 2023-10-11 04:06:17 -05:00
Bai
09f71d80eb perf: 优化LDAP用户导入列表时任务状态设置 2023-10-11 04:05:51 -05:00
jiangweidong
73db1bf50c feat: 支持LDAP用户组变更时,JS同步变更 2023-10-10 06:37:28 -05:00
fit2bot
6017f804a6 perf: 用户 phone wechat 加密 (#11789)
Co-authored-by: feng <1304903146@qq.com>
2023-10-10 19:11:08 +08:00
ibuler
affa562384 perf: 优化禁用用户 2023-10-10 19:00:00 +08:00
fit2bot
0d101bc5ad perf: 不活跃了用户默认90天检测一下 (#11790)
Co-authored-by: feng <1304903146@qq.com>
2023-10-10 18:48:35 +08:00
jiangweidong
70f0f55ddb feat: 支持自定义短信认证(文件) (#11784)
* feat: 支持自定义短信认证(文件)

* perf: 翻译

* perf: 还原注释
2023-10-10 05:23:54 -05:00
fit2bot
333746e7c4 perf: 优化用户 access key 的使用和创建 (#11776)
* perf: 优化用户 access key 的使用和创建

* perf: 优化 access key api

---------

Co-authored-by: ibuler <ibuler@qq.com>
2023-10-10 04:52:52 -05:00
fit2bot
30b19d31eb fix: 账号批量更新失败 (#11785)
Co-authored-by: feng <1304903146@qq.com>
2023-10-10 17:24:56 +08:00
Eric
a844ce23e4 perf: 调整格式 2023-10-10 07:40:48 +05:00
Eric
d6c0139fef perf: 支持持久化设置个人终端主题 2023-10-10 07:40:48 +05:00
jiangweidong
11157563ba perf: 优化跳转接口参数 2023-10-09 16:00:36 +05:00
jiangweidong
95e7bde5d7 perf: 优化翻译 2023-10-09 16:00:36 +05:00
jiangweidong
814350ab80 perf: 翻译 2023-10-09 16:00:36 +05:00
jiangweidong
3ac35eec68 perf: 优化OIDC用户未激活时,会循环跳转登录页面 2023-10-09 16:00:36 +05:00
fit2bot
3d27986c96 perf: asset login 消息通知添加操作日志记录 (#11774)
Co-authored-by: feng <1304903146@qq.com>
2023-10-09 17:16:38 +08:00
fit2bot
c981e9cd9f perf: 主机名包含/ 可以执行ansible任务 (#11772)
Co-authored-by: feng <1304903146@qq.com>
2023-10-09 16:05:42 +08:00
Bai
e00c804a5a perf: 优化校验登录城市名1 2023-10-09 14:43:48 +08:00
fit2bot
ef2b7b464e perf: ansible 用户切换至 (#11766)
Co-authored-by: feng <1304903146@qq.com>
2023-10-09 14:35:21 +08:00
feng
ae5d4257ad fix: 修复账号批量更新失败问题 2023-10-09 10:05:50 +08:00
halo
b42014d58e feat: 支持DB2数据库 2023-10-09 10:04:14 +08:00
feng
e71e8cd595 perf: 优化清除日志天数系统配置校验逻辑 2023-10-08 07:39:19 +05:00
fit2bot
dd50044b89 perf: 翻译 (#11748)
Co-authored-by: feng <1304903146@qq.com>
2023-10-07 17:58:42 +08:00
fit2bot
68707085fa perf: 日志保存时间不少于6个月 (#11742)
Co-authored-by: feng <1304903146@qq.com>
2023-10-07 17:41:45 +08:00
fit2bot
60399fae29 feat: 登录资产消息提醒 (#11747)
Co-authored-by: feng <1304903146@qq.com>
2023-10-07 17:41:20 +08:00
ibuler
f206d963a0 perf: 优化会话 api 2023-10-07 15:57:15 +08:00
fit2bot
42b4e7697d feat: 资产登录acl动作增加操作日志 (#11741)
Co-authored-by: feng <1304903146@qq.com>
2023-10-07 15:50:28 +08:00
fit2bot
0c1f4d99f8 fix: 修复工单引入html错误问题 (#11744)
Co-authored-by: feng <1304903146@qq.com>
2023-10-07 15:28:40 +08:00
ibuler
2aed3fcaea perf: 修改随机数生成,避免使用 random 库 2023-10-07 11:30:45 +05:00
ibuler
28196573bb perf: 修改随机使用secrets 2023-10-07 11:30:45 +05:00
ibuler
27c505853b perf: 优化忘记密码 2023-10-07 11:18:55 +05:00
jiangweidong
896d42c53e perf: 更新jms-storage版本 2023-09-28 18:08:39 +05:00
feng
f79084c2df fix: 账号授权过滤指定账号api 失效问题 2023-09-27 13:11:48 +05:00
ibuler
15a5dda9e0 perf: 修改默认的邮箱地址 2023-09-27 15:15:15 +08:00
ibuler
2069fee795 perf: 优化发送邮件 2023-09-27 08:27:12 +05:00
feng
56a26481a4 perf: 账号模版 生成随机密码密钥及账号批量更新500 2023-09-26 12:55:54 +08:00
ibuler
cbe3d66b39 fix: pubkey auth require svc sign 2023-09-25 23:29:42 +08:00
Bryan
7c67d882aa Revert "fix: pubkey auth require svc sign"
This reverts commit 9bde2ff6e1.
2023-09-25 23:24:52 +08:00
ibuler
9bde2ff6e1 fix: pubkey auth require svc sign 2023-09-25 23:08:55 +08:00
Bai
1f00c00183 fix: 修复验证码校验逻辑和报错信息 2023-09-25 23:03:32 +08:00
ibuler
c369b5478c fix: 修复暴力校验验证码 2023-09-25 22:06:57 +08:00
fit2bot
10363dcc5b fix: 修复用户username 中文 登录失败问题 (#11692)
Co-authored-by: feng <1304903146@qq.com>
2023-09-25 21:39:16 +08:00
jiangweidong
42bdb2cf14 perf: 优化找回密码时区号带加号无法匹配的问题 2023-09-25 16:42:30 +08:00
fit2bot
d64e77db30 perf: 去掉print (#11687)
Co-authored-by: feng <1304903146@qq.com>
2023-09-25 16:37:00 +08:00
fit2bot
4065baf785 feat: 用户登录堡垒机时通知管理员 (#11686)
Co-authored-by: feng <1304903146@qq.com>
2023-09-25 16:25:44 +08:00
Bai
0f3ddc3bf1 fix: 修复系统用户同步同时包含pwd/ssh-key导致创建账号id冲突报错的问题 2023-09-25 16:22:47 +08:00
吴小白
138adeff76 perf: 添加 ping 命令 2023-09-25 10:50:53 +08:00
ibuler
0cf17310e1 fix: 修复 DOMAINS 添加 80和443 不生效的问题 2023-09-22 17:47:43 +08:00
吴小白
43dbb4c226 perf: 添加 patch 命令 2023-09-22 15:20:49 +08:00
Bai
cefd9f4ab2 fix: 解决节点资产数量方法计算不准确的问题 2023-09-22 15:18:22 +08:00
fit2bot
7128593502 perf: CeleryTaskExecution 添加默认排序 (#11663)
Co-authored-by: feng <1304903146@qq.com>
2023-09-22 15:06:58 +08:00
maninhill
5d4fa22058 chore: 优化 README 文案 2023-09-22 10:24:21 +08:00
Bryan
3c54c82ce9 Merge pull request #11636 from jumpserver/dev
v3.7.0
2023-09-21 17:02:48 +08:00
fit2bot
91dce82b38 fix: 安全设置开启仅已存在用户登录,企业微信等扫描登录,如果用户不存在,还是会自动创建用户登录成功。 (#11651)
Co-authored-by: feng <1304903146@qq.com>
2023-09-21 17:01:03 +08:00
Bryan
d102db7a7b Merge pull request #11650 from jumpserver/pr@dev@dev_master
fix: 解决 master 冲突
2023-09-21 16:53:09 +08:00
Bai
1de7af4984 fix: 解决 master 冲突 2023-09-21 16:51:54 +08:00
Aaron3S
9892ff7dd6 feat: 代码片段支持 oracle 和 mariadb 2023-09-21 16:37:16 +08:00
老广
4cb499953c Revert "perf: 修复事务中任务执行"
This reverts commit cdbe5d31e9.
2023-09-21 15:40:39 +08:00
老广
0397bdeb46 Revert "perf: 修复 task id 不对的问题"
This reverts commit 1d6d92c160.
2023-09-21 15:39:29 +08:00
ibuler
1d6d92c160 perf: 修复 task id 不对的问题 2023-09-21 15:20:16 +08:00
ibuler
cdbe5d31e9 perf: 修复事务中任务执行 2023-09-21 15:04:58 +08:00
fit2bot
b023ca0c69 fix: saml 用户没现在记录 (#11641)
Co-authored-by: feng <1304903146@qq.com>
2023-09-21 14:02:09 +08:00
ibuler
803d590096 perf: 修改生成 applet accounts 2023-09-21 13:06:02 +08:00
ibuler
e11367088a perf: 修改 acl 登录限制问题 2023-09-21 11:33:28 +08:00
jiangweidong
1c74dd00ba fix: 解决sqlserver无法推送和改密的问题 (#11637) 2023-09-20 21:45:21 +08:00
Aaron3S
ed832af631 fix: 修复运行job 组织切换问题 2023-09-20 18:26:47 +08:00
fit2bot
948c499d9e fix: 修复仪表板图表时间范围不准 (#11633)
Co-authored-by: feng <1304903146@qq.com>
2023-09-20 17:41:35 +08:00
fit2bot
a51549cf1c perf: ansible任务 未激活的时候关闭定时任务 (#11631)
Co-authored-by: feng <1304903146@qq.com>
2023-09-20 15:30:29 +08:00
fit2bot
39baf88055 fix: ansible postgresql (#11629)
Co-authored-by: feng <1304903146@qq.com>
2023-09-20 14:29:53 +08:00
fit2bot
90131db55a perf: 修改任务检查 (#11609)
* perf: 修改任务检查

* perf: 修改翻译

---------

Co-authored-by: ibuler <ibuler@qq.com>
2023-09-20 11:12:15 +08:00
“huailei000”
ea3ff1ebcb perf: 优化登录页面移动端布局 2023-09-19 20:20:28 +08:00
Aaron3S
f3ca45aa74 perf: 优化 Playbook 文件创建逻辑 2023-09-19 18:49:16 +08:00
老广
74cc174d7a Merge pull request #11622 from jumpserver/pr@dev@perf_random_error
fix: 修复 random error
2023-09-19 18:15:50 +08:00
ibuler
0eba6d2175 fix: 修复 random error 2023-09-19 18:11:27 +08:00
fit2bot
58592a13e3 fix: 解锁ip失败问题 (#11611)
Co-authored-by: feng <1304903146@qq.com>
2023-09-19 17:38:46 +08:00
fit2bot
b8fb23a0a0 perf: user setting (#11610)
Co-authored-by: feng <1304903146@qq.com>
2023-09-19 16:30:48 +08:00
Bai
f5c43488fd perf: 优化 es host 中包含 # 字符时提示错误 2023-09-19 15:31:02 +08:00
Eric
19c76ba01c perf: 删除发布机执行的任务目录 2023-09-19 15:02:02 +08:00
Eric
68c4cd5928 perf: 修复发布机安装应用的报错 2023-09-19 15:01:37 +08:00
fit2bot
e5bfa29c7b fix: 创建用户推送失败问题 (#11606)
Co-authored-by: feng <1304903146@qq.com>
2023-09-19 14:53:43 +08:00
fit2bot
cbb772def7 fix: 修复connection token 获取user错误 (#11603)
Co-authored-by: feng <1304903146@qq.com>
2023-09-19 11:09:58 +08:00
fit2bot
e6fe7c489e perf: 修改账号生成 (#11591)
* perf: 修改账号生成

* perf: 修改账号模版支持策略

* perf: 修改特殊字符数量

* perf: 修改 model 继承

* perf: 修改顺序

* perf: 修改 requirements

* perf: 修改翻译

* perf: 修改随机生成密码

* perf: 修改密钥生成

* perf: 修复 bug

---------

Co-authored-by: ibuler <ibuler@qq.com>
2023-09-19 10:59:33 +08:00
fit2bot
0b30f5cf88 perf: 翻译 (#11602)
Co-authored-by: feng <1304903146@qq.com>
2023-09-19 10:36:03 +08:00
fit2bot
018f1a0e8d perf: 删除管理用户错误提醒 (#11596)
Co-authored-by: feng <1304903146@qq.com>
2023-09-18 18:42:02 +08:00
fit2bot
24ed57b98a fix: 三方登录用户无法下线 (#11592)
Co-authored-by: feng <1304903146@qq.com>
2023-09-18 16:20:55 +08:00
ibuler
04a790c4ee perf: 优化 account template platform required 2023-09-18 14:29:41 +08:00
ibuler
2d9a3ef7d4 perf: 修改 migrations,不生成新的迁移文件 2023-09-18 14:29:24 +08:00
ibuler
0d2adeccf2 perf: 优化 applet account delete 2023-09-18 14:18:24 +08:00
Eric
886f977311 perf: 修复 chrome 部分元素定位失败的问题 2023-09-18 14:10:24 +08:00
fit2bot
9367e79bcf perf: 翻译 (#11583)
Co-authored-by: feng <1304903146@qq.com>
2023-09-18 11:11:12 +08:00
fit2bot
af733ecbad fix: 修改平台id序列化属性 改为非只读 (#11581)
Co-authored-by: feng <1304903146@qq.com>
2023-09-17 16:07:05 +08:00
fit2bot
09f9775eab fix: 平台无category type 过滤 (#11580)
Co-authored-by: feng <1304903146@qq.com>
2023-09-17 12:50:31 +08:00
feng
1c2a362beb perf: 修改usersession 模块位置 2023-09-15 17:25:06 +08:00
Eric_Lee
bb1e674367 Merge pull request #11578 from jumpserver/pr@dev@perf_host_deploy_log
perf: 修复发布机历史执行任务日志无法查看的问题
2023-09-15 17:18:45 +08:00
Eric
a75677ab08 perf: 修复发布机历史执行任务日志无法查看的问题 2023-09-15 17:15:12 +08:00
fit2bot
b1daa4d357 fix: 修改不常登录用户锁定逻辑 (#11576)
Co-authored-by: feng <1304903146@qq.com>
2023-09-15 16:39:49 +08:00
fit2bot
c32271ec6f fix: mysql 没配置ssl ansible 连接失败问题 (#11574)
Co-authored-by: feng <1304903146@qq.com>
2023-09-15 16:16:04 +08:00
Aaron3S
beb4f14be9 perf: 优化 jobexecution 创建 2023-09-15 14:39:16 +08:00
fit2bot
e719904874 fix: 修复工单回复报500 (#11571)
Co-authored-by: feng <1304903146@qq.com>
2023-09-15 11:26:13 +08:00
Eric_Lee
664bc2a4d9 Merge pull request #11568 from jumpserver/pr@dev@perf_deplay_task
perf: 优化推送部署任务,事务提交后再执行
2023-09-14 18:30:16 +08:00
ibuler
b91db8c146 perf: 优化推送部署任务,事务提交后再执行 2023-09-14 18:17:22 +08:00
fit2bot
500aeeb77f perf: 升级flower (#11567)
Co-authored-by: feng <1304903146@qq.com>
2023-09-14 18:15:25 +08:00
feng
3abc8bddfa feat: 用户在线session控制 2023-09-14 16:21:57 +08:00
老广
5cbbf9e737 Merge pull request #11561 from jumpserver/pr@dev@perf_i18n
perf: 优化翻译
2023-09-14 14:30:53 +08:00
ibuler
7204a86f87 perf: 优化翻译 2023-09-14 14:26:17 +08:00
老广
829194420a Merge pull request #11559 from jumpserver/pr@dev@limit_super_privilege
feat: 限制超级权限
2023-09-14 13:54:20 +08:00
老广
61dc95d9ae Merge pull request #11560 from jumpserver/pr@dev@perf_i18n
perf: 优化翻译
2023-09-14 11:29:28 +08:00
ibuler
a9f60a9117 perf: 优化翻译 2023-09-14 11:26:12 +08:00
ibuler
82f96d6ed2 feat: 限制超级权限 2023-09-14 10:42:16 +08:00
feng
f6c56d4979 perf: 网络设备 ansible enables true 2023-09-13 19:29:01 +08:00
老广
54d0a1b871 Merge pull request #11554 from jumpserver/pr@dev@perf_add_tip
perf: 添加tips
2023-09-13 17:44:45 +08:00
老广
5b4a267ccd Merge pull request #11553 from jumpserver/pr@dev@feat_support_ansbile_raw
feat: 作业中心支持 raw (网络设备使用)
2023-09-13 17:44:10 +08:00
ibuler
a6d78834e7 perf: 添加tips 2023-09-13 17:43:29 +08:00
Aaron3S
07da98e438 feat: 作业中心支持 raw (网络设备使用) 2023-09-13 17:25:42 +08:00
老广
7c973616cd Merge pull request #11552 from jumpserver/pr@dev@add_api_check_for_unauth
perf: 添加 check api,检测所有 api
2023-09-13 17:24:40 +08:00
ibuler
b9997b07db perf: 去掉不用的 backend 2023-09-13 17:22:50 +08:00
ibuler
bcda879f3b perf: 修改 ticket 认证的 2023-09-13 17:19:13 +08:00
ibuler
d0f79c2df2 perf: 添加 check api 避免未认证 2023-09-13 17:05:01 +08:00
ibuler
1249935bab perf: 优化设置项名称 2023-09-13 10:09:56 +08:00
ibuler
5fa1ae9ee5 perf: 修改说明 2023-09-12 15:59:25 +08:00
Bai
d0755c4719 fix: 修复系统任务支持通过 id、name 进行搜索 2023-09-12 15:35:11 +08:00
fit2bot
72b215ed03 feat: 支持 passkey 登录 (#11519)
* perf: 基本完成功能

* perf: 优化 passkey

* perf: 优化 passkey

* perf: 完成 passkey

---------

Co-authored-by: ibuler <ibuler@qq.com>
2023-09-11 18:15:03 +08:00
fit2bot
d7ca1a09d4 perf: connectiontoken 添加 connect_options file_name_conflict_resolution参数 给koko处理冲冲突文件名 (#11535)
Co-authored-by: feng <1304903146@qq.com>
2023-09-11 16:22:11 +08:00
fit2bot
04e341a1bb perf: 翻译 (#11534)
Co-authored-by: feng <1304903146@qq.com>
2023-09-11 15:26:50 +08:00
fit2bot
a41909ec8d feat: 个人设置 (#11494)
Co-authored-by: feng <1304903146@qq.com>
2023-09-11 14:38:07 +08:00
ibuler
f9d6de9c39 fix: 修复 private storage permission 2023-09-11 11:20:12 +08:00
halo
816b284a51 perf: 支持windows客户端msi格式 2023-09-11 11:15:17 +08:00
Eric
d4c5dcf069 perf: 修改变更时间 2023-09-07 19:30:59 +08:00
Eric
73037c21e8 perf: chrome 代填进度条最大 30s 超时 2023-09-07 19:30:59 +08:00
halo
c7f9259a2e perf: 更新客户端 v2.0.1 2023-09-07 19:30:25 +08:00
feng
8632bd2480 fix: 修复ip被锁定列表展示数据不准问题 2023-09-07 19:28:11 +08:00
ibuler
23723f4eda perf: 优化 ftp log 索引 2023-09-07 19:27:49 +08:00
Bai
38601a84c2 perf: 优化 GitHub Labels 2023-09-06 16:42:42 +08:00
fit2bot
e50189e284 fix: 修复工单审计员切换其他资产,原资产未删除问题 (#11511)
Co-authored-by: feng <1304903146@qq.com>
2023-09-06 15:13:02 +08:00
jiangweidong
da9bd11db5 feat: 系统工具支持traceroute (#11474) 2023-09-06 10:30:55 +08:00
Bai
9acb7d6183 perf: 优化 GitHub 默认 Assignees 2023-09-04 14:43:18 +05:00
Bai
dbd9a9fdac perf: 优化 GitHub 默认 Assignees 2023-09-04 12:03:16 +05:00
fit2bot
25301aa396 perf: 修改 sftp 的说明文案 (#11490)
* perf: 修改 sftp 的说明文案

* perf: 修改翻译问题

---------

Co-authored-by: ibuler <ibuler@qq.com>
2023-09-04 13:48:53 +08:00
老广
8cc1ca2770 Merge pull request #11483 from jumpserver/pr@dev@perf_db_cli
perf: 修改数据库 cli 连接方式的支持
2023-08-31 19:03:20 +08:00
Eric
bad01aefa2 perf: 修改数据库 cli 连接方式的支持 2023-08-31 18:23:30 +08:00
老广
56a989bfb9 Merge pull request #11481 from jumpserver/pr@dev@perf_online_num
perf: 修改在线数量
2023-08-31 17:44:25 +08:00
fit2bot
578f66d5e2 fix: 账号推送定时任务不执行 (#11482)
Co-authored-by: feng <1304903146@qq.com>
2023-08-31 17:43:52 +08:00
ibuler
8d6083bfb2 perf: 修改在线数量 2023-08-31 17:42:21 +08:00
fit2bot
1138cd3334 perf: 添加 session 在线数量 (#11464)
* perf: 添加 session 在线数量

* perf: 优化会话数量

* perf: 优化会话数量

---------

Co-authored-by: ibuler <ibuler@qq.com>
2023-08-31 17:00:03 +08:00
fit2bot
db0b43ee84 perf: 优化 dashboard api (#11478)
Co-authored-by: feng <1304903146@qq.com>
2023-08-31 15:05:05 +08:00
Bai
40a460870a fix: 优化 db_port 日志显示 2023-08-31 10:52:41 +05:00
fit2bot
51910ea2c1 fix: 修复历史会话为负数的情况 (#11472)
Co-authored-by: feng <1304903146@qq.com>
2023-08-30 18:18:08 +08:00
fit2bot
266a360a97 feat: 可查看全局被限制的ip 并且可以解锁 (#11394)
Co-authored-by: feng <1304903146@qq.com>
2023-08-30 17:31:59 +08:00
fit2bot
24194b4e4d perf: 翻译 (#11468)
Co-authored-by: feng <1304903146@qq.com>
2023-08-30 16:01:16 +08:00
fit2bot
992e34d652 feat: mysql 证书 (#11465)
Co-authored-by: feng <1304903146@qq.com>
2023-08-30 15:15:49 +08:00
老广
894249a3d1 Merge pull request #11452 from jumpserver/pr@dev@feat_audit_view_download_replay
feat: 查看/下载录像记录在操作及活动日志中
2023-08-30 13:48:53 +08:00
老广
21c6fe19a1 Merge pull request #11459 from jumpserver/pr@dev@metics
perf: dashboard date metrics
2023-08-30 13:26:31 +08:00
老广
e4e4f82143 Merge pull request #11461 from jumpserver/pr@dev@fix_cas_login_failed
fix: 解决CAS无法登陆问题
2023-08-30 13:25:30 +08:00
jiangweidong
2a5c635dc5 fix: 修改日志内容 2023-08-30 11:32:54 +08:00
jiangweidong
7dbaa28539 fix: 解决CAS无法登陆问题 2023-08-30 11:28:17 +08:00
feng
5bae4cde58 perf: dashboard date metrics 2023-08-29 22:04:08 +08:00
老广
35c0d7be35 Merge pull request #11455 from jumpserver/pr@dev@feat_settings_tool_ping_telnet_multi
feat: telnet、ping支持批量测试
2023-08-29 19:05:56 +08:00
jiangweidong
1f2a4b0fb5 feat: telnet、ping支持批量测试 2023-08-29 17:02:51 +08:00
jiangweidong
7c3a3d599b perf: 参数修改 2023-08-29 15:18:51 +08:00
jiangweidong
d70770775a perf: 翻译 2023-08-29 15:16:02 +08:00
jiangweidong
bc217e1bad Merge branch 'dev' of https://github.com/jumpserver/jumpserver into pr@dev@feat_audit_view_download_replay 2023-08-29 14:21:11 +08:00
jiangweidong
d4469aeaf7 feat: 查看/下载录像被记录在活动日志中 2023-08-29 14:21:06 +08:00
老广
904406c5c1 Merge pull request #11442 from jumpserver/pr@dev@fix_migrate_sftp
fix: 修复迁移的 sftp 数量不对
2023-08-28 19:03:28 +08:00
ibuler
09db2ad3e1 fix: 修复迁移的 sftp 数量不对 2023-08-28 16:48:22 +08:00
fit2bot
859268f7f3 perf: 优化账号创建 (#11440)
* feat: 支持账号模版自动推送
* perf: 修改模版
* perf: 优化账号创建

---------

Co-authored-by: ibuler <ibuler@qq.com>
2023-08-28 15:43:45 +08:00
老广
72bb5a4037 Merge pull request #11439 from jumpserver/pr@dev@change_tips
perf: 修改同名账号的提示
2023-08-28 11:25:55 +08:00
ibuler
6f3871d5fe perf: 修改同名账号的提示 2023-08-28 11:24:54 +08:00
“huailei000”
2f0c346365 perf: 优化不能生成MFA二维码问题 2023-08-25 12:01:51 +05:00
老广
e9c090f656 Merge pull request #11410 from hoilc/hoilc-patch-1
perf: 通过网域连接k8s时支持默认端口
2023-08-24 18:25:14 +08:00
老广
7b0b07cf52 Merge pull request #11415 from jumpserver/pr@dev@perf_select_host
perf: 优化 applet 发布机选择
2023-08-24 18:14:08 +08:00
ibuler
bebb90f688 perf: 优化 applet 发布机选择 2023-08-24 18:00:19 +08:00
hoilc
ac14a70c51 perf: 通过网域连接k8s时支持默认端口 2023-08-24 16:10:29 +08:00
jiangweidong
642f92c0a3 fix: saml2无法登陆问题 2023-08-24 11:05:50 +05:00
fit2bot
04f4ecb3d1 perf: 优化文案 (#11405)
Co-authored-by: ibuler <ibuler@qq.com>
2023-08-24 10:58:27 +08:00
老广
60703c920c Merge pull request #11381 from jumpserver/pr@dev@sqlserver_add_version
perf: sql server 添加驱动标识
2023-08-24 10:55:48 +08:00
ibuler
9634f397df perf: 不允许修改自己的角色 2023-08-23 16:11:05 +05:00
ibuler
f9a7a95191 fix: 修复 Host name 中包含 [ 导致 ansible 错误的问题 2023-08-23 16:07:58 +05:00
ibuler
bced33fd93 perf: sql server 添加驱动标识 2023-08-22 13:40:41 +08:00
老广
1044ff004b Merge pull request #11372 from jumpserver/pr@dev@device_add_sftp
perf: 网络设备支持 sftp
2023-08-21 15:40:30 +08:00
ibuler
e11c7a264e perf: 网络设备支持 sftp 2023-08-21 15:20:58 +08:00
老广
3c497aa81e Merge pull request #11361 from jumpserver/pr@dev@perf_login_csrf
perf: 修改 csrf 登录时判断
2023-08-18 20:44:25 +08:00
ibuler
c8a1f4b092 perf: 修改 csrf 登录时判断 2023-08-18 20:36:58 +08:00
老广
9dd2dc8907 Merge pull request #11358 from jumpserver/pr@dev@perf_csrf_token_error
perf: 修改 csrf token 提示
2023-08-18 18:42:50 +08:00
ibuler
56285d906f perf: 修改 csrf token 提示 2023-08-18 18:41:10 +08:00
ibuler
44b536a23b perf: 去掉 migrate 提示 2023-08-18 15:17:41 +05:00
老广
a97003a03a Merge pull request #11353 from jumpserver/pr@dev@perf_login_info
perf: 优化登录页面提示判断,可能没有端口
2023-08-18 18:00:26 +08:00
ibuler
4315cbe6d0 perf: 优化登录页面提示判断,可能没有端口
perf: 修改 login 检测
2023-08-18 17:59:13 +08:00
老广
b2d9670721 Merge pull request #11349 from jumpserver/pr@dev@perf_info
perf: 修改说明
2023-08-18 17:01:31 +08:00
ibuler
78f66c46e8 perf: 修改说明 2023-08-18 16:59:07 +08:00
老广
f3af9c3108 Merge pull request #11346 from jumpserver/pr@dev@fix_sessionshare
fix: 修复创建会话分享不填写用户报错的问题
2023-08-18 16:52:07 +08:00
ibuler
822a124dbc perf: 优化登录提示 2023-08-18 13:51:27 +05:00
Bai
20799ece93 fix: 修复创建会话分享不填写用户报错的问题 2023-08-18 08:46:14 +00:00
老广
4e2c7d7aab Merge pull request #11343 from jumpserver/pr@dev@allow_hosts_to_all
perf: 修改 allowed hosts
2023-08-18 16:17:25 +08:00
ibuler
75e4895314 perf: 修改 allowed hosts 2023-08-18 16:15:25 +08:00
Bai
ea7b409a7f fix: 修复资产树子节点创建后没有获取到的问题 2023-08-18 13:03:54 +05:00
老广
01d10a25e9 Merge pull request #11337 from jumpserver/pr@dev@perf_change_depends
perf: 修改依赖
2023-08-18 15:27:57 +08:00
ibuler
61ce39b4ba perf: 修改依赖 2023-08-18 15:19:26 +08:00
feng
7506c7ea43 fix: 修复密钥校验ansible不支持{% 2023-08-17 16:16:34 +05:00
老广
f6f162ec3a Merge pull request #11324 from jumpserver/pr@master@perf_django_ca_version
perf: 修改 django cas version
2023-08-17 17:43:23 +08:00
老广
2e840e3b05 Merge pull request #11323 from jumpserver/pr@dev@perf_django_ca_version
perf: 修改 django cas version
2023-08-17 17:43:04 +08:00
ibuler
ff4560c2a7 perf: 修改 django cas version 2023-08-17 09:42:27 +00:00
ibuler
deeb8da226 perf: 修改 django cas version 2023-08-17 17:39:58 +08:00
313 changed files with 8166 additions and 3315 deletions

View File

@@ -6,7 +6,6 @@ labels: 类型:需求
assignees:
- ibuler
- baijiangjie
- wojiushixiaobai
---
**请描述您的需求或者改进建议.**

View File

@@ -2,11 +2,9 @@
name: Bug 提交
about: 提交产品缺陷帮助我们更好的改进
title: "[Bug] "
labels: 类型:bug
labels: 类型:Bug
assignees:
- wojiushixiaobai
- baijiangjie
---
**JumpServer 版本( v2.28 之前的版本不再支持 )**

View File

@@ -4,9 +4,7 @@ about: 提出针对本项目安装部署、使用及其他方面的相关问题
title: "[Question] "
labels: 类型:提问
assignees:
- wojiushixiaobai
- baijiangjie
---
**请描述您的问题.**

View File

@@ -36,9 +36,11 @@ ARG TOOLS=" \
curl \
default-libmysqlclient-dev \
default-mysql-client \
iputils-ping \
locales \
nmap \
openssh-client \
patch \
sshpass \
telnet \
vim \

86
Dockerfile-ce Normal file
View File

@@ -0,0 +1,86 @@
FROM python:3.11-slim-bullseye as stage-build
ARG TARGETARCH
ARG VERSION
ENV VERSION=$VERSION
WORKDIR /opt/jumpserver
ADD . .
RUN cd utils && bash -ixeu build.sh
FROM python:3.11-slim-bullseye
ARG TARGETARCH
ARG BUILD_DEPENDENCIES=" \
g++ \
make \
pkg-config"
ARG DEPENDENCIES=" \
freetds-dev \
libpq-dev \
libffi-dev \
libjpeg-dev \
libkrb5-dev \
libldap2-dev \
libsasl2-dev \
libssl-dev \
libxml2-dev \
libxmlsec1-dev \
libxmlsec1-openssl \
freerdp2-dev \
libaio-dev"
ARG TOOLS=" \
ca-certificates \
curl \
default-libmysqlclient-dev \
default-mysql-client \
iputils-ping \
locales \
nmap \
openssh-client \
patch \
sshpass \
telnet \
vim \
wget"
ARG APT_MIRROR=http://mirrors.ustc.edu.cn
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,id=core \
sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list \
&& rm -f /etc/apt/apt.conf.d/docker-clean \
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& apt-get update \
&& apt-get -y install --no-install-recommends ${BUILD_DEPENDENCIES} \
&& apt-get -y install --no-install-recommends ${DEPENDENCIES} \
&& apt-get -y install --no-install-recommends ${TOOLS} \
&& mkdir -p /root/.ssh/ \
&& echo "Host *\n\tStrictHostKeyChecking no\n\tUserKnownHostsFile /dev/null\n\tCiphers +aes128-cbc\n\tKexAlgorithms +diffie-hellman-group1-sha1\n\tHostKeyAlgorithms +ssh-rsa" > /root/.ssh/config \
&& echo "set mouse-=a" > ~/.vimrc \
&& echo "no" | dpkg-reconfigure dash \
&& echo "zh_CN.UTF-8" | dpkg-reconfigure locales \
&& sed -i "s@# export @export @g" ~/.bashrc \
&& sed -i "s@# alias @alias @g" ~/.bashrc \
&& rm -rf /var/lib/apt/lists/*
COPY --from=stage-build /opt/jumpserver/release/jumpserver /opt/jumpserver
WORKDIR /opt/jumpserver
ARG PIP_MIRROR=https://pypi.tuna.tsinghua.edu.cn/simple
RUN --mount=type=cache,target=/root/.cache \
set -ex \
&& echo > /opt/jumpserver/config.yml \
&& pip install poetry -i ${PIP_MIRROR} \
&& poetry config virtualenvs.create false \
&& poetry install --only=main
VOLUME /opt/jumpserver/data
VOLUME /opt/jumpserver/logs
ENV LANG=zh_CN.UTF-8
EXPOSE 8080
ENTRYPOINT ["./entrypoint.sh"]

1
GITSHA Normal file
View File

@@ -0,0 +1 @@
11db46e61e1be24a851bd17f7d5b8b5da47aa3c3

View File

@@ -12,8 +12,6 @@
<p align="center">
JumpServer <a href="https://github.com/jumpserver/jumpserver/releases/tag/v3.0.0">v3.0</a> 正式发布。
<br>
9 年时间,倾情投入,用心做好一款开源堡垒机。
</p>

View File

@@ -6,11 +6,12 @@ from rest_framework.status import HTTP_200_OK
from accounts import serializers
from accounts.filters import AccountFilterSet
from accounts.mixins import AccountRecordViewLogMixin
from accounts.models import Account
from assets.models import Asset, Node
from common.api import ExtraFilterFieldsMixin
from common.permissions import UserConfirmation, ConfirmType, IsValidUser
from common.views.mixins import RecordViewLogMixin
from authentication.permissions import UserConfirmation, ConfirmType
from common.api.mixin import ExtraFilterFieldsMixin
from common.permissions import IsValidUser
from orgs.mixins.api import OrgBulkModelViewSet
from rbac.permissions import RBACPermission
@@ -57,19 +58,19 @@ class AccountViewSet(OrgBulkModelViewSet):
permission_classes=[IsValidUser]
)
def username_suggestions(self, request, *args, **kwargs):
asset_ids = request.data.get('assets')
node_ids = request.data.get('nodes')
username = request.data.get('username')
asset_ids = request.data.get('assets', [])
node_ids = request.data.get('nodes', [])
username = request.data.get('username', '')
assets = Asset.objects.all()
if asset_ids:
assets = assets.filter(id__in=asset_ids)
accounts = Account.objects.all()
if node_ids:
nodes = Node.objects.filter(id__in=node_ids)
node_asset_ids = Node.get_nodes_all_assets(*nodes).values_list('id', flat=True)
assets = assets.filter(id__in=set(list(asset_ids) + list(node_asset_ids)))
asset_ids.extend(node_asset_ids)
if asset_ids:
accounts = accounts.filter(asset_id__in=list(set(asset_ids)))
accounts = Account.objects.filter(asset__in=assets)
if username:
accounts = accounts.filter(username__icontains=username)
usernames = list(accounts.values_list('username', flat=True).distinct()[:10])
@@ -86,7 +87,7 @@ class AccountViewSet(OrgBulkModelViewSet):
return Response(status=HTTP_200_OK)
class AccountSecretsViewSet(RecordViewLogMixin, AccountViewSet):
class AccountSecretsViewSet(AccountRecordViewLogMixin, AccountViewSet):
"""
因为可能要导出所有账号,所以单独建立了一个 viewset
"""
@@ -115,7 +116,7 @@ class AssetAccountBulkCreateApi(CreateAPIView):
return Response(data=serializer.data, status=HTTP_200_OK)
class AccountHistoriesSecretAPI(ExtraFilterFieldsMixin, RecordViewLogMixin, ListAPIView):
class AccountHistoriesSecretAPI(ExtraFilterFieldsMixin, AccountRecordViewLogMixin, ListAPIView):
model = Account.history.model
serializer_class = serializers.AccountHistorySerializer
http_method_names = ['get', 'options']
@@ -143,4 +144,3 @@ class AccountHistoriesSecretAPI(ExtraFilterFieldsMixin, RecordViewLogMixin, List
return histories
histories = histories.exclude(history_id=latest_history.history_id)
return histories

View File

@@ -19,7 +19,9 @@ class AccountsTaskCreateAPI(CreateAPIView):
code = 'accounts.push_account'
else:
code = 'accounts.verify_account'
return request.user.has_perm(code)
has = request.user.has_perm(code)
if not has:
self.permission_denied(request)
def perform_create(self, serializer):
data = serializer.validated_data
@@ -44,6 +46,6 @@ class AccountsTaskCreateAPI(CreateAPIView):
def get_exception_handler(self):
def handler(e, context):
return Response({"error": str(e)}, status=400)
return Response({"error": str(e)}, status=401)
return handler

View File

@@ -1,13 +1,15 @@
from django_filters import rest_framework as drf_filters
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from accounts import serializers
from accounts.mixins import AccountRecordViewLogMixin
from accounts.models import AccountTemplate
from accounts.tasks import template_sync_related_accounts
from assets.const import Protocol
from authentication.permissions import UserConfirmation, ConfirmType
from common.drf.filters import BaseFilterSet
from common.permissions import UserConfirmation, ConfirmType
from common.views.mixins import RecordViewLogMixin
from orgs.mixins.api import OrgBulkModelViewSet
from rbac.permissions import RBACPermission
@@ -44,6 +46,7 @@ class AccountTemplateViewSet(OrgBulkModelViewSet):
}
rbac_perms = {
'su_from_account_templates': 'accounts.view_accounttemplate',
'sync_related_accounts': 'accounts.change_account',
}
@action(methods=['get'], detail=False, url_path='su-from-account-templates')
@@ -54,8 +57,15 @@ class AccountTemplateViewSet(OrgBulkModelViewSet):
serializer = self.get_serializer(templates, many=True)
return Response(data=serializer.data)
@action(methods=['patch'], detail=True, url_path='sync-related-accounts')
def sync_related_accounts(self, request, *args, **kwargs):
instance = self.get_object()
user_id = str(request.user.id)
task = template_sync_related_accounts.delay(str(instance.id), user_id)
return Response({'task': task.id}, status=status.HTTP_200_OK)
class AccountTemplateSecretsViewSet(RecordViewLogMixin, AccountTemplateViewSet):
class AccountTemplateSecretsViewSet(AccountRecordViewLogMixin, AccountTemplateViewSet):
serializer_classes = {
'default': serializers.AccountTemplateSecretSerializer,
}

View File

@@ -5,8 +5,7 @@ from rest_framework import mixins
from accounts import serializers
from accounts.const import AutomationTypes
from accounts.models import ChangeSecretAutomation, ChangeSecretRecord, AutomationExecution
from common.utils import get_object_or_none
from accounts.models import ChangeSecretAutomation, ChangeSecretRecord
from orgs.mixins.api import OrgBulkModelViewSet, OrgGenericViewSet
from .base import (
AutomationAssetsListApi, AutomationRemoveAssetApi, AutomationAddAssetApi,
@@ -30,8 +29,8 @@ class ChangeSecretAutomationViewSet(OrgBulkModelViewSet):
class ChangeSecretRecordViewSet(mixins.ListModelMixin, OrgGenericViewSet):
serializer_class = serializers.ChangeSecretRecordSerializer
filter_fields = ['asset', 'execution_id']
search_fields = ['asset__hostname']
filter_fields = ('asset', 'execution_id')
search_fields = ('asset__address',)
def get_queryset(self):
return ChangeSecretRecord.objects.filter(
@@ -41,10 +40,7 @@ class ChangeSecretRecordViewSet(mixins.ListModelMixin, OrgGenericViewSet):
def filter_queryset(self, queryset):
queryset = super().filter_queryset(queryset)
eid = self.request.query_params.get('execution_id')
execution = get_object_or_none(AutomationExecution, pk=eid)
if execution:
queryset = queryset.filter(execution=execution)
return queryset
return queryset.filter(execution_id=eid)
class ChangSecretExecutionViewSet(AutomationExecutionViewSet):

View File

@@ -47,4 +47,8 @@
login_password: "{{ account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
become: false
become: "{{ account.become.ansible_become | default(False) }}"
become_method: su
become_user: "{{ account.become.ansible_user | default('') }}"
become_password: "{{ account.become.ansible_password | default('') }}"
become_private_key_path: "{{ account.become.ansible_ssh_private_key_file | default(None) }}"

View File

@@ -11,9 +11,9 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl: "{{ jms_asset.spec_info.use_ssl | default('') }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
register: db_info
@@ -31,8 +31,8 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
db: "{{ jms_asset.spec_info.db_name }}"
@@ -49,7 +49,7 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"

View File

@@ -11,6 +11,10 @@
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
filter: version
register: db_info
@@ -24,6 +28,10 @@
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
name: "{{ account.username }}"
password: "{{ account.secret }}"
host: "%"
@@ -37,4 +45,8 @@
login_password: "{{ account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
filter: version

View File

@@ -40,7 +40,7 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
script: "ALTER LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}'; select @@version"
script: "ALTER LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}', DEFAULT_DATABASE = {{ jms_asset.spec_info.db_name }}; select @@version"
ignore_errors: true
when: user_exist.query_results[0] | length != 0
@@ -51,7 +51,7 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
script: "CREATE LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}'; select @@version"
script: "CREATE LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}', DEFAULT_DATABASE = {{ jms_asset.spec_info.db_name }}; CREATE USER {{ account.username }} FOR LOGIN {{ account.username }}; select @@version"
ignore_errors: true
when: user_exist.query_results[0] | length == 0

View File

@@ -80,7 +80,11 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
gateway_args: "{{ jms_asset.ansible_ssh_common_args | default('') }}"
become: false
become: "{{ account.become.ansible_become | default(False) }}"
become_method: su
become_user: "{{ account.become.ansible_user | default('') }}"
become_password: "{{ account.become.ansible_password | default('') }}"
become_private_key_path: "{{ account.become.ansible_ssh_private_key_file | default(None) }}"
when: account.secret_type == "password"
delegate_to: localhost
@@ -91,6 +95,5 @@
login_user: "{{ account.username }}"
login_private_key_path: "{{ account.private_key_path }}"
gateway_args: "{{ jms_asset.ansible_ssh_common_args | default('') }}"
become: false
when: account.secret_type == "ssh_key"
delegate_to: localhost

View File

@@ -80,7 +80,11 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
gateway_args: "{{ jms_asset.ansible_ssh_common_args | default('') }}"
become: false
become: "{{ account.become.ansible_become | default(False) }}"
become_method: su
become_user: "{{ account.become.ansible_user | default('') }}"
become_password: "{{ account.become.ansible_password | default('') }}"
become_private_key_path: "{{ account.become.ansible_ssh_private_key_file | default(None) }}"
when: account.secret_type == "password"
delegate_to: localhost
@@ -91,6 +95,5 @@
login_user: "{{ account.username }}"
login_private_key_path: "{{ account.private_key_path }}"
gateway_args: "{{ jms_asset.ansible_ssh_common_args | default('') }}"
become: false
when: account.secret_type == "ssh_key"
delegate_to: localhost

View File

@@ -136,7 +136,8 @@ class ChangeSecretManager(AccountBasePlaybookManager):
'username': account.username,
'secret_type': secret_type,
'secret': new_secret,
'private_key_path': private_key_path
'private_key_path': private_key_path,
'become': account.get_ansible_become_auth(),
}
if asset.platform.type == 'oracle':
h['account']['mode'] = 'sysdba' if account.privileged else None

View File

@@ -12,8 +12,8 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
filter: users

View File

@@ -10,6 +10,10 @@
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
filter: users
register: db_info

View File

@@ -12,8 +12,8 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
register: db_info
@@ -31,8 +31,8 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
db: "{{ jms_asset.spec_info.db_name }}"
@@ -49,7 +49,7 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"

View File

@@ -11,6 +11,10 @@
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
filter: version
register: db_info
@@ -24,6 +28,10 @@
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
name: "{{ account.username }}"
password: "{{ account.secret }}"
host: "%"
@@ -37,4 +45,8 @@
login_password: "{{ account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
filter: version

View File

@@ -31,6 +31,7 @@
role_attr_flags: LOGIN
ignore_errors: true
when: result is succeeded
register: change_info
- name: Verify password
community.postgresql.postgresql_ping:
@@ -42,3 +43,5 @@
when:
- result is succeeded
- change_info is succeeded
register: result
failed_when: not result.is_available

View File

@@ -40,7 +40,7 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
script: "ALTER LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}'; select @@version"
script: "ALTER LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}', DEFAULT_DATABASE = {{ jms_asset.spec_info.db_name }}; select @@version"
ignore_errors: true
when: user_exist.query_results[0] | length != 0
register: change_info
@@ -52,7 +52,7 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
name: '{{ jms_asset.spec_info.db_name }}'
script: "CREATE LOGIN {{ account.username }} WITH PASSWORD = '{{ account.secret }}'; select @@version"
script: "CREATE LOGIN [{{ account.username }}] WITH PASSWORD = '{{ account.secret }}'; CREATE USER [{{ account.username }}] FOR LOGIN [{{ account.username }}]; select @@version"
ignore_errors: true
when: user_exist.query_results[0] | length == 0
register: change_info

View File

@@ -80,7 +80,11 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
gateway_args: "{{ jms_asset.ansible_ssh_common_args | default('') }}"
become: false
become: "{{ account.become.ansible_become | default(False) }}"
become_method: su
become_user: "{{ account.become.ansible_user | default('') }}"
become_password: "{{ account.become.ansible_password | default('') }}"
become_private_key_path: "{{ account.become.ansible_ssh_private_key_file | default(None) }}"
when: account.secret_type == "password"
delegate_to: localhost
@@ -91,7 +95,6 @@
login_user: "{{ account.username }}"
login_private_key_path: "{{ account.private_key_path }}"
gateway_args: "{{ jms_asset.ansible_ssh_common_args | default('') }}"
become: false
when: account.secret_type == "ssh_key"
delegate_to: localhost

View File

@@ -80,7 +80,11 @@
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
gateway_args: "{{ jms_asset.ansible_ssh_common_args | default('') }}"
become: false
become: "{{ account.become.ansible_become | default(False) }}"
become_method: su
become_user: "{{ account.become.ansible_user | default('') }}"
become_password: "{{ account.become.ansible_password | default('') }}"
become_private_key_path: "{{ account.become.ansible_ssh_private_key_file | default(None) }}"
when: account.secret_type == "password"
delegate_to: localhost
@@ -91,7 +95,6 @@
login_user: "{{ account.username }}"
login_private_key_path: "{{ account.private_key_path }}"
gateway_args: "{{ jms_asset.ansible_ssh_common_args | default('') }}"
become: false
when: account.secret_type == "ssh_key"
delegate_to: localhost

View File

@@ -56,7 +56,8 @@ class PushAccountManager(ChangeSecretManager, AccountBasePlaybookManager):
'username': account.username,
'secret_type': secret_type,
'secret': new_secret,
'private_key_path': private_key_path
'private_key_path': private_key_path,
'become': account.get_ansible_become_auth(),
}
if asset.platform.type == 'oracle':
h['account']['mode'] = 'sysdba' if account.privileged else None
@@ -80,7 +81,7 @@ class PushAccountManager(ChangeSecretManager, AccountBasePlaybookManager):
pass
def on_runner_failed(self, runner, e):
logger.error("Pust account error: ", e)
logger.error("Pust account error: {}".format(e))
def run(self, *args, **kwargs):
if self.secret_type and not self.check_secret():

View File

@@ -8,7 +8,7 @@
- name: Verify account (pyfreerdp)
rdp_ping:
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
login_port: "{{ jms_asset.protocols | selectattr('name', 'equalto', 'rdp') | map(attribute='port') | first }}"
login_user: "{{ account.username }}"
login_password: "{{ account.secret }}"
login_secret_type: "{{ account.secret_type }}"

View File

@@ -13,8 +13,8 @@
login_password: "{{ account.secret }}"
login_secret_type: "{{ account.secret_type }}"
login_private_key_path: "{{ account.private_key_path }}"
become: "{{ custom_become | default(False) }}"
become_method: "{{ custom_become_method | default('su') }}"
become_user: "{{ custom_become_user | default('') }}"
become_password: "{{ custom_become_password | default('') }}"
become_private_key_path: "{{ custom_become_private_key_path | default(None) }}"
become: "{{ account.become.ansible_become | default(False) }}"
become_method: "{{ account.become.ansible_become_method | default('su') }}"
become_user: "{{ account.become.ansible_user | default('') }}"
become_password: "{{ account.become.ansible_password | default('') }}"
become_private_key_path: "{{ account.become.ansible_ssh_private_key_file | default(None) }}"

View File

@@ -12,7 +12,7 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert }}"

View File

@@ -10,4 +10,8 @@
login_password: "{{ account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
filter: version

View File

@@ -3,7 +3,6 @@
vars:
ansible_python_interpreter: /usr/local/bin/python
tasks:
- name: Verify account
community.postgresql.postgresql_ping:

View File

@@ -1,11 +1,23 @@
- hosts: demo
gather_facts: no
tasks:
- name: Verify account connectivity
become: no
- name: Verify account connectivity(Do not switch)
ansible.builtin.ping:
vars:
ansible_become: no
ansible_user: "{{ account.username }}"
ansible_password: "{{ account.secret }}"
ansible_ssh_private_key_file: "{{ account.private_key_path }}"
when: not account.become.ansible_become
- name: Verify account connectivity(Switch)
ansible.builtin.ping:
vars:
ansible_become: yes
ansible_user: "{{ account.become.ansible_user }}"
ansible_password: "{{ account.become.ansible_password }}"
ansible_ssh_private_key_file: "{{ account.become.ansible_ssh_private_key_file }}"
ansible_become_method: "{{ account.become.ansible_become_method }}"
ansible_become_user: "{{ account.become.ansible_become_user }}"
ansible_become_password: "{{ account.become.ansible_become_password }}"
when: account.become.ansible_become

View File

@@ -42,7 +42,6 @@ class VerifyAccountManager(AccountBasePlaybookManager):
if host.get('error'):
return host
# host['ssh_args'] = '-o ControlMaster=no -o ControlPersist=no'
accounts = asset.accounts.all()
accounts = self.get_accounts(account, accounts)
inventory_hosts = []
@@ -64,7 +63,8 @@ class VerifyAccountManager(AccountBasePlaybookManager):
'username': account.username,
'secret_type': account.secret_type,
'secret': secret,
'private_key_path': private_key_path
'private_key_path': private_key_path,
'become': account.get_ansible_become_auth(),
}
if account.platform.type == 'oracle':
h['account']['mode'] = 'sysdba' if account.privileged else None

View File

@@ -4,11 +4,13 @@ from django.utils.translation import gettext_lazy as _
from assets.const import Connectivity
from common.db.fields import TreeChoices
string_punctuation = '!#$%&()*+,-.:;<=>?@[]^_~'
DEFAULT_PASSWORD_LENGTH = 30
DEFAULT_PASSWORD_RULES = {
'length': DEFAULT_PASSWORD_LENGTH,
'symbol_set': string_punctuation
'uppercase': True,
'lowercase': True,
'digit': True,
'symbol': True,
}
__all__ = [
@@ -41,8 +43,8 @@ class AutomationTypes(models.TextChoices):
class SecretStrategy(models.TextChoices):
custom = 'specific', _('Specific password')
random = 'random', _('Random')
custom = 'specific', _('Specific secret')
random = 'random', _('Random generate')
class SSHKeyStrategy(models.TextChoices):

View File

@@ -38,7 +38,7 @@ class Migration(migrations.Migration):
'verbose_name': 'Automation execution',
'verbose_name_plural': 'Automation executions',
'permissions': [('view_changesecretexecution', 'Can view change secret execution'),
('add_changesecretexection', 'Can add change secret execution'),
('add_changesecretexecution', 'Can add change secret execution'),
('view_gatheraccountsexecution', 'Can view gather accounts execution'),
('add_gatheraccountsexecution', 'Can add gather accounts execution')],
'proxy': True,
@@ -113,7 +113,7 @@ class Migration(migrations.Migration):
('comment', models.TextField(blank=True, default='', verbose_name='Comment')),
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('old_secret', common.db.fields.EncryptTextField(blank=True, null=True, verbose_name='Old secret')),
('new_secret', common.db.fields.EncryptTextField(blank=True, null=True, verbose_name='Secret')),
('new_secret', common.db.fields.EncryptTextField(blank=True, null=True, verbose_name='New secret')),
('date_started', models.DateTimeField(blank=True, null=True, verbose_name='Date started')),
('date_finished', models.DateTimeField(blank=True, null=True, verbose_name='Date finished')),
('status', models.CharField(default='pending', max_length=16)),
@@ -184,7 +184,7 @@ class Migration(migrations.Migration):
migrations.AlterModelOptions(
name='automationexecution',
options={'permissions': [('view_changesecretexecution', 'Can view change secret execution'),
('add_changesecretexection', 'Can add change secret execution'),
('add_changesecretexecution', 'Can add change secret execution'),
('view_gatheraccountsexecution', 'Can view gather accounts execution'),
('add_gatheraccountsexecution', 'Can add gather accounts execution'),
('view_pushaccountexecution', 'Can view push account execution'),

View File

@@ -13,11 +13,11 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='changesecretautomation',
name='secret_strategy',
field=models.CharField(choices=[('specific', 'Specific password'), ('random', 'Random')], default='specific', max_length=16, verbose_name='Secret strategy'),
field=models.CharField(choices=[('specific', 'Specific secret'), ('random', 'Random generate')], default='specific', max_length=16, verbose_name='Secret strategy'),
),
migrations.AlterField(
model_name='pushaccountautomation',
name='secret_strategy',
field=models.CharField(choices=[('specific', 'Specific password'), ('random', 'Random')], default='specific', max_length=16, verbose_name='Secret strategy'),
field=models.CharField(choices=[('specific', 'Specific secret'), ('random', 'Random generate')], default='specific', max_length=16, verbose_name='Secret strategy'),
),
]

View File

@@ -0,0 +1,34 @@
# Generated by Django 4.1.10 on 2023-08-25 03:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assets', '0122_auto_20230803_1553'),
('accounts', '0014_virtualaccount'),
]
operations = [
migrations.AddField(
model_name='accounttemplate',
name='auto_push',
field=models.BooleanField(default=False, verbose_name='Auto push'),
),
migrations.AddField(
model_name='accounttemplate',
name='platforms',
field=models.ManyToManyField(related_name='account_templates', to='assets.platform', verbose_name='Platforms', blank=True),
),
migrations.AddField(
model_name='accounttemplate',
name='push_params',
field=models.JSONField(default=dict, verbose_name='Push params'),
),
migrations.AddField(
model_name='accounttemplate',
name='secret_strategy',
field=models.CharField(choices=[('specific', 'Specific secret'), ('random', 'Random generate')], default='specific', max_length=16, verbose_name='Secret strategy'),
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 4.1.10 on 2023-09-18 08:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0015_auto_20230825_1120'),
]
operations = [
migrations.AddField(
model_name='accounttemplate',
name='password_rules',
field=models.JSONField(default=dict, verbose_name='Password rules'),
),
]

View File

@@ -0,0 +1,25 @@
# Generated by Django 4.1.10 on 2023-10-24 05:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0016_accounttemplate_password_rules'),
]
operations = [
migrations.AlterModelOptions(
name='automationexecution',
options={
'permissions': [
('view_changesecretexecution', 'Can view change secret execution'),
('add_changesecretexecution', 'Can add change secret execution'),
('view_gatheraccountsexecution', 'Can view gather accounts execution'),
('add_gatheraccountsexecution', 'Can add gather accounts execution'),
('view_pushaccountexecution', 'Can view push account execution'),
('add_pushaccountexecution', 'Can add push account execution')
],
'verbose_name': 'Automation execution', 'verbose_name_plural': 'Automation executions'},
),
]

75
apps/accounts/mixins.py Normal file
View File

@@ -0,0 +1,75 @@
from rest_framework.response import Response
from rest_framework import status
from django.utils import translation
from django.utils.translation import gettext_noop
from audits.const import ActionChoices
from common.views.mixins import RecordViewLogMixin
from common.utils import i18n_fmt
class AccountRecordViewLogMixin(RecordViewLogMixin):
get_object: callable
get_queryset: callable
@staticmethod
def _filter_params(params):
new_params = {}
need_pop_params = ('format', 'order')
for key, value in params.items():
if key in need_pop_params:
continue
if isinstance(value, list):
value = list(filter(None, value))
if value:
new_params[key] = value
return new_params
def get_resource_display(self, request):
query_params = dict(request.query_params)
params = self._filter_params(query_params)
spm_filter = params.pop("spm", None)
if not params and not spm_filter:
display_message = gettext_noop("Export all")
elif spm_filter:
display_message = gettext_noop("Export only selected items")
else:
query = ",".join(
["%s=%s" % (key, value) for key, value in params.items()]
)
display_message = i18n_fmt(gettext_noop("Export filtered: %s"), query)
return display_message
@property
def detail_msg(self):
return i18n_fmt(
gettext_noop('User %s view/export secret'), self.request.user
)
def list(self, request, *args, **kwargs):
list_func = getattr(super(), 'list')
if not callable(list_func):
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
response = list_func(request, *args, **kwargs)
with translation.override('en'):
resource_display = self.get_resource_display(request)
ids = [q.id for q in self.get_queryset()]
self.record_logs(
ids, ActionChoices.view, self.detail_msg, resource_display=resource_display
)
return response
def retrieve(self, request, *args, **kwargs):
retrieve_func = getattr(super(), 'retrieve')
if not callable(retrieve_func):
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
response = retrieve_func(request, *args, **kwargs)
with translation.override('en'):
resource = self.get_object()
self.record_logs(
[resource.id], ActionChoices.view, self.detail_msg, resource=resource
)
return response

View File

@@ -1,5 +1,5 @@
from .account import *
from .automations import *
from .base import *
from .template import *
from .virtual import *
from .account import * # noqa
from .base import * # noqa
from .automations import * # noqa
from .template import * # noqa
from .virtual import * # noqa

View File

@@ -95,6 +95,33 @@ class Account(AbsConnectivity, BaseAccount):
""" 排除自己和以自己为 su-from 的账号 """
return self.asset.accounts.exclude(id=self.id).exclude(su_from=self)
@staticmethod
def make_account_ansible_vars(su_from):
var = {
'ansible_user': su_from.username,
}
if not su_from.secret:
return var
var['ansible_password'] = su_from.secret
var['ansible_ssh_private_key_file'] = su_from.private_key_path
return var
def get_ansible_become_auth(self):
su_from = self.su_from
platform = self.platform
auth = {'ansible_become': False}
if not (platform.su_enabled and su_from):
return auth
auth.update(self.make_account_ansible_vars(su_from))
become_method = 'sudo' if platform.su_method != 'su' else 'su'
password = su_from.secret if become_method == 'sudo' else self.secret
auth['ansible_become'] = True
auth['ansible_become_method'] = become_method
auth['ansible_become_user'] = self.username
auth['ansible_become_password'] = password
return auth
def replace_history_model_with_mixin():
"""

View File

@@ -1,12 +1,15 @@
from django.db import models
from django.utils.translation import gettext_lazy as _
from accounts.const import SSHKeyStrategy
from accounts.models import Account, SecretWithRandomMixin
from accounts.tasks import execute_account_automation_task
from assets.models.automations import (
BaseAutomation as AssetBaseAutomation,
AutomationExecution as AssetAutomationExecution
)
__all__ = ['AccountBaseAutomation', 'AutomationExecution']
__all__ = ['AccountBaseAutomation', 'AutomationExecution', 'ChangeSecretMixin']
class AccountBaseAutomation(AssetBaseAutomation):
@@ -30,7 +33,7 @@ class AutomationExecution(AssetAutomationExecution):
verbose_name_plural = _("Automation executions")
permissions = [
('view_changesecretexecution', _('Can view change secret execution')),
('add_changesecretexection', _('Can add change secret execution')),
('add_changesecretexecution', _('Can add change secret execution')),
('view_gatheraccountsexecution', _('Can view gather accounts execution')),
('add_gatheraccountsexecution', _('Can add gather accounts execution')),
@@ -43,3 +46,40 @@ class AutomationExecution(AssetAutomationExecution):
from accounts.automations.endpoint import ExecutionManager
manager = ExecutionManager(execution=self)
return manager.run()
class ChangeSecretMixin(SecretWithRandomMixin):
ssh_key_change_strategy = models.CharField(
choices=SSHKeyStrategy.choices, max_length=16,
default=SSHKeyStrategy.add, verbose_name=_('SSH key change strategy')
)
get_all_assets: callable # get all assets
class Meta:
abstract = True
def create_nonlocal_accounts(self, usernames, asset):
pass
def get_account_ids(self):
usernames = self.accounts
accounts = Account.objects.none()
for asset in self.get_all_assets():
self.create_nonlocal_accounts(usernames, asset)
accounts = accounts | asset.accounts.all()
account_ids = accounts.filter(
username__in=usernames, secret_type=self.secret_type
).values_list('id', flat=True)
return [str(_id) for _id in account_ids]
def to_attr_json(self):
attr_json = super().to_attr_json()
attr_json.update({
'secret': self.secret,
'secret_type': self.secret_type,
'accounts': self.get_account_ids(),
'password_rules': self.password_rules,
'secret_strategy': self.secret_strategy,
'ssh_key_change_strategy': self.ssh_key_change_strategy,
})
return attr_json

View File

@@ -2,62 +2,13 @@ from django.db import models
from django.utils.translation import gettext_lazy as _
from accounts.const import (
AutomationTypes, SecretType, SecretStrategy, SSHKeyStrategy
AutomationTypes
)
from accounts.models import Account
from common.db import fields
from common.db.models import JMSBaseModel
from .base import AccountBaseAutomation
from .base import AccountBaseAutomation, ChangeSecretMixin
__all__ = ['ChangeSecretAutomation', 'ChangeSecretRecord', 'ChangeSecretMixin']
class ChangeSecretMixin(models.Model):
secret_type = models.CharField(
choices=SecretType.choices, max_length=16,
default=SecretType.PASSWORD, verbose_name=_('Secret type')
)
secret = fields.EncryptTextField(blank=True, null=True, verbose_name=_('Secret'))
secret_strategy = models.CharField(
choices=SecretStrategy.choices, max_length=16,
default=SecretStrategy.custom, verbose_name=_('Secret strategy')
)
password_rules = models.JSONField(default=dict, verbose_name=_('Password rules'))
ssh_key_change_strategy = models.CharField(
choices=SSHKeyStrategy.choices, max_length=16,
default=SSHKeyStrategy.add, verbose_name=_('SSH key change strategy')
)
get_all_assets: callable # get all assets
class Meta:
abstract = True
def create_nonlocal_accounts(self, usernames, asset):
pass
def get_account_ids(self):
usernames = self.accounts
accounts = Account.objects.none()
for asset in self.get_all_assets():
self.create_nonlocal_accounts(usernames, asset)
accounts = accounts | asset.accounts.all()
account_ids = accounts.filter(
username__in=usernames, secret_type=self.secret_type
).values_list('id', flat=True)
return [str(_id) for _id in account_ids]
def to_attr_json(self):
attr_json = super().to_attr_json()
attr_json.update({
'secret': self.secret,
'secret_type': self.secret_type,
'accounts': self.get_account_ids(),
'password_rules': self.password_rules,
'secret_strategy': self.secret_strategy,
'ssh_key_change_strategy': self.ssh_key_change_strategy,
})
return attr_json
__all__ = ['ChangeSecretAutomation', 'ChangeSecretRecord', ]
class ChangeSecretAutomation(ChangeSecretMixin, AccountBaseAutomation):

View File

@@ -1,9 +1,9 @@
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from accounts.const import AutomationTypes
from accounts.models import Account
from jumpserver.utils import has_valid_xpack_license
from .base import AccountBaseAutomation
from .change_secret import ChangeSecretMixin
@@ -17,9 +17,9 @@ class PushAccountAutomation(ChangeSecretMixin, AccountBaseAutomation):
def create_nonlocal_accounts(self, usernames, asset):
secret_type = self.secret_type
account_usernames = asset.accounts.filter(secret_type=self.secret_type).values_list(
'username', flat=True
)
account_usernames = asset.accounts \
.filter(secret_type=self.secret_type) \
.values_list('username', flat=True)
create_usernames = set(usernames) - set(account_usernames)
create_account_objs = [
Account(
@@ -30,9 +30,6 @@ class PushAccountAutomation(ChangeSecretMixin, AccountBaseAutomation):
]
Account.objects.bulk_create(create_account_objs)
def set_period_schedule(self):
pass
@property
def dynamic_username(self):
return self.username == '@USER'
@@ -44,7 +41,7 @@ class PushAccountAutomation(ChangeSecretMixin, AccountBaseAutomation):
def save(self, *args, **kwargs):
self.type = AutomationTypes.push_account
if not has_valid_xpack_license():
if not settings.XPACK_LICENSE_IS_VALID:
self.is_periodic = False
super().save(*args, **kwargs)

View File

@@ -8,12 +8,14 @@ from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from accounts.const import SecretType
from accounts.const import SecretType, SecretStrategy
from accounts.models.mixins import VaultModelMixin, VaultManagerMixin, VaultQuerySetMixin
from accounts.utils import SecretGenerator
from common.db import fields
from common.utils import (
ssh_key_string_to_obj, ssh_key_gen, get_logger,
random_string, lazyproperty, parse_ssh_public_key_str, is_openssh_format_key
)
from accounts.models.mixins import VaultModelMixin, VaultManagerMixin, VaultQuerySetMixin
from orgs.mixins.models import JMSOrgBaseModel, OrgManager
logger = get_logger(__file__)
@@ -29,6 +31,35 @@ class BaseAccountManager(VaultManagerMixin, OrgManager):
return self.get_queryset().active()
class SecretWithRandomMixin(models.Model):
secret_type = models.CharField(
choices=SecretType.choices, max_length=16,
default=SecretType.PASSWORD, verbose_name=_('Secret type')
)
secret = fields.EncryptTextField(blank=True, null=True, verbose_name=_('Secret'))
secret_strategy = models.CharField(
choices=SecretStrategy.choices, max_length=16,
default=SecretStrategy.custom, verbose_name=_('Secret strategy')
)
password_rules = models.JSONField(default=dict, verbose_name=_('Password rules'))
class Meta:
abstract = True
@lazyproperty
def secret_generator(self):
return SecretGenerator(
self.secret_strategy, self.secret_type,
self.password_rules,
)
def get_secret(self):
if self.secret_strategy == 'random':
return self.secret_generator.get_secret()
else:
return self.secret
class BaseAccount(VaultModelMixin, JMSOrgBaseModel):
name = models.CharField(max_length=128, verbose_name=_("Name"))
username = models.CharField(max_length=128, blank=True, verbose_name=_('Username'), db_index=True)

View File

@@ -37,8 +37,9 @@ class VaultManagerMixin(models.Manager):
post_save.send(obj.__class__, instance=obj, created=True)
return objs
def bulk_update(self, objs, batch_size=None, ignore_conflicts=False):
objs = super().bulk_update(objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts)
def bulk_update(self, objs, fields, batch_size=None):
fields = ["_secret" if field == "secret" else field for field in fields]
super().bulk_update(objs, fields, batch_size=batch_size)
for obj in objs:
post_save.send(obj.__class__, instance=obj, created=False)
return objs

View File

@@ -4,16 +4,22 @@ from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from .account import Account
from .base import BaseAccount
from .base import BaseAccount, SecretWithRandomMixin
__all__ = ['AccountTemplate', ]
class AccountTemplate(BaseAccount):
class AccountTemplate(BaseAccount, SecretWithRandomMixin):
su_from = models.ForeignKey(
'self', related_name='su_to', null=True,
on_delete=models.SET_NULL, verbose_name=_("Su from")
)
auto_push = models.BooleanField(default=False, verbose_name=_('Auto push'))
platforms = models.ManyToManyField(
'assets.Platform', related_name='account_templates',
verbose_name=_('Platforms'), blank=True,
)
push_params = models.JSONField(default=dict, verbose_name=_('Push params'))
class Meta:
verbose_name = _('Account template')
@@ -25,15 +31,15 @@ class AccountTemplate(BaseAccount):
('change_accounttemplatesecret', _('Can change asset account template secret')),
]
def __str__(self):
return f'{self.name}({self.username})'
@classmethod
def get_su_from_account_templates(cls, pk=None):
if pk is None:
return cls.objects.all()
return cls.objects.exclude(Q(id=pk) | Q(su_from_id=pk))
def __str__(self):
return f'{self.name}({self.username})'
def get_su_from_account(self, asset):
su_from = self.su_from
if su_from and asset.platform.su_enabled:
@@ -43,8 +49,7 @@ class AccountTemplate(BaseAccount):
).first()
return account
@staticmethod
def bulk_update_accounts(accounts, data):
def bulk_update_accounts(self, accounts):
history_model = Account.history.model
account_ids = accounts.values_list('id', flat=True)
history_accounts = history_model.objects.filter(id__in=account_ids)
@@ -57,8 +62,7 @@ class AccountTemplate(BaseAccount):
for account in accounts:
account_id = str(account.id)
account.version = account_id_count_map.get(account_id) + 1
for k, v in data.items():
setattr(account, k, v)
account.secret = self.get_secret()
Account.objects.bulk_update(accounts, ['version', 'secret'])
@staticmethod
@@ -80,7 +84,5 @@ class AccountTemplate(BaseAccount):
def bulk_sync_account_secret(self, accounts, user_id):
""" 批量同步账号密码 """
if not accounts:
return
self.bulk_update_accounts(accounts, {'secret': self.secret})
self.bulk_update_accounts(accounts)
self.bulk_create_history_accounts(accounts, user_id)

View File

@@ -2,6 +2,7 @@ import uuid
from copy import deepcopy
from django.db import IntegrityError
from django.db import transaction
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
@@ -73,6 +74,23 @@ class AccountCreateUpdateSerializerMixin(serializers.Serializer):
name = name + '_' + uuid.uuid4().hex[:4]
initial_data['name'] = name
@staticmethod
def get_template_attr_for_account(template):
# Set initial data from template
field_names = [
'name', 'username', 'secret',
'secret_type', 'privileged', 'is_active'
]
attrs = {}
for name in field_names:
value = getattr(template, name, None)
if value is None:
continue
attrs[name] = value
attrs['secret'] = template.get_secret()
return attrs
def from_template_if_need(self, initial_data):
if isinstance(initial_data, str):
return
@@ -89,20 +107,7 @@ class AccountCreateUpdateSerializerMixin(serializers.Serializer):
raise serializers.ValidationError({'template': 'Template not found'})
self._template = template
# Set initial data from template
ignore_fields = ['id', 'date_created', 'date_updated', 'su_from', 'org_id']
field_names = [
field.name for field in template._meta.fields
if field.name not in ignore_fields
]
field_names = [name if name != '_secret' else 'secret' for name in field_names]
attrs = {}
for name in field_names:
value = getattr(template, name, None)
if value is None:
continue
attrs[name] = value
attrs = self.get_template_attr_for_account(template)
initial_data.update(attrs)
initial_data.update({
'source': Source.TEMPLATE,
@@ -114,10 +119,13 @@ class AccountCreateUpdateSerializerMixin(serializers.Serializer):
asset = get_object_or_404(Asset, pk=asset_id)
initial_data['su_from'] = template.get_su_from_account(asset)
@staticmethod
def push_account_if_need(instance, push_now, params, stat):
def push_account_if_need(self, instance, push_now, params, stat):
if not push_now or stat not in ['created', 'updated']:
return
transaction.on_commit(lambda: self.start_push(instance, params))
@staticmethod
def start_push(instance, params):
push_accounts_to_assets_task.delay([str(instance.id)], params)
def get_validators(self):

View File

@@ -1,16 +1,24 @@
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from accounts.models import AccountTemplate, Account
from accounts.const import SecretStrategy, SecretType
from accounts.models import AccountTemplate
from accounts.utils import SecretGenerator
from common.serializers import SecretReadableMixin
from common.serializers.fields import ObjectRelatedField
from .base import BaseAccountSerializer
class AccountTemplateSerializer(BaseAccountSerializer):
is_sync_account = serializers.BooleanField(default=False, write_only=True)
_is_sync_account = False
class PasswordRulesSerializer(serializers.Serializer):
length = serializers.IntegerField(min_value=8, max_value=30, default=16, label=_('Password length'))
lowercase = serializers.BooleanField(default=True, label=_('Lowercase'))
uppercase = serializers.BooleanField(default=True, label=_('Uppercase'))
digit = serializers.BooleanField(default=True, label=_('Digit'))
symbol = serializers.BooleanField(default=True, label=_('Special symbol'))
class AccountTemplateSerializer(BaseAccountSerializer):
password_rules = PasswordRulesSerializer(required=False, label=_('Password rules'))
su_from = ObjectRelatedField(
required=False, queryset=AccountTemplate.objects, allow_null=True,
allow_empty=True, label=_('Su from'), attrs=('id', 'name', 'username')
@@ -18,36 +26,38 @@ class AccountTemplateSerializer(BaseAccountSerializer):
class Meta(BaseAccountSerializer.Meta):
model = AccountTemplate
fields = BaseAccountSerializer.Meta.fields + ['is_sync_account', 'su_from']
def sync_accounts_secret(self, instance, diff):
if not self._is_sync_account or 'secret' not in diff:
return
query_data = {
'source_id': instance.id,
'username': instance.username,
'secret_type': instance.secret_type
fields = BaseAccountSerializer.Meta.fields + [
'secret_strategy', 'password_rules',
'auto_push', 'push_params', 'platforms',
'su_from'
]
extra_kwargs = {
'secret_strategy': {'help_text': _('Secret generation strategy for account creation')},
'auto_push': {'help_text': _('Whether to automatically push the account to the asset')},
'platforms': {
'help_text': _(
'Associated platform, you can configure push parameters. '
'If not associated, default parameters will be used'
),
'required': False
},
}
accounts = Account.objects.filter(**query_data)
instance.bulk_sync_account_secret(accounts, self.context['request'].user.id)
@staticmethod
def generate_secret(attrs):
secret_type = attrs.get('secret_type', SecretType.PASSWORD)
secret_strategy = attrs.get('secret_strategy', SecretStrategy.custom)
password_rules = attrs.get('password_rules')
if secret_strategy != SecretStrategy.random:
return
generator = SecretGenerator(secret_strategy, secret_type, password_rules)
attrs['secret'] = generator.get_secret()
def validate(self, attrs):
self._is_sync_account = attrs.pop('is_sync_account', None)
attrs = super().validate(attrs)
self.generate_secret(attrs)
return attrs
def update(self, instance, validated_data):
diff = {
k: v for k, v in validated_data.items()
if getattr(instance, k, None) != v
}
instance = super().update(instance, validated_data)
if {'username', 'secret_type'} & set(diff.keys()):
Account.objects.filter(source_id=instance.id).update(source_id=None)
else:
self.sync_accounts_secret(instance, diff)
return instance
class AccountTemplateSecretSerializer(SecretReadableMixin, AccountTemplateSerializer):
class Meta(AccountTemplateSerializer.Meta):

View File

@@ -19,8 +19,12 @@ class VirtualAccountSerializer(serializers.ModelSerializer):
'comment': {'label': _('Comment')},
'name': {'label': _('Name')},
'username': {'label': _('Username')},
'secret_from_login': {'help_text': _('Current only support login from AD/LDAP. Secret priority: '
'Same account in asset secret > Login secret > Manual input')
},
'secret_from_login': {
'help_text': _(
'Current only support login from AD/LDAP. Secret priority: '
'Same account in asset secret > Login secret > Manual input. <br/ >'
'For security, please set config CACHE_LOGIN_PASSWORD_ENABLED to true'
)
},
'alias': {'required': False},
}

View File

@@ -4,14 +4,13 @@ from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from accounts.const import (
AutomationTypes, DEFAULT_PASSWORD_RULES,
SecretType, SecretStrategy, SSHKeyStrategy
AutomationTypes, SecretType, SecretStrategy, SSHKeyStrategy
)
from accounts.models import (
Account, ChangeSecretAutomation,
ChangeSecretRecord, AutomationExecution
)
from accounts.serializers import AuthValidateMixin
from accounts.serializers import AuthValidateMixin, PasswordRulesSerializer
from assets.models import Asset
from common.serializers.fields import LabeledChoiceField, ObjectRelatedField
from common.utils import get_logger
@@ -42,7 +41,7 @@ class ChangeSecretAutomationSerializer(AuthValidateMixin, BaseAutomationSerializ
ssh_key_change_strategy = LabeledChoiceField(
choices=SSHKeyStrategy.choices, required=False, label=_('SSH Key strategy')
)
password_rules = serializers.DictField(default=DEFAULT_PASSWORD_RULES)
password_rules = PasswordRulesSerializer(required=False, label=_('Password rules'))
secret_type = LabeledChoiceField(choices=get_secret_types(), required=True, label=_('Secret type'))
class Meta:
@@ -72,7 +71,6 @@ class ChangeSecretAutomationSerializer(AuthValidateMixin, BaseAutomationSerializ
return password_rules
length = password_rules.get('length')
symbol_set = password_rules.get('symbol_set', '')
try:
length = int(length)
@@ -85,10 +83,6 @@ class ChangeSecretAutomationSerializer(AuthValidateMixin, BaseAutomationSerializ
msg = _('* Password length range 6-30 bits')
raise serializers.ValidationError(msg)
if not isinstance(symbol_set, str):
symbol_set = str(symbol_set)
password_rules = {'length': length, 'symbol_set': ''.join(symbol_set)}
return password_rules
def validate(self, attrs):

View File

@@ -1,9 +1,17 @@
from django.db.models.signals import pre_save, post_save, post_delete
from collections import defaultdict
from django.db.models.signals import post_delete
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.utils.translation import gettext_noop
from accounts.backends import vault_client
from common.utils import get_logger
from audits.const import ActivityChoices
from audits.signal_handlers import create_activities
from common.decorators import merge_delay_run
from common.utils import get_logger, i18n_fmt
from .models import Account, AccountTemplate
from .tasks.push_account import push_accounts_to_assets_task
logger = get_logger(__name__)
@@ -16,6 +24,53 @@ def on_account_pre_save(sender, instance, **kwargs):
instance.version = instance.history.count()
@merge_delay_run(ttl=5)
def push_accounts_if_need(accounts=()):
from .models import AccountTemplate
template_accounts = defaultdict(list)
for ac in accounts:
# 再强调一次吧
if ac.source != 'template':
continue
template_accounts[ac.source_id].append(ac)
for source_id, accounts in template_accounts.items():
template = AccountTemplate.objects.filter(id=source_id).first()
if not template or not template.auto_push:
continue
logger.debug("Push accounts to source: %s", source_id)
account_ids = [str(ac.id) for ac in accounts]
task = push_accounts_to_assets_task.delay(account_ids, params=template.push_params)
detail = i18n_fmt(
gettext_noop('Push related accounts to assets: %s, by system'),
len(account_ids)
)
create_activities([str(template.id)], detail, task.id, ActivityChoices.task, template.org_id)
logger.debug("Push accounts to source: %s, task: %s", source_id, task)
def create_accounts_activities(account, action='create'):
if action == 'create':
detail = i18n_fmt(gettext_noop('Add account: %s'), str(account))
else:
detail = i18n_fmt(gettext_noop('Delete account: %s'), str(account))
create_activities([account.asset_id], detail, None, ActivityChoices.operate_log, account.org_id)
@receiver(post_save, sender=Account)
def on_account_create_by_template(sender, instance, created=False, **kwargs):
if not created or instance.source != 'template':
return
push_accounts_if_need(accounts=(instance,))
create_accounts_activities(instance, action='create')
@receiver(post_delete, sender=Account)
def on_account_delete(sender, instance, **kwargs):
create_accounts_activities(instance, action='delete')
class VaultSignalHandler(object):
""" 处理 Vault 相关的信号 """

View File

@@ -1,5 +1,6 @@
from .backup_account import *
from .automation import *
from .push_account import *
from .verify_account import *
from .backup_account import *
from .gather_accounts import *
from .push_account import *
from .template import *
from .verify_account import *

View File

@@ -0,0 +1,60 @@
from datetime import datetime
from celery import shared_task
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from orgs.utils import tmp_to_root_org, tmp_to_org
@shared_task(
verbose_name=_('Template sync info to related accounts'),
activity_callback=lambda self, template_id, *args, **kwargs: (template_id, None)
)
def template_sync_related_accounts(template_id, user_id=None):
from accounts.models import Account, AccountTemplate
with tmp_to_root_org():
template = get_object_or_404(AccountTemplate, id=template_id)
org_id = template.org_id
with tmp_to_org(org_id):
accounts = Account.objects.filter(source_id=template_id)
if not accounts:
print('\033[35m>>> 没有需要同步的账号, 结束任务')
print('\033[0m')
return
failed, succeeded = 0, 0
succeeded_account_ids = []
name = template.name
username = template.username
secret_type = template.secret_type
print(f'\033[32m>>> 开始同步模版名称、用户名、密钥类型到相关联的账号 ({datetime.now().strftime("%Y-%m-%d %H:%M:%S")})')
with tmp_to_org(org_id):
for account in accounts:
account.name = name
account.username = username
account.secret_type = secret_type
try:
account.save(update_fields=['name', 'username', 'secret_type'])
succeeded += 1
succeeded_account_ids.append(account.id)
except Exception as e:
account.source_id = None
account.save(update_fields=['source_id'])
print(f'\033[31m- 同步失败: [{account}] 原因: [{e}]')
failed += 1
accounts = Account.objects.filter(id__in=succeeded_account_ids)
if accounts:
print(f'\033[33m>>> 批量更新账号密文 ({datetime.now().strftime("%Y-%m-%d %H:%M:%S")})')
template.bulk_sync_account_secret(accounts, user_id)
total = succeeded + failed
print(
f'\033[33m>>> 同步完成:, '
f'共计: {total}, '
f'成功: {succeeded}, '
f'失败: {failed}, '
f'({datetime.now().strftime("%Y-%m-%d %H:%M:%S")}) '
)
print('\033[0m')

View File

@@ -1,3 +1,5 @@
import copy
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
@@ -14,13 +16,23 @@ class SecretGenerator:
@staticmethod
def generate_ssh_key():
private_key, public_key = ssh_key_gen()
private_key, __ = ssh_key_gen()
return private_key
def generate_password(self):
length = int(self.password_rules.get('length', 0))
length = length if length else DEFAULT_PASSWORD_RULES['length']
return random_string(length, special_char=True)
password_rules = self.password_rules
if not password_rules or not isinstance(password_rules, dict):
password_rules = {}
rules = copy.deepcopy(DEFAULT_PASSWORD_RULES)
rules.update(password_rules)
rules = {
'length': rules['length'],
'lower': rules['lowercase'],
'upper': rules['uppercase'],
'digit': rules['digit'],
'special_char': rules['symbol']
}
return random_string(**rules)
def get_secret(self):
if self.secret_type == SecretType.SSH_KEY:
@@ -39,6 +51,8 @@ def validate_password_for_ansible(password):
# Ansible 推送的时候不支持
if '{{' in password:
raise serializers.ValidationError(_('Password can not contains `{{` '))
if '{%' in password:
raise serializers.ValidationError(_('Password can not contains `{%` '))
# Ansible Windows 推送的时候不支持
if "'" in password:
raise serializers.ValidationError(_("Password can not contains `'` "))

View File

@@ -10,7 +10,7 @@ __all__ = ['CommandFilterACLViewSet', 'CommandGroupViewSet']
class CommandGroupViewSet(OrgBulkModelViewSet):
model = models.CommandGroup
filterset_fields = ('name',)
filterset_fields = ('name', 'command_filters')
search_fields = filterset_fields
serializer_class = serializers.CommandGroupSerializer

View File

@@ -7,3 +7,4 @@ class ActionChoices(models.TextChoices):
accept = 'accept', _('Accept')
review = 'review', _('Review')
warning = 'warning', _('Warning')
notice = 'notice', _('Notifications')

View File

@@ -0,0 +1,18 @@
# Generated by Django 4.1.10 on 2023-10-18 10:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('acls', '0017_alter_connectmethodacl_options'),
]
operations = [
migrations.AlterField(
model_name='commandfilteracl',
name='command_groups',
field=models.ManyToManyField(related_name='command_filters', to='acls.commandgroup', verbose_name='Command group'),
),
]

View File

@@ -103,25 +103,27 @@ class UserAssetAccountBaseACL(OrgModelMixin, UserBaseACL):
abstract = True
@classmethod
def filter_queryset(cls, user=None, asset=None, account=None, account_username=None, **kwargs):
def _get_filter_queryset(cls, user=None, asset=None, account=None, account_username=None, **kwargs):
queryset = cls.objects.all()
if user:
q = cls.users.get_filter_q(user)
queryset = queryset.filter(q)
q = models.Q()
if asset:
org_id = asset.org_id
with tmp_to_org(org_id):
q = cls.assets.get_filter_q(asset)
queryset = queryset.filter(q)
q &= cls.assets.get_filter_q(asset)
if user:
q &= cls.users.get_filter_q(user)
if account and not account_username:
account_username = account.username
if account_username:
q = models.Q(accounts__contains=account_username) | \
models.Q(accounts__contains='*') | \
models.Q(accounts__contains='@ALL')
queryset = queryset.filter(q)
q &= models.Q(accounts__contains=account_username) | \
models.Q(accounts__contains='*') | \
models.Q(accounts__contains='@ALL')
if kwargs:
queryset = queryset.filter(**kwargs)
q &= models.Q(**kwargs)
queryset = queryset.filter(q)
return queryset.valid().distinct()
@classmethod
def filter_queryset(cls, asset=None, **kwargs):
org_id = asset.org_id if asset else ''
with tmp_to_org(org_id):
return cls._get_filter_queryset(asset=asset, **kwargs)

View File

@@ -93,7 +93,10 @@ class CommandGroup(JMSOrgBaseModel):
class CommandFilterACL(UserAssetAccountBaseACL):
command_groups = models.ManyToManyField(CommandGroup, verbose_name=_('Command group'))
command_groups = models.ManyToManyField(
CommandGroup, verbose_name=_('Command group'),
related_name='command_filters'
)
class Meta(UserAssetAccountBaseACL.Meta):
abstract = False

View File

@@ -0,0 +1,68 @@
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
from assets.models import Asset
from audits.models import UserLoginLog
from notifications.notifications import UserMessage
from users.models import User
class UserLoginReminderMsg(UserMessage):
subject = _('User login reminder')
def __init__(self, user, user_log: UserLoginLog):
self.user_log = user_log
super().__init__(user)
def get_html_msg(self) -> dict:
user_log = self.user_log
context = {
'ip': user_log.ip,
'city': user_log.city,
'username': user_log.username,
'recipient': self.user.username,
'user_agent': user_log.user_agent,
}
message = render_to_string('acls/user_login_reminder.html', context)
return {
'subject': str(self.subject),
'message': message
}
@classmethod
def gen_test_msg(cls):
user = User.objects.first()
user_log = UserLoginLog.objects.first()
return cls(user, user_log)
class AssetLoginReminderMsg(UserMessage):
subject = _('Asset login reminder')
def __init__(self, user, asset: Asset, login_user: User, account_username):
self.asset = asset
self.login_user = login_user
self.account_username = account_username
super().__init__(user)
def get_html_msg(self) -> dict:
context = {
'recipient': self.user.username,
'username': self.login_user.username,
'asset': str(self.asset),
'account': self.account_username,
}
message = render_to_string('acls/asset_login_reminder.html', context)
return {
'subject': str(self.subject),
'message': message
}
@classmethod
def gen_test_msg(cls):
user = User.objects.first()
asset = Asset.objects.first()
return cls(user, asset, user)

View File

@@ -1,9 +1,9 @@
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from acls.models.base import BaseACL
from common.serializers.fields import JSONManyToManyField, LabeledChoiceField
from jumpserver.utils import has_valid_xpack_license
from orgs.models import Organization
from ..const import ActionChoices
@@ -68,7 +68,7 @@ class ActionAclSerializer(serializers.Serializer):
field_action = self.fields.get("action")
if not field_action:
return
if not has_valid_xpack_license():
if not settings.XPACK_LICENSE_IS_VALID:
field_action._choices.pop(ActionChoices.review, None)
for choice in self.Meta.action_choices_exclude:
field_action._choices.pop(choice, None)

View File

@@ -8,6 +8,7 @@ from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from orgs.utils import tmp_to_root_org
from terminal.models import Session
from .base import BaseUserAssetAccountACLSerializer as BaseSerializer
from ..const import ActionChoices
__all__ = ["CommandFilterACLSerializer", "CommandGroupSerializer", "CommandReviewSerializer"]
@@ -31,8 +32,7 @@ class CommandFilterACLSerializer(BaseSerializer, BulkOrgResourceModelSerializer)
class Meta(BaseSerializer.Meta):
model = CommandFilterACL
fields = BaseSerializer.Meta.fields + ['command_groups']
# 默认都支持所有的 actions
action_choices_exclude = []
action_choices_exclude = [ActionChoices.notice]
class CommandReviewSerializer(serializers.Serializer):

View File

@@ -1,7 +1,7 @@
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
from .base import BaseUserAssetAccountACLSerializer as BaseSerializer
from ..models import ConnectMethodACL
from ..const import ActionChoices
from ..models import ConnectMethodACL
__all__ = ["ConnectMethodACLSerializer"]
@@ -14,5 +14,5 @@ class ConnectMethodACLSerializer(BaseSerializer, BulkOrgResourceModelSerializer)
if i not in ['assets', 'accounts']
]
action_choices_exclude = BaseSerializer.Meta.action_choices_exclude + [
ActionChoices.review, ActionChoices.accept
ActionChoices.review, ActionChoices.accept, ActionChoices.notice
]

View File

@@ -0,0 +1,13 @@
{% load i18n %}
<h3>{% trans 'Respectful' %}{{ recipient }}</h3>
<hr>
<p><strong>{% trans 'Username' %}:</strong> [{{ username }}]</p>
<p><strong>{% trans 'Assets' %}:</strong> [{{ asset }}]</p>
<p><strong>{% trans 'Account' %}:</strong> [{{ account }}]</p>
<hr>
<p>{% trans 'The user has just logged in to the asset. Please ensure that this is an authorized operation. If you suspect that this is an unauthorized access, please take appropriate measures immediately.' %}</p>
<p>{% trans 'Thank you' %}</p>

View File

@@ -0,0 +1,14 @@
{% load i18n %}
<h3>{% trans 'Respectful' %}{{ recipient }}</h3>
<hr>
<p><strong>{% trans 'Username' %}:</strong> [{{ username }}]</p>
<p><strong>IP:</strong> [{{ ip }}]</p>
<p><strong>{% trans 'Login city' %}:</strong> [{{ city }}]</p>
<p><strong>{% trans 'User agent' %}:</strong> [{{ user_agent }}]</p>
<hr>
<p>{% trans 'The user has just successfully logged into the system. Please ensure that this is an authorized operation. If you suspect that this is an unauthorized access, please take appropriate measures immediately.' %}</p>
<p>{% trans 'Thank you' %}</p>

View File

@@ -1,9 +1,12 @@
# -*- coding: utf-8 -*-
#
from collections import defaultdict
import django_filters
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
@@ -12,7 +15,7 @@ from accounts.tasks import push_accounts_to_assets_task, verify_accounts_connect
from assets import serializers
from assets.exceptions import NotSupportedTemporarilyError
from assets.filters import IpInFilterBackend, LabelFilterBackend, NodeFilterBackend
from assets.models import Asset, Gateway, Platform
from assets.models import Asset, Gateway, Platform, Protocol
from assets.tasks import test_assets_connectivity_manual, update_assets_hardware_info_manual
from common.api import SuggestionMixin
from common.drf.filters import BaseFilterSet, AttrRulesFilterBackend
@@ -115,6 +118,7 @@ class AssetViewSet(SuggestionMixin, NodeFilterMixin, OrgBulkModelViewSet):
("gateways", "assets.view_gateway"),
("spec_info", "assets.view_asset"),
("gathered_info", "assets.view_asset"),
("sync_platform_protocols", "assets.change_asset"),
)
extra_filter_backends = [
LabelFilterBackend, IpInFilterBackend,
@@ -152,6 +156,39 @@ class AssetViewSet(SuggestionMixin, NodeFilterMixin, OrgBulkModelViewSet):
gateways = asset.domain.gateways
return self.get_paginated_response_from_queryset(gateways)
@action(methods=['post'], detail=False, url_path='sync-platform-protocols')
def sync_platform_protocols(self, request, *args, **kwargs):
platform_id = request.data.get('platform_id')
platform = get_object_or_404(Platform, pk=platform_id)
assets = platform.assets.all()
platform_protocols = {
p['name']: p['port']
for p in platform.protocols.values('name', 'port')
}
asset_protocols_map = defaultdict(set)
protocols = assets.prefetch_related('protocols').values_list(
'id', 'protocols__name'
)
for asset_id, protocol in protocols:
asset_id = str(asset_id)
asset_protocols_map[asset_id].add(protocol)
objs = []
for asset_id, protocols in asset_protocols_map.items():
protocol_names = set(platform_protocols) - protocols
if not protocol_names:
continue
for name in protocol_names:
objs.append(
Protocol(
name=name,
port=platform_protocols[name],
asset_id=asset_id,
)
)
Protocol.objects.bulk_create(objs)
return Response(status=status.HTTP_200_OK)
def create(self, request, *args, **kwargs):
if request.path.find('/api/v1/assets/assets/') > -1:
error = _('Cannot create asset directly, you should create a host or other')

View File

@@ -42,7 +42,7 @@ class SerializeToTreeNodeMixin:
'name': _name(node),
'title': _name(node),
'pId': node.parent_key,
'isParent': node.assets_amount > 0,
'isParent': True,
'open': _open(node),
'meta': {
'data': {

View File

@@ -49,13 +49,19 @@ class AssetPlatformViewSet(JMSModelViewSet):
@action(methods=['post'], detail=False, url_path='filter-nodes-assets')
def filter_nodes_assets(self, request, *args, **kwargs):
node_ids = request.data.get('node_ids', [])
asset_ids = request.data.get('asset_ids', [])
nodes = Node.objects.filter(id__in=node_ids)
node_asset_ids = Node.get_nodes_all_assets(*nodes).values_list('id', flat=True)
direct_asset_ids = Asset.objects.filter(id__in=asset_ids).values_list('id', flat=True)
platform_ids = Asset.objects.filter(
id__in=set(list(direct_asset_ids) + list(node_asset_ids))
).values_list('platform_id', flat=True)
asset_ids = set(request.data.get('asset_ids', []))
platform_ids = set(request.data.get('platform_ids', []))
if node_ids:
nodes = Node.objects.filter(id__in=node_ids)
node_asset_ids = Node.get_nodes_all_assets(*nodes).values_list('id', flat=True)
asset_ids |= set(node_asset_ids)
if asset_ids:
_platform_ids = Asset.objects \
.filter(id__in=set(asset_ids)) \
.values_list('platform_id', flat=True)
platform_ids |= set(_platform_ids)
platforms = Platform.objects.filter(id__in=platform_ids)
serializer = self.get_serializer(platforms, many=True)
return Response(serializer.data)

View File

@@ -1,14 +1,14 @@
# ~*~ coding: utf-8 ~*~
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from django.utils.translation import gettext_lazy as _
from assets.locks import NodeAddChildrenLock
from common.exceptions import JMSException
from common.tree import TreeNodeSerializer
from common.utils import get_logger
from common.exceptions import JMSException
from orgs.mixins import generics
from orgs.utils import current_org
from .mixin import SerializeToTreeNodeMixin
@@ -35,8 +35,8 @@ class NodeChildrenApi(generics.ListCreateAPIView):
is_initial = False
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
self.instance = self.get_object()
return super().initial(request, *args, **kwargs)
def perform_create(self, serializer):
with NodeAddChildrenLock(self.instance):

View File

@@ -175,7 +175,7 @@ class BasePlaybookManager:
method = self.method_id_meta_mapper.get(method_id)
if not method:
logger.error("Method not found: {}".format(method_id))
return method
return
method_playbook_dir_path = method['dir']
sub_playbook_path = os.path.join(sub_playbook_dir, 'project', 'main.yml')
shutil.copytree(method_playbook_dir_path, os.path.dirname(sub_playbook_path))
@@ -196,6 +196,11 @@ class BasePlaybookManager:
print(msg)
runners = []
for platform, assets in assets_group_by_platform.items():
if not assets:
continue
if not platform.automation or not platform.automation.ansible_enabled:
print(_(" - Platform {} ansible disabled").format(platform.name))
continue
assets_bulked = [assets[i:i + self.bulk_size] for i in range(0, len(assets), self.bulk_size)]
for i, _assets in enumerate(assets_bulked, start=1):
@@ -204,6 +209,8 @@ class BasePlaybookManager:
inventory_path = os.path.join(self.runtime_dir, sub_dir, 'hosts.json')
self.generate_inventory(_assets, inventory_path)
playbook_path = self.generate_playbook(_assets, platform, playbook_dir)
if not playbook_path:
continue
runer = PlaybookRunner(
inventory_path,
@@ -309,6 +316,7 @@ class BasePlaybookManager:
shutil.rmtree(self.runtime_dir)
def run(self, *args, **kwargs):
print(">>> 任务准备阶段\n")
runners = self.get_runners()
if len(runners) > 1:
print("### 分次执行任务, 总共 {}\n".format(len(runners)))

View File

@@ -12,8 +12,8 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"
register: db_info

View File

@@ -10,6 +10,10 @@
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
filter: version
register: db_info

View File

@@ -10,6 +10,6 @@
login_user: "{{ jms_account.username }}"
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
login_port: "{{ jms_asset.protocols | selectattr('name', 'equalto', 'rdp') | map(attribute='port') | first }}"
login_secret_type: "{{ jms_account.secret_type }}"
login_private_key_path: "{{ jms_account.private_key_path }}"

View File

@@ -12,7 +12,7 @@
login_port: "{{ jms_asset.port }}"
login_database: "{{ jms_asset.spec_info.db_name }}"
ssl: "{{ jms_asset.spec_info.use_ssl }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key }}"
ssl_ca_certs: "{{ jms_asset.secret_info.ca_cert | default('') }}"
ssl_certfile: "{{ jms_asset.secret_info.client_key | default('') }}"
connection_options:
- tlsAllowInvalidHostnames: "{{ jms_asset.spec_info.allow_invalid_cert}}"

View File

@@ -10,4 +10,8 @@
login_password: "{{ jms_account.secret }}"
login_host: "{{ jms_asset.address }}"
login_port: "{{ jms_asset.port }}"
check_hostname: "{{ jms_asset.spec_info.use_ssl and not jms_asset.spec_info.allow_invalid_cert }}"
ca_cert: "{{ jms_asset.secret_info.ca_cert | default(omit) }}"
client_cert: "{{ jms_asset.secret_info.client_cert | default(omit) }}"
client_key: "{{ jms_asset.secret_info.client_key | default(omit) }}"
filter: version

View File

@@ -1,9 +1,8 @@
from django.conf import settings
from django.db import models
from django.db.models import TextChoices
from django.utils.translation import gettext_lazy as _
from jumpserver.utils import has_valid_xpack_license
class Type:
def __init__(self, label, value):
@@ -65,14 +64,14 @@ class BaseType(TextChoices):
@classmethod
def _parse_protocols(cls, protocol, tp):
from .protocol import Protocol
settings = Protocol.settings()
_settings = Protocol.settings()
choices = protocol.get('choices', [])
if choices == '__self__':
choices = [tp]
protocols = []
for name in choices:
protocol = {'name': name, **settings.get(name, {})}
protocol = {'name': name, **_settings.get(name, {})}
setting = protocol.pop('setting', {})
setting_values = {k: v.get('default', None) for k, v in setting.items()}
protocol['setting'] = setting_values
@@ -113,7 +112,7 @@ class BaseType(TextChoices):
@classmethod
def get_choices(cls):
if not has_valid_xpack_license():
if not settings.XPACK_ENABLED:
return [
(tp.value, tp.label)
for tp in cls.get_community_types()

View File

@@ -7,6 +7,7 @@ class DatabaseTypes(BaseType):
POSTGRESQL = 'postgresql', 'PostgreSQL'
ORACLE = 'oracle', 'Oracle'
SQLSERVER = 'sqlserver', 'SQLServer'
DB2 = 'db2', 'DB2'
CLICKHOUSE = 'clickhouse', 'ClickHouse'
MONGODB = 'mongodb', 'MongoDB'
REDIS = 'redis', 'Redis'
@@ -45,6 +46,15 @@ class DatabaseTypes(BaseType):
'change_secret_enabled': False,
'push_account_enabled': False,
},
cls.DB2: {
'ansible_enabled': False,
'ping_enabled': False,
'gather_facts_enabled': False,
'gather_accounts_enabled': False,
'verify_account_enabled': False,
'change_secret_enabled': False,
'push_account_enabled': False,
},
cls.CLICKHOUSE: {
'ansible_enabled': False,
'ping_enabled': False,
@@ -73,6 +83,7 @@ class DatabaseTypes(BaseType):
cls.POSTGRESQL: [{'name': 'PostgreSQL'}],
cls.ORACLE: [{'name': 'Oracle'}],
cls.SQLSERVER: [{'name': 'SQLServer'}],
cls.DB2: [{'name': 'DB2'}],
cls.CLICKHOUSE: [{'name': 'ClickHouse'}],
cls.MONGODB: [{'name': 'MongoDB'}],
cls.REDIS: [

View File

@@ -24,7 +24,7 @@ class DeviceTypes(BaseType):
def _get_protocol_constrains(cls) -> dict:
return {
'*': {
'choices': ['ssh', 'telnet']
'choices': ['ssh', 'telnet', 'sftp']
}
}

View File

@@ -22,6 +22,7 @@ class Protocol(ChoicesMixin, models.TextChoices):
oracle = 'oracle', 'Oracle'
postgresql = 'postgresql', 'PostgreSQL'
sqlserver = 'sqlserver', 'SQLServer'
db2 = 'db2', 'DB2'
clickhouse = 'clickhouse', 'ClickHouse'
redis = 'redis', 'Redis'
mongodb = 'mongodb', 'MongoDB'
@@ -45,7 +46,13 @@ class Protocol(ChoicesMixin, models.TextChoices):
'sftp_home': {
'type': 'str',
'default': '/tmp',
'label': _('SFTP home')
'label': _('SFTP root'),
'help_text': _(
'SFTP root directory, Support variable: <br>'
'- ${ACCOUNT} The connected account username <br>'
'- ${HOME} The home directory of the connected account <br>'
'- ${USER} The username of the user'
)
}
}
},
@@ -154,6 +161,21 @@ class Protocol(ChoicesMixin, models.TextChoices):
'required': True,
'secret_types': ['password'],
'xpack': True,
'setting': {
'version': {
'type': 'choice',
'choices': [('>=2014', '>= 2014'), ('<2014', '< 2014')],
'default': '>=2014',
'label': _('Version'),
'help_text': _('SQL Server version, Different versions have different connection drivers')
}
}
},
cls.db2: {
'port': 5000,
'required': True,
'secret_types': ['password'],
'xpack': True,
},
cls.clickhouse: {
'port': 9000,
@@ -254,7 +276,7 @@ class Protocol(ChoicesMixin, models.TextChoices):
}
}
}
if settings.XPACK_ENABLED:
if settings.XPACK_LICENSE_IS_VALID:
choices = protocols[cls.chatgpt]['setting']['api_mode']['choices']
choices.extend([
('gpt-4', 'GPT-4'),

View File

@@ -107,8 +107,9 @@ def create_app_nodes(apps, org_id):
'key': next_key, 'value': name, 'parent_key': parent_key,
'full_value': full_value, 'org_id': org_id
}
node, created = node_model.objects.get_or_create(
node, __ = node_model.objects.get_or_create(
defaults=defaults, value=name, org_id=org_id,
parent_key=parent_key
)
node.parent = parent
return node

View File

@@ -25,7 +25,7 @@ def migrate_asset_accounts(apps, schema_editor):
count += len(auth_books)
# auth book 和 account 相同的属性
same_attrs = [
'id', 'username', 'comment', 'date_created', 'date_updated',
'username', 'comment', 'date_created', 'date_updated',
'created_by', 'asset_id', 'org_id',
]
# 认证的属性,可能是 auth_book 的,可能是 system_user 的

View File

@@ -49,11 +49,11 @@ def migrate_assets_sftp_protocol(apps, schema_editor):
count = 0
print("\nAsset add sftp protocol: ")
asset_ids = asset_cls.objects\
asset_ids = list(asset_cls.objects\
.filter(platform__in=sftp_platforms)\
.exclude(protocols__name='sftp')\
.distinct()\
.values_list('id', flat=True)
.values_list('id', flat=True))
while True:
_asset_ids = asset_ids[count:count + 1000]
if not _asset_ids:

View File

@@ -0,0 +1,20 @@
# Generated by Django 4.1.10 on 2023-09-13 10:59
from django.db import migrations
def migrate_device_automation_ansible_enabled(apps, *args):
platform_model = apps.get_model('assets', 'Platform')
automation_model = apps.get_model('assets', 'PlatformAutomation')
ids = platform_model.objects.filter(category='device').values_list('id', flat=True)
automation_model.objects.filter(platform_id__in=ids).update(ansible_enabled=True)
class Migration(migrations.Migration):
dependencies = [
('assets', '0122_auto_20230803_1553'),
]
operations = [
migrations.RunPython(migrate_device_automation_ansible_enabled)
]

View File

@@ -0,0 +1,31 @@
# Generated by Django 4.1.10 on 2023-10-07 06:37
from django.db import migrations
def add_db2_platform(apps, schema_editor):
platform_cls = apps.get_model('assets', 'Platform')
automation_cls = apps.get_model('assets', 'PlatformAutomation')
platform, _ = platform_cls.objects.update_or_create(
name='DB2', defaults={
'name': 'DB2', 'category': 'database',
'internal': True, 'type': 'db2',
'domain_enabled': True, 'su_enabled': False,
'su_method': None, 'comment': 'DB2', 'created_by': 'System',
'updated_by': 'System', 'custom_fields': []
}
)
platform.protocols.update_or_create(name='db2', defaults={
'name': 'db2', 'port': 50000, 'primary': True, 'setting': {}
})
automation_cls.objects.update_or_create(platform=platform, defaults={'ansible_enabled': False})
class Migration(migrations.Migration):
dependencies = [
('assets', '0123_device_automation_ansible_enabled'),
]
operations = [
migrations.RunPython(add_db2_platform)
]

View File

@@ -0,0 +1,21 @@
# Generated by Django 4.1.10 on 2023-10-11 02:53
from django.db import migrations
def change_windows_ping_method(apps, schema_editor):
platform_automation_cls = apps.get_model('assets', 'PlatformAutomation')
automations = platform_automation_cls.objects.filter(platform__name__in=['Windows', 'Windows2016'])
automations.update(ping_method='ping_by_rdp')
automations.update(verify_account_method='verify_account_by_rdp')
class Migration(migrations.Migration):
dependencies = [
('assets', '0124_auto_20231007_1437'),
]
operations = [
migrations.RunPython(change_windows_ping_method)
]

View File

@@ -402,12 +402,7 @@ class NodeAssetsMixin(NodeAllAssetsMappingMixin):
return Asset.objects.filter(q).distinct()
def get_assets_amount(self):
q = Q(node__key__startswith=f'{self.key}:') | Q(node__key=self.key)
return self.assets.through.objects.filter(q).count()
def get_assets_account_by_children(self):
children = self.get_all_children().values_list()
return self.assets.through.objects.filter(node_id__in=children).count()
return self.get_all_assets().count()
@classmethod
def get_node_all_assets_by_key_v2(cls, key):

View File

@@ -175,6 +175,8 @@ class AssetSerializer(BulkOrgResourceModelSerializer, WritableNestedModelSeriali
protocols = self.initial_data.get('protocols')
if protocols is not None:
return
if getattr(self, 'instance', None):
return
protocols_required, protocols_default = self._get_protocols_required_default()
protocol_map = {str(protocol.id): protocol for protocol in protocols_required + protocols_default}
@@ -281,14 +283,52 @@ class AssetSerializer(BulkOrgResourceModelSerializer, WritableNestedModelSeriali
return protocols_data_map.values()
@staticmethod
def accounts_create(accounts_data, asset):
def update_account_su_from(accounts, include_su_from_accounts):
if not include_su_from_accounts:
return
name_map = {account.name: account for account in accounts}
username_secret_type_map = {
(account.username, account.secret_type): account for account in accounts
}
for name, username_secret_type in include_su_from_accounts.items():
account = name_map.get(name)
if not account:
continue
su_from_account = username_secret_type_map.get(username_secret_type)
if su_from_account:
account.su_from = su_from_account
account.save()
def accounts_create(self, accounts_data, asset):
from accounts.models import AccountTemplate
if not accounts_data:
return
if not isinstance(accounts_data[0], dict):
raise serializers.ValidationError({'accounts': _("Invalid data")})
su_from_name_username_secret_type_map = {}
for data in accounts_data:
data['asset'] = asset.id
name = data.get('name')
su_from = data.pop('su_from', None)
template_id = data.get('template', None)
if template_id:
template = AccountTemplate.objects.get(id=template_id)
if template and template.su_from:
su_from_name_username_secret_type_map[template.name] = (
template.su_from.username, template.su_from.secret_type
)
elif isinstance(su_from, dict):
su_from = Account.objects.get(id=su_from.get('id'))
su_from_name_username_secret_type_map[name] = (
su_from.username, su_from.secret_type
)
s = AssetAccountSerializer(data=accounts_data, many=True)
s.is_valid(raise_exception=True)
s.save()
accounts = s.save()
self.update_account_su_from(accounts, su_from_name_username_secret_type_map)
@atomic
def create(self, validated_data):
@@ -298,10 +338,37 @@ class AssetSerializer(BulkOrgResourceModelSerializer, WritableNestedModelSeriali
self.perform_nodes_display_create(instance, nodes_display)
return instance
@staticmethod
def sync_platform_protocols(instance, old_platform):
platform = instance.platform
if str(old_platform.id) == str(instance.platform_id):
return
platform_protocols = {
p['name']: p['port']
for p in platform.protocols.values('name', 'port')
}
protocols = set(instance.protocols.values_list('name', flat=True))
protocol_names = set(platform_protocols) - protocols
objs = []
for name in protocol_names:
objs.append(
Protocol(
name=name,
port=platform_protocols[name],
asset_id=instance.id,
)
)
Protocol.objects.bulk_create(objs)
@atomic
def update(self, instance, validated_data):
old_platform = instance.platform
nodes_display = validated_data.pop('nodes_display', '')
instance = super().update(instance, validated_data)
self.sync_platform_protocols(instance, old_platform)
self.perform_nodes_display_create(instance, nodes_display)
return instance

View File

@@ -1,8 +1,8 @@
from django.db.models import QuerySet
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.serializers import ValidationError
from assets.models import Database
from assets.models import Database, Platform
from assets.serializers.gateway import GatewayWithAccountSecretSerializer
from .common import AssetSerializer
@@ -20,13 +20,44 @@ class DatabaseSerializer(AssetSerializer):
]
fields = AssetSerializer.Meta.fields + extra_fields
def validate(self, attrs):
platform = attrs.get('platform')
db_type_required = ('mongodb', 'postgresql')
if platform and getattr(platform, 'type') in db_type_required \
and not attrs.get('db_name'):
raise ValidationError({'db_name': _('This field is required.')})
return attrs
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_db_name_required()
def get_platform(self):
platform = None
platform_id = None
if getattr(self, 'initial_data', None):
platform_id = self.initial_data.get('platform')
if isinstance(platform_id, dict):
platform_id = platform_id.get('id') or platform_id.get('pk')
if not platform_id and self.instance:
platform = self.instance.platform
elif getattr(self, 'instance', None):
if isinstance(self.instance, (list, QuerySet)):
return
platform = self.instance.platform
elif self.context.get('request'):
platform_id = self.context['request'].query_params.get('platform')
if not platform and platform_id:
platform = Platform.objects.filter(id=platform_id).first()
return platform
def set_db_name_required(self):
db_field = self.fields.get('db_name')
if not db_field:
return
platform = self.get_platform()
if not platform:
return
if platform.type in ['mysql', 'mariadb']:
db_field.required = False
db_field.allow_blank = True
db_field.allow_null = True
class DatabaseWithGatewaySerializer(DatabaseSerializer):

View File

@@ -30,8 +30,9 @@ class NodeSerializer(BulkOrgResourceModelSerializer):
if '/' in data:
error = _("Can't contains: " + "/")
raise serializers.ValidationError(error)
if self.instance:
instance = self.instance
view = self.context['view']
instance = self.instance or getattr(view, 'instance', None)
if instance:
siblings = instance.get_siblings()
else:
instance = Node.org_root()

View File

@@ -1,6 +1,7 @@
from django.db.models import QuerySet
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from common.serializers import (
WritableNestedModelSerializer, type_field_map, MethodSerializer,
@@ -123,6 +124,10 @@ class PlatformSerializer(WritableNestedModelSerializer):
("super", "super 15"),
("super_level", "super level 15")
]
id = serializers.IntegerField(
label='ID', required=False,
validators=[UniqueValidator(queryset=Platform.objects.all())]
)
charset = LabeledChoiceField(choices=Platform.CharsetChoices.choices, label=_("Charset"), default='utf-8')
type = LabeledChoiceField(choices=AllTypes.choices(), label=_("Type"))
category = LabeledChoiceField(choices=Category.choices, label=_("Category"))
@@ -213,7 +218,7 @@ class PlatformSerializer(WritableNestedModelSerializer):
def validate_automation(self, automation):
automation = automation or {}
ansible_enabled = automation.get('ansible_enabled', False) \
and self.constraints['automation'].get('ansible_enabled', False)
and self.constraints['automation'].get('ansible_enabled', False)
automation['ansible_enable'] = ansible_enabled
return automation

View File

@@ -66,7 +66,7 @@ class KubernetesClient:
remote_bind_address = (
urlparse(asset.address).hostname,
urlparse(asset.address).port
urlparse(asset.address).port or 443
)
server = SSHTunnelForwarder(
(gateway.address, gateway.port),

View File

@@ -1,50 +1,51 @@
# -*- coding: utf-8 -*-
#
import os
from importlib import import_module
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.db.models import F, Value, CharField, Q
from django.http import HttpResponse, FileResponse
from django.utils.encoding import escape_uri_path
from rest_framework import generics
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import action
from common.api import AsyncApiMixin
from common.drf.filters import DatetimeRangeFilter
from common.api import CommonApiMixin
from common.const.http import GET, POST
from common.drf.filters import DatetimeRangeFilterBackend
from common.permissions import IsServiceAccount
from common.plugins.es import QuerySet as ESQuerySet
from common.utils import is_uuid, get_logger, lazyproperty
from common.const.http import GET, POST
from common.storage.ftp_file import FTPFileStorageHandler
from common.utils import is_uuid, get_logger, lazyproperty
from orgs.mixins.api import OrgReadonlyModelViewSet, OrgModelViewSet
from orgs.utils import current_org, tmp_to_root_org
from orgs.models import Organization
from orgs.utils import current_org, tmp_to_root_org
from rbac.permissions import RBACPermission
from terminal.models import default_storage
from users.models import User
from .backends import TYPE_ENGINE_MAPPING
from .const import ActivityChoices
from .models import FTPLog, UserLoginLog, OperateLog, PasswordChangeLog, ActivityLog, JobLog
from .models import (
FTPLog, UserLoginLog, OperateLog, PasswordChangeLog,
ActivityLog, JobLog, UserSession
)
from .serializers import (
FTPLogSerializer, UserLoginLogSerializer, JobLogSerializer,
OperateLogSerializer, OperateLogActionDetailSerializer,
PasswordChangeLogSerializer, ActivityUnionLogSerializer,
FileSerializer
FileSerializer, UserSessionSerializer
)
logger = get_logger(__name__)
class JobAuditViewSet(OrgReadonlyModelViewSet):
model = JobLog
extra_filter_backends = [DatetimeRangeFilter]
extra_filter_backends = [DatetimeRangeFilterBackend]
date_range_filter_fields = [
('date_start', ('date_from', 'date_to'))
]
@@ -57,7 +58,7 @@ class JobAuditViewSet(OrgReadonlyModelViewSet):
class FTPLogViewSet(OrgModelViewSet):
model = FTPLog
serializer_class = FTPLogSerializer
extra_filter_backends = [DatetimeRangeFilter]
extra_filter_backends = [DatetimeRangeFilterBackend]
date_range_filter_fields = [
('date_start', ('date_from', 'date_to'))
]
@@ -113,7 +114,7 @@ class FTPLogViewSet(OrgModelViewSet):
class UserLoginCommonMixin:
model = UserLoginLog
serializer_class = UserLoginLogSerializer
extra_filter_backends = [DatetimeRangeFilter]
extra_filter_backends = [DatetimeRangeFilterBackend]
date_range_filter_fields = [
('datetime', ('date_from', 'date_to'))
]
@@ -183,6 +184,8 @@ class ResourceActivityAPIView(generics.ListAPIView):
'r_user', 'r_action', 'r_type'
)
org_q = Q(org_id=Organization.SYSTEM_ID) | Q(org_id=current_org.id)
if resource_id:
org_q |= Q(org_id='') | Q(org_id=Organization.ROOT_ID)
with tmp_to_root_org():
qs1 = self.get_operate_log_qs(fields, limit, org_q, resource_id=resource_id)
qs2 = self.get_activity_log_qs(fields, limit, org_q, resource_id=resource_id)
@@ -193,7 +196,7 @@ class ResourceActivityAPIView(generics.ListAPIView):
class OperateLogViewSet(OrgReadonlyModelViewSet):
model = OperateLog
serializer_class = OperateLogSerializer
extra_filter_backends = [DatetimeRangeFilter]
extra_filter_backends = [DatetimeRangeFilterBackend]
date_range_filter_fields = [
('datetime', ('date_from', 'date_to'))
]
@@ -214,11 +217,10 @@ class OperateLogViewSet(OrgReadonlyModelViewSet):
return super().get_serializer_class()
def get_queryset(self):
org_q = Q(org_id=current_org.id)
qs = OperateLog.objects.all()
if self.is_action_detail:
org_q |= Q(org_id=Organization.SYSTEM_ID)
with tmp_to_root_org():
qs = OperateLog.objects.filter(org_q)
with tmp_to_root_org():
qs |= OperateLog.objects.filter(org_id=Organization.SYSTEM_ID)
es_config = settings.OPERATE_LOG_ELASTICSEARCH_CONFIG
if es_config:
engine_mod = import_module(TYPE_ENGINE_MAPPING['es'])
@@ -232,7 +234,7 @@ class OperateLogViewSet(OrgReadonlyModelViewSet):
class PasswordChangeLogViewSet(OrgReadonlyModelViewSet):
model = PasswordChangeLog
serializer_class = PasswordChangeLogSerializer
extra_filter_backends = [DatetimeRangeFilter]
extra_filter_backends = [DatetimeRangeFilterBackend]
date_range_filter_fields = [
('datetime', ('date_from', 'date_to'))
]
@@ -248,3 +250,43 @@ class PasswordChangeLogViewSet(OrgReadonlyModelViewSet):
user__in=[str(user) for user in users]
)
return queryset
class UserSessionViewSet(CommonApiMixin, viewsets.ModelViewSet):
http_method_names = ('get', 'post', 'head', 'options', 'trace')
serializer_class = UserSessionSerializer
filterset_fields = ['id', 'ip', 'city', 'type']
search_fields = ['id', 'ip', 'city']
rbac_perms = {
'offline': ['audits.offline_usersession']
}
@property
def org_user_ids(self):
user_ids = current_org.get_members().values_list('id', flat=True)
return user_ids
def get_queryset(self):
keys = UserSession.get_keys()
queryset = UserSession.objects.filter(key__in=keys)
if current_org.is_root():
return queryset
user_ids = self.org_user_ids
queryset = queryset.filter(user_id__in=user_ids)
return queryset
@action(['POST'], detail=False, url_path='offline')
def offline(self, request, *args, **kwargs):
ids = request.data.get('ids', [])
queryset = self.get_queryset()
session_key = request.session.session_key
queryset = queryset.exclude(key=session_key).filter(id__in=ids)
if not queryset.exists():
return Response(status=status.HTTP_200_OK)
keys = queryset.values_list('key', flat=True)
session_store_cls = import_module(settings.SESSION_ENGINE).SessionStore
for key in keys:
session_store_cls(key).delete()
queryset.delete()
return Response(status=status.HTTP_200_OK)

View File

@@ -58,7 +58,7 @@ class OperateLogStore(object):
return diff_list
def save(self, **kwargs):
log_id = kwargs.get('id', '')
log_id = kwargs.pop('id', None)
before = kwargs.pop('before') or {}
after = kwargs.pop('after') or {}

View File

@@ -25,10 +25,18 @@ class ActionChoices(TextChoices):
delete = "delete", _("Delete")
create = "create", _("Create")
# Activities action
download = "download", _("Download")
connect = "connect", _("Connect")
login = "login", _("Login")
change_auth = "change_password", _("Change password")
accept = 'accept', _('Accept')
review = 'review', _('Review')
notice = 'notice', _('Notifications')
reject = 'reject', _('Reject')
approve = 'approve', _('Approve')
close = 'close', _('Close')
class LoginTypeChoices(TextChoices):
web = "W", _("Web")

View File

@@ -0,0 +1,29 @@
# Generated by Django 4.1.10 on 2023-09-06 05:31
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('audits', '0022_auto_20230605_1555'),
]
operations = [
migrations.AlterField(
model_name='ftplog',
name='date_start',
field=models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Date start'),
),
migrations.AlterField(
model_name='operatelog',
name='action',
field=models.CharField(choices=[('view', 'View'), ('update', 'Update'), ('delete', 'Delete'), ('create', 'Create'), ('download', 'Download'), ('connect', 'Connect'), ('login', 'Login'), ('change_password', 'Change password'), ('accept', 'Accept'), ('review', 'Review'), ('notice', 'Notifications'), ('reject', 'Reject'), ('approve', 'Approve'), ('close', 'Close')], max_length=16, verbose_name='Action'),
),
migrations.AlterField(
model_name='userloginlog',
name='datetime',
field=models.DateTimeField(db_index=True, default=django.utils.timezone.now, verbose_name='Date login'),
),
]

View File

@@ -0,0 +1,37 @@
# Generated by Django 4.1.10 on 2023-09-15 08:58
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('audits', '0023_auto_20230906_1322'),
]
operations = [
migrations.CreateModel(
name='UserSession',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('ip', models.GenericIPAddressField(verbose_name='Login IP')),
('key', models.CharField(max_length=128, verbose_name='Session key')),
('city', models.CharField(blank=True, max_length=254, null=True, verbose_name='Login city')),
('user_agent', models.CharField(blank=True, max_length=254, null=True, verbose_name='User agent')),
('type', models.CharField(choices=[('W', 'Web'), ('T', 'Terminal'), ('U', 'Unknown')], max_length=2, verbose_name='Login type')),
('backend', models.CharField(default='', max_length=32, verbose_name='Authentication backend')),
('date_created', models.DateTimeField(blank=True, null=True, verbose_name='Date created')),
('date_expired', models.DateTimeField(blank=True, db_index=True, null=True, verbose_name='Date expired')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sessions', to=settings.AUTH_USER_MODEL, verbose_name='User')),
],
options={
'verbose_name': 'User session',
'ordering': ['-date_created'],
'permissions': [('offline_usersession', 'Offline ussr session')],
},
),
]

View File

@@ -0,0 +1,17 @@
# Generated by Django 4.1.10 on 2023-10-18 08:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('audits', '0024_usersession'),
]
operations = [
migrations.RemoveField(
model_name='usersession',
name='date_expired',
),
]

Some files were not shown because too many files have changed in this diff Show More