mirror of
https://github.com/jumpserver/jumpserver.git
synced 2025-12-17 09:32:35 +00:00
Compare commits
527 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d27947919b | ||
|
|
b92530f0b9 | ||
|
|
b113eeb1d6 | ||
|
|
eb3165f8e7 | ||
|
|
93d77b2312 | ||
|
|
ae1d419f70 | ||
|
|
36054cb64c | ||
|
|
022e93d7a2 | ||
|
|
ac14790960 | ||
|
|
facc231e3f | ||
|
|
e4178849ba | ||
|
|
151d897746 | ||
|
|
27588f48d8 | ||
|
|
303102d40b | ||
|
|
ff9632d6da | ||
|
|
4cbf6dd5e6 | ||
|
|
4f889cfe36 | ||
|
|
0c2e5f3f2a | ||
|
|
19ecc7fef6 | ||
|
|
0020343ae0 | ||
|
|
fa5c433c7c | ||
|
|
5139f9c4b9 | ||
|
|
d6aad41d05 | ||
|
|
b3acc0d451 | ||
|
|
330917df4c | ||
|
|
21d4ffa33b | ||
|
|
1bc14c53d4 | ||
|
|
5024d0d739 | ||
|
|
c5013dcbd6 | ||
|
|
84924bc3f6 | ||
|
|
2de769ecad | ||
|
|
ab68aed98f | ||
|
|
9b9e32d2f4 | ||
|
|
b6249e9a63 | ||
|
|
5f7fa7e02f | ||
|
|
74fe9dddb7 | ||
|
|
ade3f3ae6c | ||
|
|
1c3b574c46 | ||
|
|
92aeae4a2a | ||
|
|
ea6c28fa0d | ||
|
|
f44acc923b | ||
|
|
f27df2f523 | ||
|
|
bbf2aff96c | ||
|
|
3ea4a9fbe6 | ||
|
|
3962af7c4f | ||
|
|
38c6d11af1 | ||
|
|
5f45acf68f | ||
|
|
c7f2afc3c1 | ||
|
|
16fae00e0e | ||
|
|
0afeed0ff1 | ||
|
|
d72aa34513 | ||
|
|
d56de16563 | ||
|
|
8536e6fca7 | ||
|
|
adb9f01231 | ||
|
|
e0d4ad8570 | ||
|
|
3c8726f1b0 | ||
|
|
6b4bc1bdb5 | ||
|
|
c92d36391f | ||
|
|
24bbe7c31f | ||
|
|
77f2bd9262 | ||
|
|
495a6fbc95 | ||
|
|
36c6299a03 | ||
|
|
8a31fbe35e | ||
|
|
dbe628a8db | ||
|
|
e45b893662 | ||
|
|
ac4b6e5b96 | ||
|
|
c85249be36 | ||
|
|
de006bc664 | ||
|
|
a313e011ef | ||
|
|
3076b7a5e1 | ||
|
|
c47a588e7c | ||
|
|
7f61c49db2 | ||
|
|
c8a76c9afb | ||
|
|
3e85a9a079 | ||
|
|
62cbca7eb2 | ||
|
|
434793bc41 | ||
|
|
85a017b2c4 | ||
|
|
84bce19a92 | ||
|
|
3874b8ed67 | ||
|
|
7f0ad7e27f | ||
|
|
2ee26971c9 | ||
|
|
5ace5a752e | ||
|
|
e838d974c3 | ||
|
|
9dd93ea3b8 | ||
|
|
88ea7ae149 | ||
|
|
1132c6a4e4 | ||
|
|
0762f87ba5 | ||
|
|
cb98b4f80a | ||
|
|
599d58e9f2 | ||
|
|
5c6f1730d5 | ||
|
|
67d084fc43 | ||
|
|
24d0d52a0a | ||
|
|
d94c515cfc | ||
|
|
cae956f9a5 | ||
|
|
2c70e117c6 | ||
|
|
70e8a03888 | ||
|
|
d2df8acd84 | ||
|
|
6e5dcc738e | ||
|
|
d1ccb4af15 | ||
|
|
086ecfc046 | ||
|
|
8f3765a98d | ||
|
|
2d6610b133 | ||
|
|
5a82174c54 | ||
|
|
dac45f234a | ||
|
|
096b2cf8b8 | ||
|
|
0ed0f69be0 | ||
|
|
8af88cd2c6 | ||
|
|
2a9f0f8dcf | ||
|
|
cc2d47e6dc | ||
|
|
22c9dfc0f2 | ||
|
|
ed01f2f1fb | ||
|
|
c5ff0d972b | ||
|
|
7d9da9ff66 | ||
|
|
d6395b64fa | ||
|
|
9bfbdea508 | ||
|
|
cb1c906db4 | ||
|
|
12a0096963 | ||
|
|
a315e8888b | ||
|
|
454d3cba96 | ||
|
|
4a786baf4e | ||
|
|
187977c04a | ||
|
|
4260fe1424 | ||
|
|
7286b1b09e | ||
|
|
9a7919f3ac | ||
|
|
43cbf4f6a9 | ||
|
|
e9dc1ad86a | ||
|
|
90477146ed | ||
|
|
353b66bf8f | ||
|
|
3051996e35 | ||
|
|
8761ed741c | ||
|
|
0facd8a25e | ||
|
|
b28ce9de7a | ||
|
|
f2b72aae37 | ||
|
|
b001443f34 | ||
|
|
17303c0550 | ||
|
|
bac974b4f2 | ||
|
|
f9e970f4ed | ||
|
|
07c60ca75d | ||
|
|
bbe2678df3 | ||
|
|
d57f52ee24 | ||
|
|
55775f0deb | ||
|
|
fde118021e | ||
|
|
d484885762 | ||
|
|
8071f45f92 | ||
|
|
15cdd44c6c | ||
|
|
d44f90ea3d | ||
|
|
42e9fbf37a | ||
|
|
d44656aa10 | ||
|
|
09d4228182 | ||
|
|
3ae8da231a | ||
|
|
2e4b6d150a | ||
|
|
8542d53aff | ||
|
|
141dafc8bf | ||
|
|
28a6024b49 | ||
|
|
6cf2bc4baf | ||
|
|
631f802961 | ||
|
|
0eedda748a | ||
|
|
7183f0d274 | ||
|
|
c93ab15351 | ||
|
|
3fffd667dc | ||
|
|
11fd2afa3a | ||
|
|
1eb59b11da | ||
|
|
a1e2d4ca57 | ||
|
|
8a413563be | ||
|
|
203a01240b | ||
|
|
37fef6153a | ||
|
|
ba6c49e62b | ||
|
|
da79f8beab | ||
|
|
3f72c02049 | ||
|
|
380226a7d2 | ||
|
|
f88e5de3c1 | ||
|
|
7c149fe91b | ||
|
|
f673fed706 | ||
|
|
84326cc999 | ||
|
|
7d56678a8e | ||
|
|
25d1b71448 | ||
|
|
d3920a0cc9 | ||
|
|
52889cb67a | ||
|
|
0b67c7a953 | ||
|
|
1f50a2fe33 | ||
|
|
cd5094f10d | ||
|
|
c244cf5f43 | ||
|
|
a0db2f6ef8 | ||
|
|
ea485c3070 | ||
|
|
705f352cb9 | ||
|
|
dc13134b7b | ||
|
|
06de6c3575 | ||
|
|
c341d01e5a | ||
|
|
d1a3d31d3f | ||
|
|
10f4ff4eec | ||
|
|
25ea3ba01d | ||
|
|
072865f3e5 | ||
|
|
d5c9ec1c3d | ||
|
|
487c945d1d | ||
|
|
a78b2f4b62 | ||
|
|
a1f1dce56b | ||
|
|
a1221a39fd | ||
|
|
8c118b6f47 | ||
|
|
68fd8012d8 | ||
|
|
526928518d | ||
|
|
c5f6c564a7 | ||
|
|
076adec218 | ||
|
|
00d434ceea | ||
|
|
9acfd461b4 | ||
|
|
9424929dde | ||
|
|
b95d3ac9be | ||
|
|
af2a9bb1e6 | ||
|
|
63638ed1ce | ||
|
|
fa68389028 | ||
|
|
63b338085a | ||
|
|
5d8818e69e | ||
|
|
77521119b9 | ||
|
|
baee71e4b8 | ||
|
|
6459c20516 | ||
|
|
0207fe60c5 | ||
|
|
b8c43f5944 | ||
|
|
63ca2ab182 | ||
|
|
f9ea119928 | ||
|
|
d4bdc74bd8 | ||
|
|
42e7ca6a18 | ||
|
|
6e0341b7b1 | ||
|
|
2f25e2b24c | ||
|
|
87dcd2dcb7 | ||
|
|
e96aac058f | ||
|
|
d76bad125b | ||
|
|
913b1a1426 | ||
|
|
0213154a19 | ||
|
|
8f63b488b2 | ||
|
|
f8921004c2 | ||
|
|
5588eab57e | ||
|
|
e0a8f91741 | ||
|
|
467ebfa650 | ||
|
|
0533b77b1b | ||
|
|
a558ee2ac0 | ||
|
|
46a39701d4 | ||
|
|
8c3ab31e4e | ||
|
|
476e6cdc2f | ||
|
|
0b593f4555 | ||
|
|
456116938d | ||
|
|
76b24f62d4 | ||
|
|
e1eef0a3f3 | ||
|
|
2c74727b65 | ||
|
|
08cd91c426 | ||
|
|
90d269d2a2 | ||
|
|
a9ddbcc0cd | ||
|
|
aec31128cf | ||
|
|
b415ee051d | ||
|
|
082a5ae84c | ||
|
|
6b7554d69a | ||
|
|
5923562440 | ||
|
|
d144e7e572 | ||
|
|
cafbd08986 | ||
|
|
b436fc9b44 | ||
|
|
26fc56b4be | ||
|
|
3b1d199669 | ||
|
|
e7edbc9d84 | ||
|
|
41f81bc0bf | ||
|
|
75d2c81d33 | ||
|
|
da2dea5003 | ||
|
|
fc60156c23 | ||
|
|
76fb547551 | ||
|
|
e686f51703 | ||
|
|
7578bda588 | ||
|
|
f2d743ec2b | ||
|
|
7099aef360 | ||
|
|
246f5d8a11 | ||
|
|
6c98bd3b48 | ||
|
|
6def113cbd | ||
|
|
2dc0af2553 | ||
|
|
a291592e59 | ||
|
|
6fb4c1e181 | ||
|
|
eee093742c | ||
|
|
743c9bc3f1 | ||
|
|
f963c5ef9d | ||
|
|
2c46072db2 | ||
|
|
b375cd3e75 | ||
|
|
c26ca20ad8 | ||
|
|
982a510213 | ||
|
|
5d6880f6e9 | ||
|
|
a784a33203 | ||
|
|
a452f3307f | ||
|
|
b7a6287925 | ||
|
|
3cba8648cb | ||
|
|
ef7b2b7980 | ||
|
|
1ab247ac22 | ||
|
|
ef8a027849 | ||
|
|
7890e43f5a | ||
|
|
2030cbd19d | ||
|
|
0f7c8c2570 | ||
|
|
9b60d86ddd | ||
|
|
f129f99faa | ||
|
|
43f30b37da | ||
|
|
45aefa6b75 | ||
|
|
b30123054b | ||
|
|
b456e71ec4 | ||
|
|
7560b70c4d | ||
|
|
0c96df5283 | ||
|
|
9dda19b8d7 | ||
|
|
fbe5f9a63a | ||
|
|
1c4b4951dc | ||
|
|
8e12399058 | ||
|
|
741b96ddee | ||
|
|
8c3f89ee51 | ||
|
|
dee45ce2e0 | ||
|
|
cfab30f7f7 | ||
|
|
02e9a96792 | ||
|
|
aa6dcdc65d | ||
|
|
5a6b64eebd | ||
|
|
2dd7867b32 | ||
|
|
6507f0982c | ||
|
|
c115ef7b47 | ||
|
|
bf68ddf09e | ||
|
|
f3906ff998 | ||
|
|
e47ee43631 | ||
|
|
d22bb2c92f | ||
|
|
870dac37b9 | ||
|
|
d14c5c58ff | ||
|
|
a6b40510d0 | ||
|
|
f762fe73ff | ||
|
|
d49d1ba055 | ||
|
|
6e3d950e23 | ||
|
|
7939ef34b0 | ||
|
|
07cd930c0e | ||
|
|
c14c89a758 | ||
|
|
245367ec29 | ||
|
|
c5f4ecc8cc | ||
|
|
eb8bdf8623 | ||
|
|
a26c5a5e32 | ||
|
|
068db6d1ca | ||
|
|
e6e2a35745 | ||
|
|
fafc2791ab | ||
|
|
39507ef152 | ||
|
|
683fb9f596 | ||
|
|
ced9e53d62 | ||
|
|
93846234f8 | ||
|
|
8ac7d4b682 | ||
|
|
c4890f66e1 | ||
|
|
4618989813 | ||
|
|
29645768a0 | ||
|
|
8f1c934f73 | ||
|
|
7a45f4d129 | ||
|
|
55a5dd1e34 | ||
|
|
6695d0a8a2 | ||
|
|
84d6b3de26 | ||
|
|
17a5e919d5 | ||
|
|
3ba07867c8 | ||
|
|
75b76170f9 | ||
|
|
d34c7edb00 | ||
|
|
f64740c2db | ||
|
|
3a09845c29 | ||
|
|
09d51fd5be | ||
|
|
fc8181b5ed | ||
|
|
5a993c255d | ||
|
|
ad592fa504 | ||
|
|
1dcc8ff0a3 | ||
|
|
11a9a49bf8 | ||
|
|
b9ffc23066 | ||
|
|
ea4dccbab8 | ||
|
|
683461a49b | ||
|
|
1a1ad0f1a2 | ||
|
|
773f7048be | ||
|
|
f8f783745c | ||
|
|
4fe715d953 | ||
|
|
36dfc4bcb8 | ||
|
|
8925314dc7 | ||
|
|
817c02c667 | ||
|
|
58a10778cd | ||
|
|
fa81652de5 | ||
|
|
7e6fa27719 | ||
|
|
3e737c8cb8 | ||
|
|
345c0fcf4f | ||
|
|
bf6b685e8c | ||
|
|
654ec4970e | ||
|
|
4a436856b4 | ||
|
|
e993e7257c | ||
|
|
f12a59da2f | ||
|
|
42c3c85863 | ||
|
|
7e638ff8de | ||
|
|
932a65b840 | ||
|
|
81000953e2 | ||
|
|
dc742d1281 | ||
|
|
b1fceca8a6 | ||
|
|
d49d1e1414 | ||
|
|
dac3f7fc71 | ||
|
|
47989c41a3 | ||
|
|
ca34216141 | ||
|
|
905014d441 | ||
|
|
3e51f4d616 | ||
|
|
07179a4d22 | ||
|
|
7a2e93c087 | ||
|
|
3fb368c741 | ||
|
|
fca3a8fbca | ||
|
|
c1375ed7cb | ||
|
|
8b483b8c36 | ||
|
|
c465fccc33 | ||
|
|
3d934dc7c0 | ||
|
|
b69ed8cbe9 | ||
|
|
c27230762b | ||
|
|
7ea8205672 | ||
|
|
b9b55e3d67 | ||
|
|
900fc4420c | ||
|
|
0a3e5aed56 | ||
|
|
9fb6fd44d1 | ||
|
|
4214b220e1 | ||
|
|
ae80797ce4 | ||
|
|
d1be4a136e | ||
|
|
e8e211f47c | ||
|
|
44044a7d99 | ||
|
|
5854ad1975 | ||
|
|
0b1a1591f8 | ||
|
|
6241238b45 | ||
|
|
0f87f05b3f | ||
|
|
19c63a0b19 | ||
|
|
1fdc558ef7 | ||
|
|
9f6e26c4db | ||
|
|
628012a7ee | ||
|
|
c1579f5fe4 | ||
|
|
cbe0483b46 | ||
|
|
10c2935df4 | ||
|
|
10e06a4533 | ||
|
|
98e38ebfd8 | ||
|
|
9660e20176 | ||
|
|
21a7ec9fec | ||
|
|
7d123ff8c5 | ||
|
|
2af6ac504d | ||
|
|
6c8d1c4e77 | ||
|
|
52d3e1b34b | ||
|
|
bf6fcc9020 | ||
|
|
a0b756ebaa | ||
|
|
5e8a55f949 | ||
|
|
f9218584f4 | ||
|
|
228446979f | ||
|
|
aa37d86959 | ||
|
|
0e9079fa2e | ||
|
|
58c058c1a5 | ||
|
|
f390556a87 | ||
|
|
b7378da46e | ||
|
|
0c8c926aac | ||
|
|
81d8592ee1 | ||
|
|
af827f3626 | ||
|
|
91b269fc36 | ||
|
|
1605a57df6 | ||
|
|
5cd23b843a | ||
|
|
d46f1080f8 | ||
|
|
9a541ebf05 | ||
|
|
dba416f5eb | ||
|
|
7d7da9bf98 | ||
|
|
4425efd3c2 | ||
|
|
c6bb9e97fb | ||
|
|
9c7adb7a14 | ||
|
|
7b4faccf05 | ||
|
|
0cd3419e09 | ||
|
|
e49dedf6b1 | ||
|
|
bee4e05b5f | ||
|
|
a5419b49ee | ||
|
|
84e60283b8 | ||
|
|
96206384c0 | ||
|
|
78c61d5afa | ||
|
|
ee712d9a9d | ||
|
|
a1e8c2849a | ||
|
|
54751a715c | ||
|
|
a2907a6e6d | ||
|
|
33236aaa47 | ||
|
|
cd6c7ce7fa | ||
|
|
363baece4f | ||
|
|
1db0e28346 | ||
|
|
7366bbb197 | ||
|
|
7959f84bba | ||
|
|
0c96bf61ef | ||
|
|
39ce60c93a | ||
|
|
8ad78ffef8 | ||
|
|
66b499b8e3 | ||
|
|
22406f47f7 | ||
|
|
72f782b589 | ||
|
|
cf3df951a9 | ||
|
|
4085df913b | ||
|
|
d93f3aca51 | ||
|
|
b180a162cd | ||
|
|
1bf3ff5e1b | ||
|
|
0def477b63 | ||
|
|
337e1ba206 | ||
|
|
fe2d80046c | ||
|
|
f16a9ddb86 | ||
|
|
5f6c207721 | ||
|
|
988d686418 | ||
|
|
89e654af80 | ||
|
|
2ab1bbaa2c | ||
|
|
b43626b5a2 | ||
|
|
5e4b3e924f | ||
|
|
66b0173e20 | ||
|
|
67f6b1080e | ||
|
|
b56b897260 | ||
|
|
f031f4d560 | ||
|
|
d0e119fb50 | ||
|
|
7892e50aa2 | ||
|
|
bff3582136 | ||
|
|
bdf95903ce | ||
|
|
c1e6bc5d60 | ||
|
|
da588ce0ae | ||
|
|
d0680c3753 | ||
|
|
905d0d5131 | ||
|
|
d347ed9862 | ||
|
|
8611f765a3 | ||
|
|
962f1c0310 | ||
|
|
473a66719b | ||
|
|
aeb43a04f6 | ||
|
|
49a35985a1 | ||
|
|
21b789e08c | ||
|
|
51387ad97e | ||
|
|
290d584ac9 | ||
|
|
160b238058 | ||
|
|
938255df6f | ||
|
|
4230da0fd9 | ||
|
|
fee3715d30 | ||
|
|
689bd093be | ||
|
|
77461d7834 | ||
|
|
ee5894c296 | ||
|
|
07898004b0 | ||
|
|
630164cd51 | ||
|
|
981319e553 | ||
|
|
fedd32ea7a | ||
|
|
e57574f10a | ||
|
|
3f0a0b33b5 | ||
|
|
c21217d50c | ||
|
|
e44c8ae940 | ||
|
|
1da187c373 | ||
|
|
36ad42beb2 |
@@ -7,3 +7,4 @@ django.db
|
|||||||
celerybeat.pid
|
celerybeat.pid
|
||||||
### Vagrant ###
|
### Vagrant ###
|
||||||
.vagrant/
|
.vagrant/
|
||||||
|
apps/xpack/.git
|
||||||
2
.gitattributes
vendored
Normal file
2
.gitattributes
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
*.mmdb filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.mo filter=lfs diff=lfs merge=lfs -text
|
||||||
18
.github/workflows/issue-close-require.yml
vendored
Normal file
18
.github/workflows/issue-close-require.yml
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
name: Issue Close Require
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 0 * * *"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
issue-close-require:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: need reproduce
|
||||||
|
uses: actions-cool/issues-helper@v2
|
||||||
|
with:
|
||||||
|
actions: 'close-issues'
|
||||||
|
labels: '状态:待反馈'
|
||||||
|
inactive-day: 30
|
||||||
|
body: |
|
||||||
|
您超过 30 天未反馈信息,我们将关闭该 issue,如有需求您可以重新打开或者提交新的 issue。
|
||||||
16
.github/workflows/issue-close.yml
vendored
Normal file
16
.github/workflows/issue-close.yml
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
name: Issue Close Check
|
||||||
|
|
||||||
|
on:
|
||||||
|
issues:
|
||||||
|
types: [closed]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
issue-close-remove-labels:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Remove labels
|
||||||
|
uses: actions-cool/issues-helper@v2
|
||||||
|
if: ${{ !github.event.issue.pull_request }}
|
||||||
|
with:
|
||||||
|
actions: 'remove-labels'
|
||||||
|
labels: '状态:待处理,状态:待反馈'
|
||||||
38
.github/workflows/issue-comment.yml
vendored
Normal file
38
.github/workflows/issue-comment.yml
vendored
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
on:
|
||||||
|
issue_comment:
|
||||||
|
types: [created]
|
||||||
|
|
||||||
|
name: Add issues workflow labels
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
add-label-if-is-author:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: (github.event.issue.user.id == github.event.comment.user.id) && !github.event.issue.pull_request && (github.event.issue.state == 'open')
|
||||||
|
steps:
|
||||||
|
- name: Add require handle label
|
||||||
|
uses: actions-cool/issues-helper@v2
|
||||||
|
with:
|
||||||
|
actions: 'add-labels'
|
||||||
|
labels: '状态:待处理'
|
||||||
|
|
||||||
|
- name: Remove require reply label
|
||||||
|
uses: actions-cool/issues-helper@v2
|
||||||
|
with:
|
||||||
|
actions: 'remove-labels'
|
||||||
|
labels: '状态:待反馈'
|
||||||
|
|
||||||
|
add-label-if-not-author:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: (github.event.issue.user.id != github.event.comment.user.id) && !github.event.issue.pull_request && (github.event.issue.state == 'open')
|
||||||
|
steps:
|
||||||
|
- name: Add require replay label
|
||||||
|
uses: actions-cool/issues-helper@v2
|
||||||
|
with:
|
||||||
|
actions: 'add-labels'
|
||||||
|
labels: '状态:待反馈'
|
||||||
|
|
||||||
|
- name: Remove require handle label
|
||||||
|
uses: actions-cool/issues-helper@v2
|
||||||
|
with:
|
||||||
|
actions: 'remove-labels'
|
||||||
|
labels: '状态:待处理'
|
||||||
16
.github/workflows/issue-open.yml
vendored
Normal file
16
.github/workflows/issue-open.yml
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
name: Issue Open Check
|
||||||
|
|
||||||
|
on:
|
||||||
|
issues:
|
||||||
|
types: [opened]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
issue-open-add-labels:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Add labels
|
||||||
|
uses: actions-cool/issues-helper@v2
|
||||||
|
if: ${{ !github.event.issue.pull_request }}
|
||||||
|
with:
|
||||||
|
actions: 'add-labels'
|
||||||
|
labels: '状态:待处理'
|
||||||
17
.github/workflows/issue-recent-alert.yml
vendored
Normal file
17
.github/workflows/issue-recent-alert.yml
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 1 * * *"
|
||||||
|
|
||||||
|
name: Check recent handle issues
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check-recent-issues-not-handle:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check recent issues and send msg
|
||||||
|
uses: jumpserver/action-issues-alert@master
|
||||||
|
with:
|
||||||
|
hook: ${{ secrets.WECHAT_GROUP_WEB_HOOK }}
|
||||||
|
type: recent
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
17
.github/workflows/issue-untimely-alert.yml
vendored
Normal file
17
.github/workflows/issue-untimely-alert.yml
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 9 * * 1-5"
|
||||||
|
|
||||||
|
name: Check untimely handle issues
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check-untimely-handle-issues:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check untimely issues and send msg
|
||||||
|
uses: jumpserver/action-issues-alert@master
|
||||||
|
with:
|
||||||
|
hook: ${{ secrets.WECHAT_GROUP_WEB_HOOK }}
|
||||||
|
type: untimely
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -39,3 +39,4 @@ logs/*
|
|||||||
.vagrant/
|
.vagrant/
|
||||||
release/*
|
release/*
|
||||||
releashe
|
releashe
|
||||||
|
/apps/script.py
|
||||||
|
|||||||
28
Dockerfile
28
Dockerfile
@@ -8,7 +8,6 @@ WORKDIR /opt/jumpserver
|
|||||||
ADD . .
|
ADD . .
|
||||||
RUN cd utils && bash -ixeu build.sh
|
RUN cd utils && bash -ixeu build.sh
|
||||||
|
|
||||||
|
|
||||||
# 构建运行时环境
|
# 构建运行时环境
|
||||||
FROM python:3.8.6-slim
|
FROM python:3.8.6-slim
|
||||||
ARG PIP_MIRROR=https://pypi.douban.com/simple
|
ARG PIP_MIRROR=https://pypi.douban.com/simple
|
||||||
@@ -18,26 +17,39 @@ ENV PIP_JMS_MIRROR=$PIP_JMS_MIRROR
|
|||||||
|
|
||||||
WORKDIR /opt/jumpserver
|
WORKDIR /opt/jumpserver
|
||||||
|
|
||||||
COPY ./requirements/deb_buster_requirements.txt ./requirements/deb_buster_requirements.txt
|
COPY ./requirements/deb_requirements.txt ./requirements/deb_requirements.txt
|
||||||
RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list \
|
RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list \
|
||||||
&& sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list \
|
&& sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list \
|
||||||
&& apt update \
|
&& apt update \
|
||||||
&& grep -v '^#' ./requirements/deb_buster_requirements.txt | xargs apt -y install \
|
&& apt -y install telnet iproute2 redis-tools default-mysql-client vim wget curl locales procps \
|
||||||
|
&& apt -y install $(cat requirements/deb_requirements.txt) \
|
||||||
&& rm -rf /var/lib/apt/lists/* \
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
&& localedef -c -f UTF-8 -i zh_CN zh_CN.UTF-8 \
|
&& localedef -c -f UTF-8 -i zh_CN zh_CN.UTF-8 \
|
||||||
&& cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
&& cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
||||||
|
&& sed -i "s@# alias l@alias l@g" ~/.bashrc \
|
||||||
|
&& echo "set mouse-=a" > ~/.vimrc
|
||||||
|
|
||||||
COPY ./requirements/requirements.txt ./requirements/requirements.txt
|
COPY ./requirements/requirements.txt ./requirements/requirements.txt
|
||||||
RUN pip install --upgrade pip==20.2.4 setuptools==49.6.0 wheel==0.34.2 -i ${PIP_MIRROR} \
|
RUN pip install --upgrade pip==20.2.4 setuptools==49.6.0 wheel==0.34.2 -i ${PIP_MIRROR} \
|
||||||
&& pip config set global.index-url ${PIP_MIRROR} \
|
&& pip install --no-cache-dir $(grep -E 'jms|jumpserver' requirements/requirements.txt) -i ${PIP_JMS_MIRROR} \
|
||||||
&& pip install --no-cache-dir $(grep 'jms' requirements/requirements.txt) -i ${PIP_JMS_MIRROR} \
|
&& pip install --no-cache-dir -r requirements/requirements.txt -i ${PIP_MIRROR} \
|
||||||
&& pip install --no-cache-dir -r requirements/requirements.txt
|
&& rm -rf ~/.cache/pip
|
||||||
|
|
||||||
COPY --from=stage-build /opt/jumpserver/release/jumpserver /opt/jumpserver
|
COPY --from=stage-build /opt/jumpserver/release/jumpserver /opt/jumpserver
|
||||||
RUN mkdir -p /root/.ssh/ \
|
RUN mkdir -p /root/.ssh/ \
|
||||||
&& echo "Host *\n\tStrictHostKeyChecking no\n\tUserKnownHostsFile /dev/null" > /root/.ssh/config
|
&& echo "Host *\n\tStrictHostKeyChecking no\n\tUserKnownHostsFile /dev/null" > /root/.ssh/config \
|
||||||
|
&& mv /bin/sh /bin/sh.bak \
|
||||||
|
&& ln -s /bin/bash /bin/sh
|
||||||
|
|
||||||
|
RUN mkdir -p /opt/jumpserver/oracle/ \
|
||||||
|
&& wget https://download.jumpserver.org/public/instantclient-basiclite-linux.x64-21.1.0.0.0.tar > /dev/null \
|
||||||
|
&& tar xf instantclient-basiclite-linux.x64-21.1.0.0.0.tar -C /opt/jumpserver/oracle/ \
|
||||||
|
&& echo "/opt/jumpserver/oracle/instantclient_21_1" > /etc/ld.so.conf.d/oracle-instantclient.conf \
|
||||||
|
&& ldconfig \
|
||||||
|
&& rm -f instantclient-basiclite-linux.x64-21.1.0.0.0.tar
|
||||||
|
|
||||||
RUN echo > config.yml
|
RUN echo > config.yml
|
||||||
|
|
||||||
VOLUME /opt/jumpserver/data
|
VOLUME /opt/jumpserver/data
|
||||||
VOLUME /opt/jumpserver/logs
|
VOLUME /opt/jumpserver/logs
|
||||||
|
|
||||||
|
|||||||
837
LICENSE
837
LICENSE
@@ -1,281 +1,622 @@
|
|||||||
GNU GENERAL PUBLIC LICENSE
|
GNU GENERAL PUBLIC LICENSE
|
||||||
Version 2, June 1991
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
of this license document, but changing it is not allowed.
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Preamble
|
Preamble
|
||||||
|
|
||||||
The licenses for most software are designed to take away your
|
The GNU General Public License is a free, copyleft license for
|
||||||
freedom to share and change it. By contrast, the GNU General Public
|
software and other kinds of works.
|
||||||
License is intended to guarantee your freedom to share and change free
|
|
||||||
software--to make sure the software is free for all its users. This
|
The licenses for most software and other practical works are designed
|
||||||
General Public License applies to most of the Free Software
|
to take away your freedom to share and change the works. By contrast,
|
||||||
Foundation's software and to any other program whose authors commit to
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
using it. (Some other Free Software Foundation software is covered by
|
share and change all versions of a program--to make sure it remains free
|
||||||
the GNU Lesser General Public License instead.) You can apply it to
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
your programs, too.
|
your programs, too.
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not
|
When we speak of free software, we are referring to freedom, not
|
||||||
price. Our General Public Licenses are designed to make sure that you
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
have the freedom to distribute copies of free software (and charge for
|
have the freedom to distribute copies of free software (and charge for
|
||||||
this service if you wish), that you receive source code or can get it
|
them if you wish), that you receive source code or can get it if you
|
||||||
if you want it, that you can change the software or use pieces of it
|
want it, that you can change the software or use pieces of it in new
|
||||||
in new free programs; and that you know you can do these things.
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
To protect your rights, we need to make restrictions that forbid
|
To protect your rights, we need to prevent others from denying you
|
||||||
anyone to deny you these rights or to ask you to surrender the rights.
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
These restrictions translate to certain responsibilities for you if you
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
distribute copies of the software, or if you modify it.
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
For example, if you distribute copies of such a program, whether
|
For example, if you distribute copies of such a program, whether
|
||||||
gratis or for a fee, you must give the recipients all the rights that
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
you have. You must make sure that they, too, receive or can get the
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
source code. And you must show them these terms so they know their
|
or can get the source code. And you must show them these terms so they
|
||||||
rights.
|
know their rights.
|
||||||
|
|
||||||
We protect your rights with two steps: (1) copyright the software, and
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
(2) offer you this license which gives you legal permission to copy,
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
distribute and/or modify the software.
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
Also, for each author's protection and ours, we want to make certain
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
that everyone understands that there is no warranty for this free
|
that there is no warranty for this free software. For both users' and
|
||||||
software. If the software is modified by someone else and passed on, we
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
want its recipients to know that what they have is not the original, so
|
changed, so that their problems will not be attributed erroneously to
|
||||||
that any problems introduced by others will not reflect on the original
|
authors of previous versions.
|
||||||
authors' reputations.
|
|
||||||
|
|
||||||
Finally, any free program is threatened constantly by software
|
Some devices are designed to deny users access to install or run
|
||||||
patents. We wish to avoid the danger that redistributors of a free
|
modified versions of the software inside them, although the manufacturer
|
||||||
program will individually obtain patent licenses, in effect making the
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
program proprietary. To prevent this, we have made it clear that any
|
protecting users' freedom to change the software. The systematic
|
||||||
patent must be licensed for everyone's free use or not licensed at all.
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and
|
The precise terms and conditions for copying, distribution and
|
||||||
modification follow.
|
modification follow.
|
||||||
|
|
||||||
GNU GENERAL PUBLIC LICENSE
|
TERMS AND CONDITIONS
|
||||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
|
||||||
|
|
||||||
0. This License applies to any program or other work which contains
|
0. Definitions.
|
||||||
a notice placed by the copyright holder saying it may be distributed
|
|
||||||
under the terms of this General Public License. The "Program", below,
|
|
||||||
refers to any such program or work, and a "work based on the Program"
|
|
||||||
means either the Program or any derivative work under copyright law:
|
|
||||||
that is to say, a work containing the Program or a portion of it,
|
|
||||||
either verbatim or with modifications and/or translated into another
|
|
||||||
language. (Hereinafter, translation is included without limitation in
|
|
||||||
the term "modification".) Each licensee is addressed as "you".
|
|
||||||
|
|
||||||
Activities other than copying, distribution and modification are not
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
covered by this License; they are outside its scope. The act of
|
|
||||||
running the Program is not restricted, and the output from the Program
|
|
||||||
is covered only if its contents constitute a work based on the
|
|
||||||
Program (independent of having been made by running the Program).
|
|
||||||
Whether that is true depends on what the Program does.
|
|
||||||
|
|
||||||
1. You may copy and distribute verbatim copies of the Program's
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
source code as you receive it, in any medium, provided that you
|
works, such as semiconductor masks.
|
||||||
conspicuously and appropriately publish on each copy an appropriate
|
|
||||||
copyright notice and disclaimer of warranty; keep intact all the
|
|
||||||
notices that refer to this License and to the absence of any warranty;
|
|
||||||
and give any other recipients of the Program a copy of this License
|
|
||||||
along with the Program.
|
|
||||||
|
|
||||||
You may charge a fee for the physical act of transferring a copy, and
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
you may at your option offer warranty protection in exchange for a fee.
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
2. You may modify your copy or copies of the Program or any portion
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
of it, thus forming a work based on the Program, and copy and
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
distribute such modifications or work under the terms of Section 1
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
above, provided that you also meet all of these conditions:
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
a) You must cause the modified files to carry prominent notices
|
A "covered work" means either the unmodified Program or a work based
|
||||||
stating that you changed the files and the date of any change.
|
on the Program.
|
||||||
|
|
||||||
b) You must cause any work that you distribute or publish, that in
|
To "propagate" a work means to do anything with it that, without
|
||||||
whole or in part contains or is derived from the Program or any
|
permission, would make you directly or secondarily liable for
|
||||||
part thereof, to be licensed as a whole at no charge to all third
|
infringement under applicable copyright law, except executing it on a
|
||||||
parties under the terms of this License.
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
c) If the modified program normally reads commands interactively
|
To "convey" a work means any kind of propagation that enables other
|
||||||
when run, you must cause it, when started running for such
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
interactive use in the most ordinary way, to print or display an
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
announcement including an appropriate copyright notice and a
|
|
||||||
notice that there is no warranty (or else, saying that you provide
|
|
||||||
a warranty) and that users may redistribute the program under
|
|
||||||
these conditions, and telling the user how to view a copy of this
|
|
||||||
License. (Exception: if the Program itself is interactive but
|
|
||||||
does not normally print such an announcement, your work based on
|
|
||||||
the Program is not required to print an announcement.)
|
|
||||||
|
|
||||||
These requirements apply to the modified work as a whole. If
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
identifiable sections of that work are not derived from the Program,
|
to the extent that it includes a convenient and prominently visible
|
||||||
and can be reasonably considered independent and separate works in
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
themselves, then this License, and its terms, do not apply to those
|
tells the user that there is no warranty for the work (except to the
|
||||||
sections when you distribute them as separate works. But when you
|
extent that warranties are provided), that licensees may convey the
|
||||||
distribute the same sections as part of a whole which is a work based
|
work under this License, and how to view a copy of this License. If
|
||||||
on the Program, the distribution of the whole must be on the terms of
|
the interface presents a list of user commands or options, such as a
|
||||||
this License, whose permissions for other licensees extend to the
|
menu, a prominent item in the list meets this criterion.
|
||||||
entire whole, and thus to each and every part regardless of who wrote it.
|
|
||||||
|
|
||||||
Thus, it is not the intent of this section to claim rights or contest
|
1. Source Code.
|
||||||
your rights to work written entirely by you; rather, the intent is to
|
|
||||||
exercise the right to control the distribution of derivative or
|
|
||||||
collective works based on the Program.
|
|
||||||
|
|
||||||
In addition, mere aggregation of another work not based on the Program
|
The "source code" for a work means the preferred form of the work
|
||||||
with the Program (or with a work based on the Program) on a volume of
|
for making modifications to it. "Object code" means any non-source
|
||||||
a storage or distribution medium does not bring the other work under
|
form of a work.
|
||||||
the scope of this License.
|
|
||||||
|
|
||||||
3. You may copy and distribute the Program (or a work based on it,
|
A "Standard Interface" means an interface that either is an official
|
||||||
under Section 2) in object code or executable form under the terms of
|
standard defined by a recognized standards body, or, in the case of
|
||||||
Sections 1 and 2 above provided that you also do one of the following:
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
a) Accompany it with the complete corresponding machine-readable
|
The "System Libraries" of an executable work include anything, other
|
||||||
source code, which must be distributed under the terms of Sections
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
1 and 2 above on a medium customarily used for software interchange; or,
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
b) Accompany it with a written offer, valid for at least three
|
The "Corresponding Source" for a work in object code form means all
|
||||||
years, to give any third party, for a charge no more than your
|
the source code needed to generate, install, and (for an executable
|
||||||
cost of physically performing source distribution, a complete
|
work) run the object code and to modify the work, including scripts to
|
||||||
machine-readable copy of the corresponding source code, to be
|
control those activities. However, it does not include the work's
|
||||||
distributed under the terms of Sections 1 and 2 above on a medium
|
System Libraries, or general-purpose tools or generally available free
|
||||||
customarily used for software interchange; or,
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
c) Accompany it with the information you received as to the offer
|
The Corresponding Source need not include anything that users
|
||||||
to distribute corresponding source code. (This alternative is
|
can regenerate automatically from other parts of the Corresponding
|
||||||
allowed only for noncommercial distribution and only if you
|
Source.
|
||||||
received the program in object code or executable form with such
|
|
||||||
an offer, in accord with Subsection b above.)
|
|
||||||
|
|
||||||
The source code for a work means the preferred form of the work for
|
The Corresponding Source for a work in source code form is that
|
||||||
making modifications to it. For an executable work, complete source
|
same work.
|
||||||
code means all the source code for all modules it contains, plus any
|
|
||||||
associated interface definition files, plus the scripts used to
|
|
||||||
control compilation and installation of the executable. However, as a
|
|
||||||
special exception, the source code distributed need not include
|
|
||||||
anything that is normally distributed (in either source or binary
|
|
||||||
form) with the major components (compiler, kernel, and so on) of the
|
|
||||||
operating system on which the executable runs, unless that component
|
|
||||||
itself accompanies the executable.
|
|
||||||
|
|
||||||
If distribution of executable or object code is made by offering
|
2. Basic Permissions.
|
||||||
access to copy from a designated place, then offering equivalent
|
|
||||||
access to copy the source code from the same place counts as
|
|
||||||
distribution of the source code, even though third parties are not
|
|
||||||
compelled to copy the source along with the object code.
|
|
||||||
|
|
||||||
4. You may not copy, modify, sublicense, or distribute the Program
|
All rights granted under this License are granted for the term of
|
||||||
except as expressly provided under this License. Any attempt
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
otherwise to copy, modify, sublicense or distribute the Program is
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
void, and will automatically terminate your rights under this License.
|
permission to run the unmodified Program. The output from running a
|
||||||
However, parties who have received copies, or rights, from you under
|
covered work is covered by this License only if the output, given its
|
||||||
this License will not have their licenses terminated so long as such
|
content, constitutes a covered work. This License acknowledges your
|
||||||
parties remain in full compliance.
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
5. You are not required to accept this License, since you have not
|
You may make, run and propagate covered works that you do not
|
||||||
signed it. However, nothing else grants you permission to modify or
|
convey, without conditions so long as your license otherwise remains
|
||||||
distribute the Program or its derivative works. These actions are
|
in force. You may convey covered works to others for the sole purpose
|
||||||
prohibited by law if you do not accept this License. Therefore, by
|
of having them make modifications exclusively for you, or provide you
|
||||||
modifying or distributing the Program (or any work based on the
|
with facilities for running those works, provided that you comply with
|
||||||
Program), you indicate your acceptance of this License to do so, and
|
the terms of this License in conveying all material for which you do
|
||||||
all its terms and conditions for copying, distributing or modifying
|
not control copyright. Those thus making or running the covered works
|
||||||
the Program or works based on it.
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
6. Each time you redistribute the Program (or any work based on the
|
Conveying under any other circumstances is permitted solely under
|
||||||
Program), the recipient automatically receives a license from the
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
original licensor to copy, distribute or modify the Program subject to
|
makes it unnecessary.
|
||||||
these terms and conditions. You may not impose any further
|
|
||||||
restrictions on the recipients' exercise of the rights granted herein.
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
You are not responsible for enforcing compliance by third parties to
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
this License.
|
this License.
|
||||||
|
|
||||||
7. If, as a consequence of a court judgment or allegation of patent
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
infringement or for any other reason (not limited to patent issues),
|
patent license under the contributor's essential patent claims, to
|
||||||
conditions are imposed on you (whether by court order, agreement or
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
otherwise) that contradict the conditions of this License, they do not
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
excuse you from the conditions of this License. If you cannot
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
distribute so as to satisfy simultaneously your obligations under this
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
License and any other pertinent obligations, then as a consequence you
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
may not distribute the Program at all. For example, if a patent
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
license would not permit royalty-free redistribution of the Program by
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
all those who receive copies directly or indirectly through you, then
|
the Program, the only way you could satisfy both those terms and this
|
||||||
the only way you could satisfy both it and this License would be to
|
License would be to refrain entirely from conveying the Program.
|
||||||
refrain entirely from distribution of the Program.
|
|
||||||
|
|
||||||
If any portion of this section is held invalid or unenforceable under
|
13. Use with the GNU Affero General Public License.
|
||||||
any particular circumstance, the balance of the section is intended to
|
|
||||||
apply and the section as a whole is intended to apply in other
|
|
||||||
circumstances.
|
|
||||||
|
|
||||||
It is not the purpose of this section to induce you to infringe any
|
Notwithstanding any other provision of this License, you have
|
||||||
patents or other property right claims or to contest validity of any
|
permission to link or combine any covered work with a work licensed
|
||||||
such claims; this section has the sole purpose of protecting the
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
integrity of the free software distribution system, which is
|
combined work, and to convey the resulting work. The terms of this
|
||||||
implemented by public license practices. Many people have made
|
License will continue to apply to the part which is the covered work,
|
||||||
generous contributions to the wide range of software distributed
|
but the special requirements of the GNU Affero General Public License,
|
||||||
through that system in reliance on consistent application of that
|
section 13, concerning interaction through a network will apply to the
|
||||||
system; it is up to the author/donor to decide if he or she is willing
|
combination as such.
|
||||||
to distribute software through any other system and a licensee cannot
|
|
||||||
impose that choice.
|
|
||||||
|
|
||||||
This section is intended to make thoroughly clear what is believed to
|
14. Revised Versions of this License.
|
||||||
be a consequence of the rest of this License.
|
|
||||||
|
|
||||||
8. If the distribution and/or use of the Program is restricted in
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
certain countries either by patents or by copyrighted interfaces, the
|
the GNU General Public License from time to time. Such new versions will
|
||||||
original copyright holder who places the Program under this License
|
|
||||||
may add an explicit geographical distribution limitation excluding
|
|
||||||
those countries, so that distribution is permitted only in or among
|
|
||||||
countries not thus excluded. In such case, this License incorporates
|
|
||||||
the limitation as if written in the body of this License.
|
|
||||||
|
|
||||||
9. The Free Software Foundation may publish revised and/or new versions
|
|
||||||
of the General Public License from time to time. Such new versions will
|
|
||||||
be similar in spirit to the present version, but may differ in detail to
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
address new problems or concerns.
|
address new problems or concerns.
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the Program
|
Each version is given a distinguishing version number. If the
|
||||||
specifies a version number of this License which applies to it and "any
|
Program specifies that a certain numbered version of the GNU General
|
||||||
later version", you have the option of following the terms and conditions
|
Public License "or any later version" applies to it, you have the
|
||||||
either of that version or of any later version published by the Free
|
option of following the terms and conditions either of that numbered
|
||||||
Software Foundation. If the Program does not specify a version number of
|
version or of any later version published by the Free Software
|
||||||
this License, you may choose any version ever published by the Free Software
|
Foundation. If the Program does not specify a version number of the
|
||||||
Foundation.
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
10. If you wish to incorporate parts of the Program into other free
|
If the Program specifies that a proxy can decide which future
|
||||||
programs whose distribution conditions are different, write to the author
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
to ask for permission. For software which is copyrighted by the Free
|
public statement of acceptance of a version permanently authorizes you
|
||||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
to choose that version for the Program.
|
||||||
make exceptions for this. Our decision will be guided by the two goals
|
|
||||||
of preserving the free status of all derivatives of our free software and
|
|
||||||
of promoting the sharing and reuse of software generally.
|
|
||||||
|
|
||||||
NO WARRANTY
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
15. Disclaimer of Warranty.
|
||||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
|
||||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
|
||||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
|
||||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
|
||||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
|
||||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
|
||||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
|
||||||
REPAIR OR CORRECTION.
|
|
||||||
|
|
||||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
POSSIBILITY OF SUCH DAMAGES.
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
@@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms.
|
|||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest
|
To do so, attach the following notices to the program. It is safest
|
||||||
to attach them to the start of each source file to most effectively
|
to attach them to the start of each source file to most effectively
|
||||||
convey the exclusion of warranty; and each file should have at least
|
state the exclusion of warranty; and each file should have at least
|
||||||
the "copyright" line and a pointer to where the full notice is found.
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
{description}
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
Copyright (C) {year} {fullname}
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
This program is free software; you can redistribute it and/or modify
|
This program is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
the Free Software Foundation; either version 2 of the License, or
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
(at your option) any later version.
|
(at your option) any later version.
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
This program is distributed in the hope that it will be useful,
|
||||||
@@ -303,37 +644,31 @@ the "copyright" line and a pointer to where the full notice is found.
|
|||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
GNU General Public License for more details.
|
GNU General Public License for more details.
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License along
|
You should have received a copy of the GNU General Public License
|
||||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
If the program is interactive, make it output a short notice like this
|
If the program does terminal interaction, make it output a short
|
||||||
when it starts in an interactive mode:
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
Gnomovision version 69, Copyright (C) year name of author
|
<program> Copyright (C) <year> <name of author>
|
||||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
This is free software, and you are welcome to redistribute it
|
This is free software, and you are welcome to redistribute it
|
||||||
under certain conditions; type `show c' for details.
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
parts of the General Public License. Of course, the commands you use may
|
parts of the General Public License. Of course, your program's commands
|
||||||
be called something other than `show w' and `show c'; they could even be
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
mouse-clicks or menu items--whatever suits your program.
|
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or your
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
necessary. Here is a sample; alter the names:
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
The GNU General Public License does not permit incorporating your program
|
||||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
{signature of Ty Coon}, 1 April 1989
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
Ty Coon, President of Vice
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
This General Public License does not permit incorporating your program into
|
|
||||||
proprietary programs. If your program is a subroutine library, you may
|
|
||||||
consider it more useful to permit linking proprietary applications with the
|
|
||||||
library. If this is what you want to do, use the GNU Lesser General
|
|
||||||
Public License instead of this License.
|
|
||||||
28
README.md
28
README.md
@@ -2,7 +2,7 @@
|
|||||||
<h3 align="center">多云环境下更好用的堡垒机</h3>
|
<h3 align="center">多云环境下更好用的堡垒机</h3>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0"><img src="https://shields.io/github/license/jumpserver/jumpserver" alt="License: GPL v2"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.html"><img src="https://img.shields.io/github/license/jumpserver/jumpserver" alt="License: GPLv3"></a>
|
||||||
<a href="https://shields.io/github/downloads/jumpserver/jumpserver/total"><img src="https://shields.io/github/downloads/jumpserver/jumpserver/total" alt=" release"></a>
|
<a href="https://shields.io/github/downloads/jumpserver/jumpserver/total"><img src="https://shields.io/github/downloads/jumpserver/jumpserver/total" alt=" release"></a>
|
||||||
<a href="https://hub.docker.com/u/jumpserver"><img src="https://img.shields.io/docker/pulls/jumpserver/jms_all.svg" alt="Codacy"></a>
|
<a href="https://hub.docker.com/u/jumpserver"><img src="https://img.shields.io/docker/pulls/jumpserver/jms_all.svg" alt="Codacy"></a>
|
||||||
<a href="https://github.com/jumpserver/jumpserver"><img src="https://img.shields.io/github/stars/jumpserver/jumpserver?color=%231890FF&style=flat-square" alt="Stars"></a>
|
<a href="https://github.com/jumpserver/jumpserver"><img src="https://img.shields.io/github/stars/jumpserver/jumpserver?color=%231890FF&style=flat-square" alt="Stars"></a>
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
JumpServer 是全球首款开源的堡垒机,使用 GNU GPL v2.0 开源协议,是符合 4A 规范的运维安全审计系统。
|
JumpServer 是全球首款开源的堡垒机,使用 GPLv3 开源协议,是符合 4A 规范的运维安全审计系统。
|
||||||
|
|
||||||
JumpServer 使用 Python 开发,遵循 Web 2.0 规范,配备了业界领先的 Web Terminal 方案,交互界面美观、用户体验好。
|
JumpServer 使用 Python 开发,遵循 Web 2.0 规范,配备了业界领先的 Web Terminal 方案,交互界面美观、用户体验好。
|
||||||
|
|
||||||
@@ -21,6 +21,7 @@ JumpServer 采纳分布式架构,支持多机房跨区域部署,支持横向
|
|||||||
|
|
||||||
改变世界,从一点点开始 ...
|
改变世界,从一点点开始 ...
|
||||||
|
|
||||||
|
> 如需进一步了解 JumpServer 开源项目,推荐阅读 [JumpServer 的初心和使命](https://mp.weixin.qq.com/s/S6q_2rP_9MwaVwyqLQnXzA)
|
||||||
|
|
||||||
### 特色优势
|
### 特色优势
|
||||||
|
|
||||||
@@ -32,6 +33,19 @@ JumpServer 采纳分布式架构,支持多机房跨区域部署,支持横向
|
|||||||
- 多租户: 一套系统,多个子公司和部门同时使用;
|
- 多租户: 一套系统,多个子公司和部门同时使用;
|
||||||
- 多应用支持: 数据库,Windows远程应用,Kubernetes。
|
- 多应用支持: 数据库,Windows远程应用,Kubernetes。
|
||||||
|
|
||||||
|
### UI 展示
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### 在线体验
|
||||||
|
|
||||||
|
- 环境地址:<https://demo.jumpserver.org/>
|
||||||
|
|
||||||
|
| :warning: 注意 |
|
||||||
|
| :--------------------------- |
|
||||||
|
| 该环境仅作体验目的使用,我们会定时清理、重置数据! |
|
||||||
|
| 请勿修改体验环境用户的密码! |
|
||||||
|
| 请勿在环境中添加业务生产环境地址、用户名密码等敏感信息! |
|
||||||
|
|
||||||
### 快速开始
|
### 快速开始
|
||||||
|
|
||||||
@@ -45,6 +59,8 @@ JumpServer 采纳分布式架构,支持多机房跨区域部署,支持横向
|
|||||||
- [Luna](https://github.com/jumpserver/luna) JumpServer Web Terminal 项目
|
- [Luna](https://github.com/jumpserver/luna) JumpServer Web Terminal 项目
|
||||||
- [KoKo](https://github.com/jumpserver/koko) JumpServer 字符协议 Connector 项目,替代原来 Python 版本的 [Coco](https://github.com/jumpserver/coco)
|
- [KoKo](https://github.com/jumpserver/koko) JumpServer 字符协议 Connector 项目,替代原来 Python 版本的 [Coco](https://github.com/jumpserver/coco)
|
||||||
- [Lion](https://github.com/jumpserver/lion-release) JumpServer 图形协议 Connector 项目,依赖 [Apache Guacamole](https://guacamole.apache.org/)
|
- [Lion](https://github.com/jumpserver/lion-release) JumpServer 图形协议 Connector 项目,依赖 [Apache Guacamole](https://guacamole.apache.org/)
|
||||||
|
- [Clients](https://github.com/jumpserver/clients) JumpServer 客户端 项目
|
||||||
|
- [Installer](https://github.com/jumpserver/installer) JumpServer 安装包 项目
|
||||||
|
|
||||||
### 社区
|
### 社区
|
||||||
|
|
||||||
@@ -52,7 +68,7 @@ JumpServer 采纳分布式架构,支持多机房跨区域部署,支持横向
|
|||||||
|
|
||||||
#### 微信交流群
|
#### 微信交流群
|
||||||
|
|
||||||
<img src="https://download.jumpserver.org/images/weixin-group.jpeg" alt="微信群二维码" width="200"/>
|
<img src="https://download.jumpserver.org/images/wecom-group.jpeg" alt="微信群二维码" width="200"/>
|
||||||
|
|
||||||
### 贡献
|
### 贡献
|
||||||
如果有你好的想法创意,或者帮助我们修复了 Bug, 欢迎提交 Pull Request
|
如果有你好的想法创意,或者帮助我们修复了 Bug, 欢迎提交 Pull Request
|
||||||
@@ -108,11 +124,11 @@ JumpServer是一款安全产品,请参考 [基本安全建议](https://docs.ju
|
|||||||
|
|
||||||
### License & Copyright
|
### License & Copyright
|
||||||
|
|
||||||
Copyright (c) 2014-2020 飞致云 FIT2CLOUD, All rights reserved.
|
Copyright (c) 2014-2021 飞致云 FIT2CLOUD, All rights reserved.
|
||||||
|
|
||||||
Licensed under The GNU General Public License version 2 (GPLv2) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
|
Licensed under The GNU General Public License version 3 (GPLv3) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
|
||||||
|
|
||||||
https://www.gnu.org/licenses/gpl-2.0.html
|
https://www.gnu.org/licenses/gpl-3.0.html
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
||||||
|
|
||||||
|
|||||||
11
README_EN.md
11
README_EN.md
@@ -2,13 +2,13 @@
|
|||||||
<h3 align="center">Open Source Bastion Host</h3>
|
<h3 align="center">Open Source Bastion Host</h3>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0"><img src="https://shields.io/github/license/jumpserver/jumpserver" alt="License: GPL v2"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.html"><img src="https://img.shields.io/github/license/jumpserver/jumpserver" alt="License: GPLv3"></a>
|
||||||
<a href="https://shields.io/github/downloads/jumpserver/jumpserver/total"><img src="https://shields.io/github/downloads/jumpserver/jumpserver/total" alt=" release"></a>
|
<a href="https://shields.io/github/downloads/jumpserver/jumpserver/total"><img src="https://shields.io/github/downloads/jumpserver/jumpserver/total" alt=" release"></a>
|
||||||
<a href="https://hub.docker.com/u/jumpserver"><img src="https://img.shields.io/docker/pulls/jumpserver/jms_all.svg" alt="Codacy"></a>
|
<a href="https://hub.docker.com/u/jumpserver"><img src="https://img.shields.io/docker/pulls/jumpserver/jms_all.svg" alt="Codacy"></a>
|
||||||
<a href="https://github.com/jumpserver/jumpserver"><img src="https://img.shields.io/github/stars/jumpserver/jumpserver?color=%231890FF&style=flat-square" alt="Stars"></a>
|
<a href="https://github.com/jumpserver/jumpserver"><img src="https://img.shields.io/github/stars/jumpserver/jumpserver?color=%231890FF&style=flat-square" alt="Stars"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
JumpServer is the world's first open-source Bastion Host and is licensed under the GNU GPL v2.0. It is a 4A-compliant professional operation and maintenance security audit system.
|
JumpServer is the world's first open-source Bastion Host and is licensed under the GPLv3. It is a 4A-compliant professional operation and maintenance security audit system.
|
||||||
|
|
||||||
JumpServer uses Python / Django for development, follows Web 2.0 specifications, and is equipped with an industry-leading Web Terminal solution that provides a beautiful user interface and great user experience
|
JumpServer uses Python / Django for development, follows Web 2.0 specifications, and is equipped with an industry-leading Web Terminal solution that provides a beautiful user interface and great user experience
|
||||||
|
|
||||||
@@ -85,10 +85,11 @@ If you find a security problem, please contact us directly:
|
|||||||
- 400-052-0755
|
- 400-052-0755
|
||||||
|
|
||||||
### License & Copyright
|
### License & Copyright
|
||||||
Copyright (c) 2014-2019 Beijing Duizhan Tech, Inc., All rights reserved.
|
Copyright (c) 2014-2021 FIT2CLOUD Tech, Inc., All rights reserved.
|
||||||
|
|
||||||
Licensed under The GNU General Public License version 2 (GPLv2) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
|
Licensed under The GNU General Public License version 3 (GPLv3) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
|
||||||
|
|
||||||
https://www.gnu.org/licenses/gpl-2.0.html
|
https://www.gnu.org/licenses/gpl-3.0.htmll
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
||||||
|
|
||||||
|
|||||||
9
SECURITY.md
Normal file
9
SECURITY.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# 安全说明
|
||||||
|
|
||||||
|
JumpServer 是一款正在成长的安全产品, 请参考 [基本安全建议](https://docs.jumpserver.org/zh/master/install/install_security/) 部署安装.
|
||||||
|
|
||||||
|
如果你发现安全问题,请直接联系我们,我们携手让世界更好:
|
||||||
|
|
||||||
|
- ibuler@fit2cloud.com
|
||||||
|
- support@fit2cloud.com
|
||||||
|
- 400-052-0755
|
||||||
@@ -2,14 +2,15 @@ from common.permissions import IsOrgAdmin, HasQueryParamsUserAndIsCurrentOrgMemb
|
|||||||
from common.drf.api import JMSBulkModelViewSet
|
from common.drf.api import JMSBulkModelViewSet
|
||||||
from ..models import LoginACL
|
from ..models import LoginACL
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
|
from ..filters import LoginAclFilter
|
||||||
|
|
||||||
__all__ = ['LoginACLViewSet', ]
|
__all__ = ['LoginACLViewSet', ]
|
||||||
|
|
||||||
|
|
||||||
class LoginACLViewSet(JMSBulkModelViewSet):
|
class LoginACLViewSet(JMSBulkModelViewSet):
|
||||||
queryset = LoginACL.objects.all()
|
queryset = LoginACL.objects.all()
|
||||||
filterset_fields = ('name', 'user', )
|
filterset_class = LoginAclFilter
|
||||||
search_fields = filterset_fields
|
search_fields = ('name',)
|
||||||
permission_classes = (IsOrgAdmin,)
|
permission_classes = (IsOrgAdmin,)
|
||||||
serializer_class = serializers.LoginACLSerializer
|
serializer_class = serializers.LoginACLSerializer
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
from orgs.mixins.api import OrgBulkModelViewSet
|
from orgs.mixins.api import OrgBulkModelViewSet
|
||||||
from common.permissions import IsOrgAdmin
|
from common.permissions import IsOrgAdmin
|
||||||
from .. import models, serializers
|
from .. import models, serializers
|
||||||
|
|||||||
@@ -1,15 +1,13 @@
|
|||||||
from django.shortcuts import get_object_or_404
|
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.generics import CreateAPIView, RetrieveDestroyAPIView
|
from rest_framework.generics import CreateAPIView
|
||||||
|
|
||||||
from common.permissions import IsAppUser
|
from common.permissions import IsAppUser
|
||||||
from common.utils import reverse, lazyproperty
|
from common.utils import reverse, lazyproperty
|
||||||
from orgs.utils import tmp_to_org, tmp_to_root_org
|
from orgs.utils import tmp_to_org
|
||||||
from tickets.api import GenericTicketStatusRetrieveCloseAPI
|
from tickets.api import GenericTicketStatusRetrieveCloseAPI
|
||||||
from ..models import LoginAssetACL
|
from ..models import LoginAssetACL
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
|
|
||||||
|
|
||||||
__all__ = ['LoginAssetCheckAPI', 'LoginAssetConfirmStatusAPI']
|
__all__ = ['LoginAssetCheckAPI', 'LoginAssetConfirmStatusAPI']
|
||||||
|
|
||||||
|
|
||||||
@@ -57,11 +55,12 @@ class LoginAssetCheckAPI(CreateAPIView):
|
|||||||
external=True, api_to_ui=True
|
external=True, api_to_ui=True
|
||||||
)
|
)
|
||||||
ticket_detail_url = '{url}?type={type}'.format(url=ticket_detail_url, type=ticket.type)
|
ticket_detail_url = '{url}?type={type}'.format(url=ticket_detail_url, type=ticket.type)
|
||||||
|
ticket_assignees = ticket.current_node.first().ticket_assignees.all()
|
||||||
data = {
|
data = {
|
||||||
'check_confirm_status': {'method': 'GET', 'url': confirm_status_url},
|
'check_confirm_status': {'method': 'GET', 'url': confirm_status_url},
|
||||||
'close_confirm': {'method': 'DELETE', 'url': confirm_status_url},
|
'close_confirm': {'method': 'DELETE', 'url': confirm_status_url},
|
||||||
'ticket_detail_url': ticket_detail_url,
|
'ticket_detail_url': ticket_detail_url,
|
||||||
'reviewers': [str(user) for user in ticket.assignees.all()],
|
'reviewers': [str(ticket_assignee.assignee) for ticket_assignee in ticket_assignees]
|
||||||
}
|
}
|
||||||
return data
|
return data
|
||||||
|
|
||||||
@@ -74,4 +73,3 @@ class LoginAssetCheckAPI(CreateAPIView):
|
|||||||
|
|
||||||
class LoginAssetConfirmStatusAPI(GenericTicketStatusRetrieveCloseAPI):
|
class LoginAssetConfirmStatusAPI(GenericTicketStatusRetrieveCloseAPI):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
15
apps/acls/filters.py
Normal file
15
apps/acls/filters.py
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
from django_filters import rest_framework as filters
|
||||||
|
from common.drf.filters import BaseFilterSet
|
||||||
|
|
||||||
|
from acls.models import LoginACL
|
||||||
|
|
||||||
|
|
||||||
|
class LoginAclFilter(BaseFilterSet):
|
||||||
|
user = filters.UUIDFilter(field_name='user_id')
|
||||||
|
user_display = filters.CharFilter(field_name='user__name')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = LoginACL
|
||||||
|
fields = (
|
||||||
|
'name', 'user', 'user_display', 'action'
|
||||||
|
)
|
||||||
98
apps/acls/migrations/0002_auto_20210926_1047.py
Normal file
98
apps/acls/migrations/0002_auto_20210926_1047.py
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
# Generated by Django 3.1.12 on 2021-09-26 02:47
|
||||||
|
import django
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models, transaction
|
||||||
|
from acls.models import LoginACL
|
||||||
|
|
||||||
|
LOGIN_CONFIRM_ZH = '登录复核'
|
||||||
|
LOGIN_CONFIRM_EN = 'Login confirm'
|
||||||
|
|
||||||
|
DEFAULT_TIME_PERIODS = [{'id': i, 'value': '00:00~00:00'} for i in range(7)]
|
||||||
|
|
||||||
|
|
||||||
|
def has_zh(name: str) -> bool:
|
||||||
|
for i in name:
|
||||||
|
if u'\u4e00' <= i <= u'\u9fff':
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_login_confirm(apps, schema_editor):
|
||||||
|
login_acl_model = apps.get_model("acls", "LoginACL")
|
||||||
|
login_confirm_model = apps.get_model("authentication", "LoginConfirmSetting")
|
||||||
|
|
||||||
|
with transaction.atomic():
|
||||||
|
for instance in login_confirm_model.objects.filter(is_active=True):
|
||||||
|
user = instance.user
|
||||||
|
reviewers = instance.reviewers.all()
|
||||||
|
login_confirm = LOGIN_CONFIRM_ZH if has_zh(user.name) else LOGIN_CONFIRM_EN
|
||||||
|
date_created = instance.date_created.strftime('%Y-%m-%d %H:%M:%S')
|
||||||
|
if reviewers.count() == 0:
|
||||||
|
continue
|
||||||
|
data = {
|
||||||
|
'user': user,
|
||||||
|
'name': f'{user.name}-{login_confirm} ({date_created})',
|
||||||
|
'created_by': instance.created_by,
|
||||||
|
'action': LoginACL.ActionChoices.confirm,
|
||||||
|
'rules': {'ip_group': ['*'], 'time_period': DEFAULT_TIME_PERIODS}
|
||||||
|
}
|
||||||
|
instance = login_acl_model.objects.create(**data)
|
||||||
|
instance.reviewers.set(reviewers)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_ip_group(apps, schema_editor):
|
||||||
|
login_acl_model = apps.get_model("acls", "LoginACL")
|
||||||
|
updates = list()
|
||||||
|
with transaction.atomic():
|
||||||
|
for instance in login_acl_model.objects.exclude(action=LoginACL.ActionChoices.confirm):
|
||||||
|
instance.rules = {'ip_group': instance.ip_group, 'time_period': DEFAULT_TIME_PERIODS}
|
||||||
|
updates.append(instance)
|
||||||
|
login_acl_model.objects.bulk_update(updates, ['rules', ])
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
('acls', '0001_initial'),
|
||||||
|
('authentication', '0004_ssotoken'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='loginacl',
|
||||||
|
name='action',
|
||||||
|
field=models.CharField(choices=[('reject', 'Reject'), ('allow', 'Allow'), ('confirm', 'Login confirm')],
|
||||||
|
default='reject', max_length=64, verbose_name='Action'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='loginacl',
|
||||||
|
name='reviewers',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='login_confirm_acls',
|
||||||
|
to=settings.AUTH_USER_MODEL, verbose_name='Reviewers'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='loginacl',
|
||||||
|
name='user',
|
||||||
|
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name='login_acls', to=settings.AUTH_USER_MODEL, verbose_name='User'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='loginacl',
|
||||||
|
name='rules',
|
||||||
|
field=models.JSONField(default=dict, verbose_name='Rule'),
|
||||||
|
),
|
||||||
|
migrations.RunPython(migrate_login_confirm),
|
||||||
|
migrations.RunPython(migrate_ip_group),
|
||||||
|
migrations.RemoveField(
|
||||||
|
model_name='loginacl',
|
||||||
|
name='ip_group',
|
||||||
|
),
|
||||||
|
migrations.AlterModelOptions(
|
||||||
|
name='loginacl',
|
||||||
|
options={'ordering': ('priority', '-date_updated', 'name'), 'verbose_name': 'Login acl'},
|
||||||
|
),
|
||||||
|
migrations.AlterModelOptions(
|
||||||
|
name='loginassetacl',
|
||||||
|
options={'ordering': ('priority', '-date_updated', 'name'), 'verbose_name': 'Login asset acl'},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from .base import BaseACL, BaseACLQuerySet
|
from .base import BaseACL, BaseACLQuerySet
|
||||||
from ..utils import contains_ip
|
from common.utils import get_request_ip, get_ip_city
|
||||||
|
from common.utils.ip import contains_ip
|
||||||
|
from common.utils.time_period import contains_time_period
|
||||||
|
from common.utils.timezone import local_now_display
|
||||||
|
|
||||||
|
|
||||||
class ACLManager(models.Manager):
|
class ACLManager(models.Manager):
|
||||||
@@ -15,23 +17,29 @@ class LoginACL(BaseACL):
|
|||||||
class ActionChoices(models.TextChoices):
|
class ActionChoices(models.TextChoices):
|
||||||
reject = 'reject', _('Reject')
|
reject = 'reject', _('Reject')
|
||||||
allow = 'allow', _('Allow')
|
allow = 'allow', _('Allow')
|
||||||
|
confirm = 'confirm', _('Login confirm')
|
||||||
|
|
||||||
# 条件
|
# 用户
|
||||||
ip_group = models.JSONField(default=list, verbose_name=_('Login IP'))
|
user = models.ForeignKey(
|
||||||
|
'users.User', on_delete=models.CASCADE, verbose_name=_('User'),
|
||||||
|
related_name='login_acls'
|
||||||
|
)
|
||||||
|
# 规则
|
||||||
|
rules = models.JSONField(default=dict, verbose_name=_('Rule'))
|
||||||
# 动作
|
# 动作
|
||||||
action = models.CharField(
|
action = models.CharField(
|
||||||
max_length=64, choices=ActionChoices.choices, default=ActionChoices.reject,
|
max_length=64, verbose_name=_('Action'),
|
||||||
verbose_name=_('Action')
|
choices=ActionChoices.choices, default=ActionChoices.reject
|
||||||
)
|
)
|
||||||
# 关联
|
reviewers = models.ManyToManyField(
|
||||||
user = models.ForeignKey(
|
'users.User', verbose_name=_("Reviewers"),
|
||||||
'users.User', on_delete=models.CASCADE, related_name='login_acls', verbose_name=_('User')
|
related_name="login_confirm_acls", blank=True
|
||||||
)
|
)
|
||||||
|
|
||||||
objects = ACLManager.from_queryset(BaseACLQuerySet)()
|
objects = ACLManager.from_queryset(BaseACLQuerySet)()
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
ordering = ('priority', '-date_updated', 'name')
|
ordering = ('priority', '-date_updated', 'name')
|
||||||
|
verbose_name = _('Login acl')
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.name
|
return self.name
|
||||||
@@ -44,14 +52,77 @@ class LoginACL(BaseACL):
|
|||||||
def action_allow(self):
|
def action_allow(self):
|
||||||
return self.action == self.ActionChoices.allow
|
return self.action == self.ActionChoices.allow
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def filter_acl(cls, user):
|
||||||
|
return user.login_acls.all().valid().distinct()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def allow_user_confirm_if_need(user, ip):
|
||||||
|
acl = LoginACL.filter_acl(user).filter(
|
||||||
|
action=LoginACL.ActionChoices.confirm
|
||||||
|
).first()
|
||||||
|
acl = acl if acl and acl.reviewers.exists() else None
|
||||||
|
if not acl:
|
||||||
|
return False, acl
|
||||||
|
ip_group = acl.rules.get('ip_group')
|
||||||
|
time_periods = acl.rules.get('time_period')
|
||||||
|
is_contain_ip = contains_ip(ip, ip_group)
|
||||||
|
is_contain_time_period = contains_time_period(time_periods)
|
||||||
|
return is_contain_ip and is_contain_time_period, acl
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def allow_user_to_login(user, ip):
|
def allow_user_to_login(user, ip):
|
||||||
acl = user.login_acls.valid().first()
|
acl = LoginACL.filter_acl(user).exclude(
|
||||||
|
action=LoginACL.ActionChoices.confirm
|
||||||
|
).first()
|
||||||
if not acl:
|
if not acl:
|
||||||
return True
|
return True, ''
|
||||||
is_contained = contains_ip(ip, acl.ip_group)
|
ip_group = acl.rules.get('ip_group')
|
||||||
if acl.action_allow and is_contained:
|
time_periods = acl.rules.get('time_period')
|
||||||
return True
|
is_contain_ip = contains_ip(ip, ip_group)
|
||||||
if acl.action_reject and not is_contained:
|
is_contain_time_period = contains_time_period(time_periods)
|
||||||
return True
|
|
||||||
return False
|
reject_type = ''
|
||||||
|
if is_contain_ip and is_contain_time_period:
|
||||||
|
# 满足条件
|
||||||
|
allow = acl.action_allow
|
||||||
|
if not allow:
|
||||||
|
reject_type = 'ip' if is_contain_ip else 'time'
|
||||||
|
else:
|
||||||
|
# 不满足条件
|
||||||
|
# 如果acl本身允许,那就拒绝;如果本身拒绝,那就允许
|
||||||
|
allow = not acl.action_allow
|
||||||
|
if not allow:
|
||||||
|
reject_type = 'ip' if not is_contain_ip else 'time'
|
||||||
|
|
||||||
|
return allow, reject_type
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def construct_confirm_ticket_meta(request=None):
|
||||||
|
login_ip = get_request_ip(request) if request else ''
|
||||||
|
login_ip = login_ip or '0.0.0.0'
|
||||||
|
login_city = get_ip_city(login_ip)
|
||||||
|
login_datetime = local_now_display()
|
||||||
|
ticket_meta = {
|
||||||
|
'apply_login_ip': login_ip,
|
||||||
|
'apply_login_city': login_city,
|
||||||
|
'apply_login_datetime': login_datetime,
|
||||||
|
}
|
||||||
|
return ticket_meta
|
||||||
|
|
||||||
|
def create_confirm_ticket(self, request=None):
|
||||||
|
from tickets import const
|
||||||
|
from tickets.models import Ticket
|
||||||
|
from orgs.models import Organization
|
||||||
|
ticket_title = _('Login confirm') + ' {}'.format(self.user)
|
||||||
|
ticket_meta = self.construct_confirm_ticket_meta(request)
|
||||||
|
data = {
|
||||||
|
'title': ticket_title,
|
||||||
|
'type': const.TicketType.login_confirm.value,
|
||||||
|
'meta': ticket_meta,
|
||||||
|
'org_id': Organization.ROOT_ID,
|
||||||
|
}
|
||||||
|
ticket = Ticket.objects.create(**data)
|
||||||
|
ticket.create_process_map_and_node(self.reviewers.all())
|
||||||
|
ticket.open(self.user)
|
||||||
|
return ticket
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ from django.db.models import Q
|
|||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from orgs.mixins.models import OrgModelMixin, OrgManager
|
from orgs.mixins.models import OrgModelMixin, OrgManager
|
||||||
from .base import BaseACL, BaseACLQuerySet
|
from .base import BaseACL, BaseACLQuerySet
|
||||||
from ..utils import contains_ip
|
from common.utils.ip import contains_ip
|
||||||
|
|
||||||
|
|
||||||
class ACLManager(OrgManager):
|
class ACLManager(OrgManager):
|
||||||
@@ -37,6 +37,7 @@ class LoginAssetACL(BaseACL, OrgModelMixin):
|
|||||||
class Meta:
|
class Meta:
|
||||||
unique_together = ('name', 'org_id')
|
unique_together = ('name', 'org_id')
|
||||||
ordering = ('priority', '-date_updated', 'name')
|
ordering = ('priority', '-date_updated', 'name')
|
||||||
|
verbose_name = _('Login asset acl')
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.name
|
return self.name
|
||||||
@@ -83,11 +84,11 @@ class LoginAssetACL(BaseACL, OrgModelMixin):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def create_login_asset_confirm_ticket(cls, user, asset, system_user, assignees, org_id):
|
def create_login_asset_confirm_ticket(cls, user, asset, system_user, assignees, org_id):
|
||||||
from tickets.const import TicketTypeChoices
|
from tickets.const import TicketType
|
||||||
from tickets.models import Ticket
|
from tickets.models import Ticket
|
||||||
data = {
|
data = {
|
||||||
'title': _('Login asset confirm') + ' ({})'.format(user),
|
'title': _('Login asset confirm') + ' ({})'.format(user),
|
||||||
'type': TicketTypeChoices.login_asset_confirm,
|
'type': TicketType.login_asset_confirm,
|
||||||
'meta': {
|
'meta': {
|
||||||
'apply_login_user': str(user),
|
'apply_login_user': str(user),
|
||||||
'apply_login_asset': str(asset),
|
'apply_login_asset': str(asset),
|
||||||
@@ -96,7 +97,7 @@ class LoginAssetACL(BaseACL, OrgModelMixin):
|
|||||||
'org_id': org_id,
|
'org_id': org_id,
|
||||||
}
|
}
|
||||||
ticket = Ticket.objects.create(**data)
|
ticket = Ticket.objects.create(**data)
|
||||||
ticket.assignees.set(assignees)
|
ticket.create_process_map_and_node(assignees)
|
||||||
ticket.open(applicant=user)
|
ticket.open(applicant=user)
|
||||||
return ticket
|
return ticket
|
||||||
|
|
||||||
|
|||||||
@@ -1,59 +1,56 @@
|
|||||||
from django.utils.translation import ugettext as _
|
from django.utils.translation import ugettext as _
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
from common.drf.serializers import BulkModelSerializer
|
from common.drf.serializers import BulkModelSerializer
|
||||||
from orgs.utils import current_org
|
from common.drf.serializers import MethodSerializer
|
||||||
|
from jumpserver.utils import has_valid_xpack_license
|
||||||
from ..models import LoginACL
|
from ..models import LoginACL
|
||||||
from ..utils import is_ip_address, is_ip_network, is_ip_segment
|
from .rules import RuleSerializer
|
||||||
|
|
||||||
|
|
||||||
__all__ = ['LoginACLSerializer', ]
|
__all__ = ['LoginACLSerializer', ]
|
||||||
|
|
||||||
|
common_help_text = _('Format for comma-delimited string, with * indicating a match all. ')
|
||||||
def ip_group_child_validator(ip_group_child):
|
|
||||||
is_valid = ip_group_child == '*' \
|
|
||||||
or is_ip_address(ip_group_child) \
|
|
||||||
or is_ip_network(ip_group_child) \
|
|
||||||
or is_ip_segment(ip_group_child)
|
|
||||||
if not is_valid:
|
|
||||||
error = _('IP address invalid: `{}`').format(ip_group_child)
|
|
||||||
raise serializers.ValidationError(error)
|
|
||||||
|
|
||||||
|
|
||||||
class LoginACLSerializer(BulkModelSerializer):
|
class LoginACLSerializer(BulkModelSerializer):
|
||||||
ip_group_help_text = _(
|
user_display = serializers.ReadOnlyField(source='user.username', label=_('Username'))
|
||||||
'Format for comma-delimited string, with * indicating a match all. '
|
reviewers_display = serializers.SerializerMethodField(label=_('Reviewers'))
|
||||||
'Such as: '
|
|
||||||
'192.168.10.1, 192.168.1.0/24, 10.1.1.1-10.1.1.20, 2001:db8:2de::e13, 2001:db8:1a:1110::/64 '
|
|
||||||
)
|
|
||||||
|
|
||||||
ip_group = serializers.ListField(
|
|
||||||
default=['*'], label=_('IP'), help_text=ip_group_help_text,
|
|
||||||
child=serializers.CharField(max_length=1024, validators=[ip_group_child_validator])
|
|
||||||
)
|
|
||||||
user_display = serializers.ReadOnlyField(source='user.name', label=_('User'))
|
|
||||||
action_display = serializers.ReadOnlyField(source='get_action_display', label=_('Action'))
|
action_display = serializers.ReadOnlyField(source='get_action_display', label=_('Action'))
|
||||||
|
reviewers_amount = serializers.IntegerField(read_only=True, source='reviewers.count')
|
||||||
|
rules = MethodSerializer()
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = LoginACL
|
model = LoginACL
|
||||||
fields_mini = ['id', 'name']
|
fields_mini = ['id', 'name']
|
||||||
fields_small = fields_mini + [
|
fields_small = fields_mini + [
|
||||||
'priority', 'ip_group', 'action', 'action_display',
|
'priority', 'rules', 'action', 'action_display',
|
||||||
'is_active',
|
'is_active', 'user', 'user_display',
|
||||||
'date_created', 'date_updated',
|
'date_created', 'date_updated', 'reviewers_amount',
|
||||||
'comment', 'created_by',
|
'comment', 'created_by'
|
||||||
]
|
]
|
||||||
fields_fk = ['user', 'user_display',]
|
fields_fk = ['user', 'user_display']
|
||||||
fields = fields_small + fields_fk
|
fields_m2m = ['reviewers', 'reviewers_display']
|
||||||
|
fields = fields_small + fields_fk + fields_m2m
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'priority': {'default': 50},
|
'priority': {'default': 50},
|
||||||
'is_active': {'default': True},
|
'is_active': {'default': True},
|
||||||
|
"reviewers": {'allow_null': False, 'required': True},
|
||||||
}
|
}
|
||||||
|
|
||||||
@staticmethod
|
def __init__(self, *args, **kwargs):
|
||||||
def validate_user(user):
|
super().__init__(*args, **kwargs)
|
||||||
if user not in current_org.get_members():
|
self.set_action_choices()
|
||||||
error = _('The user `{}` is not in the current organization: `{}`').format(
|
|
||||||
user, current_org
|
def set_action_choices(self):
|
||||||
)
|
action = self.fields.get('action')
|
||||||
raise serializers.ValidationError(error)
|
if not action:
|
||||||
return user
|
return
|
||||||
|
choices = action._choices
|
||||||
|
if not has_valid_xpack_license():
|
||||||
|
choices.pop(LoginACL.ActionChoices.confirm, None)
|
||||||
|
action._choices = choices
|
||||||
|
|
||||||
|
def get_rules_serializer(self):
|
||||||
|
return RuleSerializer()
|
||||||
|
|
||||||
|
def get_reviewers_display(self, obj):
|
||||||
|
return ','.join([str(user) for user in obj.reviewers.all()])
|
||||||
|
|||||||
1
apps/acls/serializers/rules/__init__.py
Normal file
1
apps/acls/serializers/rules/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
from .rules import *
|
||||||
35
apps/acls/serializers/rules/rules.py
Normal file
35
apps/acls/serializers/rules/rules.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# coding: utf-8
|
||||||
|
#
|
||||||
|
from rest_framework import serializers
|
||||||
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
|
from common.utils import get_logger
|
||||||
|
from common.utils.ip import is_ip_address, is_ip_network, is_ip_segment
|
||||||
|
|
||||||
|
logger = get_logger(__file__)
|
||||||
|
|
||||||
|
__all__ = ['RuleSerializer', 'ip_group_child_validator', 'ip_group_help_text']
|
||||||
|
|
||||||
|
|
||||||
|
def ip_group_child_validator(ip_group_child):
|
||||||
|
is_valid = ip_group_child == '*' \
|
||||||
|
or is_ip_address(ip_group_child) \
|
||||||
|
or is_ip_network(ip_group_child) \
|
||||||
|
or is_ip_segment(ip_group_child)
|
||||||
|
if not is_valid:
|
||||||
|
error = _('IP address invalid: `{}`').format(ip_group_child)
|
||||||
|
raise serializers.ValidationError(error)
|
||||||
|
|
||||||
|
|
||||||
|
ip_group_help_text = _(
|
||||||
|
'Format for comma-delimited string, with * indicating a match all. '
|
||||||
|
'Such as: '
|
||||||
|
'192.168.10.1, 192.168.1.0/24, 10.1.1.1-10.1.1.20, 2001:db8:2de::e13, 2001:db8:1a:1110::/64 '
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RuleSerializer(serializers.Serializer):
|
||||||
|
ip_group = serializers.ListField(
|
||||||
|
default=['*'], label=_('IP'), help_text=ip_group_help_text,
|
||||||
|
child=serializers.CharField(max_length=1024, validators=[ip_group_child_validator]))
|
||||||
|
time_period = serializers.ListField(default=[], label=_('Time Period'))
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
from ipaddress import ip_network, ip_address
|
|
||||||
|
|
||||||
|
|
||||||
def is_ip_address(address):
|
|
||||||
""" 192.168.10.1 """
|
|
||||||
try:
|
|
||||||
ip_address(address)
|
|
||||||
except ValueError:
|
|
||||||
return False
|
|
||||||
else:
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def is_ip_network(ip):
|
|
||||||
""" 192.168.1.0/24 """
|
|
||||||
try:
|
|
||||||
ip_network(ip)
|
|
||||||
except ValueError:
|
|
||||||
return False
|
|
||||||
else:
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def is_ip_segment(ip):
|
|
||||||
""" 10.1.1.1-10.1.1.20 """
|
|
||||||
if '-' not in ip:
|
|
||||||
return False
|
|
||||||
ip_address1, ip_address2 = ip.split('-')
|
|
||||||
return is_ip_address(ip_address1) and is_ip_address(ip_address2)
|
|
||||||
|
|
||||||
|
|
||||||
def in_ip_segment(ip, ip_segment):
|
|
||||||
ip1, ip2 = ip_segment.split('-')
|
|
||||||
ip1 = int(ip_address(ip1))
|
|
||||||
ip2 = int(ip_address(ip2))
|
|
||||||
ip = int(ip_address(ip))
|
|
||||||
return min(ip1, ip2) <= ip <= max(ip1, ip2)
|
|
||||||
|
|
||||||
|
|
||||||
def contains_ip(ip, ip_group):
|
|
||||||
"""
|
|
||||||
ip_group:
|
|
||||||
[192.168.10.1, 192.168.1.0/24, 10.1.1.1-10.1.1.20, 2001:db8:2de::e13, 2001:db8:1a:1110::/64.]
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
if '*' in ip_group:
|
|
||||||
return True
|
|
||||||
|
|
||||||
for _ip in ip_group:
|
|
||||||
if is_ip_address(_ip):
|
|
||||||
# 192.168.10.1
|
|
||||||
if ip == _ip:
|
|
||||||
return True
|
|
||||||
elif is_ip_network(_ip) and is_ip_address(ip):
|
|
||||||
# 192.168.1.0/24
|
|
||||||
if ip_address(ip) in ip_network(_ip):
|
|
||||||
return True
|
|
||||||
elif is_ip_segment(_ip) and is_ip_address(ip):
|
|
||||||
# 10.1.1.1-10.1.1.20
|
|
||||||
if in_ip_segment(ip, _ip):
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
# is domain name
|
|
||||||
if ip == _ip:
|
|
||||||
return True
|
|
||||||
|
|
||||||
return False
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from .application import *
|
from .application import *
|
||||||
from .application_user import *
|
from .account import *
|
||||||
from .mixin import *
|
from .mixin import *
|
||||||
from .remote_app import *
|
from .remote_app import *
|
||||||
|
|||||||
58
apps/applications/api/account.py
Normal file
58
apps/applications/api/account.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
# coding: utf-8
|
||||||
|
#
|
||||||
|
|
||||||
|
from django_filters import rest_framework as filters
|
||||||
|
from django.db.models import F, Q
|
||||||
|
|
||||||
|
from common.drf.filters import BaseFilterSet
|
||||||
|
from common.drf.api import JMSBulkModelViewSet
|
||||||
|
from ..models import Account
|
||||||
|
from ..hands import IsOrgAdminOrAppUser, IsOrgAdmin, NeedMFAVerify
|
||||||
|
from .. import serializers
|
||||||
|
|
||||||
|
|
||||||
|
class AccountFilterSet(BaseFilterSet):
|
||||||
|
username = filters.CharFilter(method='do_nothing')
|
||||||
|
type = filters.CharFilter(field_name='type', lookup_expr='exact')
|
||||||
|
category = filters.CharFilter(field_name='category', lookup_expr='exact')
|
||||||
|
app_display = filters.CharFilter(field_name='app_display', lookup_expr='exact')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
fields = ['app', 'systemuser']
|
||||||
|
|
||||||
|
@property
|
||||||
|
def qs(self):
|
||||||
|
qs = super().qs
|
||||||
|
qs = self.filter_username(qs)
|
||||||
|
return qs
|
||||||
|
|
||||||
|
def filter_username(self, qs):
|
||||||
|
username = self.get_query_param('username')
|
||||||
|
if not username:
|
||||||
|
return qs
|
||||||
|
qs = qs.filter(Q(username=username) | Q(systemuser__username=username)).distinct()
|
||||||
|
return qs
|
||||||
|
|
||||||
|
|
||||||
|
class ApplicationAccountViewSet(JMSBulkModelViewSet):
|
||||||
|
model = Account
|
||||||
|
search_fields = ['username', 'app_display']
|
||||||
|
filterset_class = AccountFilterSet
|
||||||
|
filterset_fields = ['username', 'app_display', 'type', 'category', 'app']
|
||||||
|
serializer_class = serializers.AppAccountSerializer
|
||||||
|
permission_classes = (IsOrgAdmin,)
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
queryset = Account.objects.all() \
|
||||||
|
.annotate(type=F('app__type')) \
|
||||||
|
.annotate(app_display=F('app__name')) \
|
||||||
|
.annotate(systemuser_display=F('systemuser__name')) \
|
||||||
|
.annotate(category=F('app__category'))
|
||||||
|
return queryset
|
||||||
|
|
||||||
|
|
||||||
|
class ApplicationAccountSecretViewSet(ApplicationAccountViewSet):
|
||||||
|
serializer_class = serializers.AppAccountSecretSerializer
|
||||||
|
permission_classes = [IsOrgAdminOrAppUser, NeedMFAVerify]
|
||||||
|
http_method_names = ['get', 'options']
|
||||||
@@ -2,18 +2,37 @@
|
|||||||
#
|
#
|
||||||
|
|
||||||
from orgs.mixins.api import OrgBulkModelViewSet
|
from orgs.mixins.api import OrgBulkModelViewSet
|
||||||
|
from rest_framework.decorators import action
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
from common.tree import TreeNodeSerializer
|
||||||
|
from common.mixins.api import SuggestionMixin
|
||||||
from ..hands import IsOrgAdminOrAppUser
|
from ..hands import IsOrgAdminOrAppUser
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
from ..models import Application
|
from ..models import Application
|
||||||
|
|
||||||
|
|
||||||
__all__ = ['ApplicationViewSet']
|
__all__ = ['ApplicationViewSet']
|
||||||
|
|
||||||
|
|
||||||
class ApplicationViewSet(OrgBulkModelViewSet):
|
class ApplicationViewSet(SuggestionMixin, OrgBulkModelViewSet):
|
||||||
model = Application
|
model = Application
|
||||||
filterset_fields = ('name', 'type', 'category')
|
filterset_fields = {
|
||||||
search_fields = filterset_fields
|
'name': ['exact'],
|
||||||
|
'category': ['exact'],
|
||||||
|
'type': ['exact', 'in'],
|
||||||
|
}
|
||||||
|
search_fields = ('name', 'type', 'category')
|
||||||
permission_classes = (IsOrgAdminOrAppUser,)
|
permission_classes = (IsOrgAdminOrAppUser,)
|
||||||
serializer_class = serializers.ApplicationSerializer
|
serializer_classes = {
|
||||||
|
'default': serializers.AppSerializer,
|
||||||
|
'get_tree': TreeNodeSerializer,
|
||||||
|
'suggestion': serializers.MiniAppSerializer
|
||||||
|
}
|
||||||
|
|
||||||
|
@action(methods=['GET'], detail=False, url_path='tree')
|
||||||
|
def get_tree(self, request, *args, **kwargs):
|
||||||
|
show_count = request.query_params.get('show_count', '1') == '1'
|
||||||
|
queryset = self.filter_queryset(self.get_queryset())
|
||||||
|
tree_nodes = Application.create_tree_nodes(queryset, show_count=show_count)
|
||||||
|
serializer = self.get_serializer(tree_nodes, many=True)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
# coding: utf-8
|
|
||||||
#
|
|
||||||
|
|
||||||
from rest_framework import generics
|
|
||||||
from django.conf import settings
|
|
||||||
|
|
||||||
from ..hands import IsOrgAdminOrAppUser, IsOrgAdmin, NeedMFAVerify
|
|
||||||
from .. import serializers
|
|
||||||
from ..models import Application, ApplicationUser
|
|
||||||
from perms.models import ApplicationPermission
|
|
||||||
|
|
||||||
|
|
||||||
class ApplicationUserListApi(generics.ListAPIView):
|
|
||||||
permission_classes = (IsOrgAdmin, )
|
|
||||||
filterset_fields = ('name', 'username')
|
|
||||||
search_fields = filterset_fields
|
|
||||||
serializer_class = serializers.ApplicationUserSerializer
|
|
||||||
_application = None
|
|
||||||
|
|
||||||
@property
|
|
||||||
def application(self):
|
|
||||||
if self._application is None:
|
|
||||||
app_id = self.request.query_params.get('application_id')
|
|
||||||
if app_id:
|
|
||||||
self._application = Application.objects.get(id=app_id)
|
|
||||||
return self._application
|
|
||||||
|
|
||||||
def get_serializer_context(self):
|
|
||||||
context = super().get_serializer_context()
|
|
||||||
context.update({
|
|
||||||
'application': self.application
|
|
||||||
})
|
|
||||||
return context
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
queryset = ApplicationUser.objects.none()
|
|
||||||
if not self.application:
|
|
||||||
return queryset
|
|
||||||
system_user_ids = ApplicationPermission.objects.filter(applications=self.application)\
|
|
||||||
.values_list('system_users', flat=True)
|
|
||||||
if not system_user_ids:
|
|
||||||
return queryset
|
|
||||||
queryset = ApplicationUser.objects.filter(id__in=system_user_ids)
|
|
||||||
return queryset
|
|
||||||
|
|
||||||
|
|
||||||
class ApplicationUserAuthInfoListApi(ApplicationUserListApi):
|
|
||||||
serializer_class = serializers.ApplicationUserWithAuthInfoSerializer
|
|
||||||
http_method_names = ['get']
|
|
||||||
permission_classes = [IsOrgAdminOrAppUser]
|
|
||||||
|
|
||||||
def get_permissions(self):
|
|
||||||
if settings.SECURITY_VIEW_AUTH_NEED_MFA:
|
|
||||||
self.permission_classes = [IsOrgAdminOrAppUser, NeedMFAVerify]
|
|
||||||
return super().get_permissions()
|
|
||||||
@@ -1,89 +1,55 @@
|
|||||||
from orgs.models import Organization
|
from django.utils.translation import ugettext as _
|
||||||
|
|
||||||
|
from common.tree import TreeNode
|
||||||
|
from orgs.models import Organization
|
||||||
|
from ..models import Application
|
||||||
|
|
||||||
__all__ = ['SerializeApplicationToTreeNodeMixin']
|
__all__ = ['SerializeApplicationToTreeNodeMixin']
|
||||||
|
|
||||||
|
|
||||||
class SerializeApplicationToTreeNodeMixin:
|
class SerializeApplicationToTreeNodeMixin:
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _serialize_db(db):
|
|
||||||
return {
|
|
||||||
'id': db.id,
|
|
||||||
'name': db.name,
|
|
||||||
'title': db.name,
|
|
||||||
'pId': '',
|
|
||||||
'open': False,
|
|
||||||
'iconSkin': 'database',
|
|
||||||
'meta': {'type': 'database_app'}
|
|
||||||
}
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _serialize_remote_app(remote_app):
|
|
||||||
return {
|
|
||||||
'id': remote_app.id,
|
|
||||||
'name': remote_app.name,
|
|
||||||
'title': remote_app.name,
|
|
||||||
'pId': '',
|
|
||||||
'open': False,
|
|
||||||
'isParent': False,
|
|
||||||
'iconSkin': 'chrome',
|
|
||||||
'meta': {'type': 'remote_app'}
|
|
||||||
}
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _serialize_cloud(cloud):
|
|
||||||
return {
|
|
||||||
'id': cloud.id,
|
|
||||||
'name': cloud.name,
|
|
||||||
'title': cloud.name,
|
|
||||||
'pId': '',
|
|
||||||
'open': False,
|
|
||||||
'isParent': False,
|
|
||||||
'iconSkin': 'k8s',
|
|
||||||
'meta': {'type': 'k8s_app'}
|
|
||||||
}
|
|
||||||
|
|
||||||
def _serialize_application(self, application):
|
|
||||||
method_name = f'_serialize_{application.category}'
|
|
||||||
data = getattr(self, method_name)(application)
|
|
||||||
data.update({
|
|
||||||
'pId': application.org.id,
|
|
||||||
'org_name': application.org_name
|
|
||||||
})
|
|
||||||
return data
|
|
||||||
|
|
||||||
def serialize_applications(self, applications):
|
|
||||||
data = [self._serialize_application(application) for application in applications]
|
|
||||||
return data
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _serialize_organization(org):
|
|
||||||
return {
|
|
||||||
'id': org.id,
|
|
||||||
'name': org.name,
|
|
||||||
'title': org.name,
|
|
||||||
'pId': '',
|
|
||||||
'open': True,
|
|
||||||
'isParent': True,
|
|
||||||
'meta': {
|
|
||||||
'type': 'node'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def serialize_organizations(self, organizations):
|
|
||||||
data = [self._serialize_organization(org) for org in organizations]
|
|
||||||
return data
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def filter_organizations(applications):
|
def filter_organizations(applications):
|
||||||
organization_ids = set(applications.values_list('org_id', flat=True))
|
organization_ids = set(applications.values_list('org_id', flat=True))
|
||||||
organizations = [Organization.get_instance(org_id) for org_id in organization_ids]
|
organizations = [Organization.get_instance(org_id) for org_id in organization_ids]
|
||||||
|
organizations.sort(key=lambda x: x.name)
|
||||||
return organizations
|
return organizations
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_root_node():
|
||||||
|
name = _('My applications')
|
||||||
|
node = TreeNode(**{
|
||||||
|
'id': 'applications',
|
||||||
|
'name': name,
|
||||||
|
'title': name,
|
||||||
|
'pId': '',
|
||||||
|
'open': True,
|
||||||
|
'isParent': True,
|
||||||
|
'meta': {
|
||||||
|
'type': 'root'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return node
|
||||||
|
|
||||||
def serialize_applications_with_org(self, applications):
|
def serialize_applications_with_org(self, applications):
|
||||||
|
if not applications:
|
||||||
|
return []
|
||||||
|
root_node = self.create_root_node()
|
||||||
|
tree_nodes = [root_node]
|
||||||
organizations = self.filter_organizations(applications)
|
organizations = self.filter_organizations(applications)
|
||||||
data_organizations = self.serialize_organizations(organizations)
|
|
||||||
data_applications = self.serialize_applications(applications)
|
for i, org in enumerate(organizations):
|
||||||
data = data_organizations + data_applications
|
# 组织节点
|
||||||
return data
|
org_node = org.as_tree_node(pid=root_node.id)
|
||||||
|
tree_nodes.append(org_node)
|
||||||
|
org_applications = applications.filter(org_id=org.id)
|
||||||
|
count = org_applications.count()
|
||||||
|
org_node.name += '({})'.format(count)
|
||||||
|
|
||||||
|
# 各应用节点
|
||||||
|
apps_nodes = Application.create_tree_nodes(
|
||||||
|
queryset=org_applications, root_node=org_node,
|
||||||
|
show_empty=False
|
||||||
|
)
|
||||||
|
tree_nodes += apps_nodes
|
||||||
|
return tree_nodes
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
# coding: utf-8
|
# coding: utf-8
|
||||||
#
|
#
|
||||||
|
|
||||||
from django.db.models import TextChoices
|
from django.db.models import TextChoices
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
|
|
||||||
class ApplicationCategoryChoices(TextChoices):
|
class AppCategory(TextChoices):
|
||||||
db = 'db', _('Database')
|
db = 'db', _('Database')
|
||||||
remote_app = 'remote_app', _('Remote app')
|
remote_app = 'remote_app', _('Remote app')
|
||||||
cloud = 'cloud', 'Cloud'
|
cloud = 'cloud', 'Cloud'
|
||||||
@@ -15,12 +14,13 @@ class ApplicationCategoryChoices(TextChoices):
|
|||||||
return dict(cls.choices).get(category, '')
|
return dict(cls.choices).get(category, '')
|
||||||
|
|
||||||
|
|
||||||
class ApplicationTypeChoices(TextChoices):
|
class AppType(TextChoices):
|
||||||
# db category
|
# db category
|
||||||
mysql = 'mysql', 'MySQL'
|
mysql = 'mysql', 'MySQL'
|
||||||
oracle = 'oracle', 'Oracle'
|
oracle = 'oracle', 'Oracle'
|
||||||
pgsql = 'postgresql', 'PostgreSQL'
|
pgsql = 'postgresql', 'PostgreSQL'
|
||||||
mariadb = 'mariadb', 'MariaDB'
|
mariadb = 'mariadb', 'MariaDB'
|
||||||
|
sqlserver = 'sqlserver', 'SQLServer'
|
||||||
|
|
||||||
# remote-app category
|
# remote-app category
|
||||||
chrome = 'chrome', 'Chrome'
|
chrome = 'chrome', 'Chrome'
|
||||||
@@ -31,19 +31,38 @@ class ApplicationTypeChoices(TextChoices):
|
|||||||
# cloud category
|
# cloud category
|
||||||
k8s = 'k8s', 'Kubernetes'
|
k8s = 'k8s', 'Kubernetes'
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def category_types_mapper(cls):
|
||||||
|
return {
|
||||||
|
AppCategory.db: [cls.mysql, cls.oracle, cls.pgsql, cls.mariadb, cls.sqlserver],
|
||||||
|
AppCategory.remote_app: [cls.chrome, cls.mysql_workbench, cls.vmware_client, cls.custom],
|
||||||
|
AppCategory.cloud: [cls.k8s]
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def type_category_mapper(cls):
|
||||||
|
mapper = {}
|
||||||
|
for category, tps in cls.category_types_mapper().items():
|
||||||
|
for tp in tps:
|
||||||
|
mapper[tp] = category
|
||||||
|
return mapper
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_label(cls, tp):
|
def get_label(cls, tp):
|
||||||
return dict(cls.choices).get(tp, '')
|
return dict(cls.choices).get(tp, '')
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def db_types(cls):
|
def db_types(cls):
|
||||||
return [cls.mysql.value, cls.oracle.value, cls.pgsql.value, cls.mariadb.value]
|
return [tp.value for tp in cls.category_types_mapper()[AppCategory.db]]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def remote_app_types(cls):
|
def remote_app_types(cls):
|
||||||
return [cls.chrome.value, cls.mysql_workbench.value, cls.vmware_client.value, cls.custom.value]
|
return [tp.value for tp in cls.category_types_mapper()[AppCategory.remote_app]]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def cloud_types(cls):
|
def cloud_types(cls):
|
||||||
return [cls.k8s.value]
|
return [tp.value for tp in cls.category_types_mapper()[AppCategory.cloud]]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# Generated by Django 3.1.12 on 2021-08-26 09:07
|
||||||
|
|
||||||
|
import assets.models.base
|
||||||
|
import common.fields.model
|
||||||
|
from django.conf import settings
|
||||||
|
import django.core.validators
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
import simple_history.models
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
('assets', '0076_delete_assetuser'),
|
||||||
|
('applications', '0009_applicationuser'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='HistoricalAccount',
|
||||||
|
fields=[
|
||||||
|
('org_id', models.CharField(blank=True, db_index=True, default='', max_length=36, verbose_name='Organization')),
|
||||||
|
('id', models.UUIDField(db_index=True, default=uuid.uuid4)),
|
||||||
|
('name', models.CharField(max_length=128, verbose_name='Name')),
|
||||||
|
('username', models.CharField(blank=True, db_index=True, max_length=128, validators=[django.core.validators.RegexValidator('^[0-9a-zA-Z_@\\-\\.]*$', 'Special char not allowed')], verbose_name='Username')),
|
||||||
|
('password', common.fields.model.EncryptCharField(blank=True, max_length=256, null=True, verbose_name='Password')),
|
||||||
|
('private_key', common.fields.model.EncryptTextField(blank=True, null=True, verbose_name='SSH private key')),
|
||||||
|
('public_key', common.fields.model.EncryptTextField(blank=True, null=True, verbose_name='SSH public key')),
|
||||||
|
('comment', models.TextField(blank=True, verbose_name='Comment')),
|
||||||
|
('date_created', models.DateTimeField(blank=True, editable=False, verbose_name='Date created')),
|
||||||
|
('date_updated', models.DateTimeField(blank=True, editable=False, verbose_name='Date updated')),
|
||||||
|
('created_by', models.CharField(max_length=128, null=True, verbose_name='Created by')),
|
||||||
|
('version', models.IntegerField(default=1, verbose_name='Version')),
|
||||||
|
('history_id', models.AutoField(primary_key=True, serialize=False)),
|
||||||
|
('history_date', models.DateTimeField()),
|
||||||
|
('history_change_reason', models.CharField(max_length=100, null=True)),
|
||||||
|
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
|
||||||
|
('app', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='applications.application', verbose_name='Database')),
|
||||||
|
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
|
||||||
|
('systemuser', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='assets.systemuser', verbose_name='System user')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'historical Account',
|
||||||
|
'ordering': ('-history_date', '-history_id'),
|
||||||
|
'get_latest_by': 'history_date',
|
||||||
|
},
|
||||||
|
bases=(simple_history.models.HistoricalChanges, models.Model),
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='Account',
|
||||||
|
fields=[
|
||||||
|
('org_id', models.CharField(blank=True, db_index=True, default='', max_length=36, verbose_name='Organization')),
|
||||||
|
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
|
||||||
|
('name', models.CharField(max_length=128, verbose_name='Name')),
|
||||||
|
('username', models.CharField(blank=True, db_index=True, max_length=128, validators=[django.core.validators.RegexValidator('^[0-9a-zA-Z_@\\-\\.]*$', 'Special char not allowed')], verbose_name='Username')),
|
||||||
|
('password', common.fields.model.EncryptCharField(blank=True, max_length=256, null=True, verbose_name='Password')),
|
||||||
|
('private_key', common.fields.model.EncryptTextField(blank=True, null=True, verbose_name='SSH private key')),
|
||||||
|
('public_key', common.fields.model.EncryptTextField(blank=True, null=True, verbose_name='SSH public key')),
|
||||||
|
('comment', models.TextField(blank=True, verbose_name='Comment')),
|
||||||
|
('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date created')),
|
||||||
|
('date_updated', models.DateTimeField(auto_now=True, verbose_name='Date updated')),
|
||||||
|
('created_by', models.CharField(max_length=128, null=True, verbose_name='Created by')),
|
||||||
|
('version', models.IntegerField(default=1, verbose_name='Version')),
|
||||||
|
('app', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='applications.application', verbose_name='Database')),
|
||||||
|
('systemuser', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='assets.systemuser', verbose_name='System user')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Account',
|
||||||
|
'unique_together': {('username', 'app', 'systemuser')},
|
||||||
|
},
|
||||||
|
bases=(models.Model, assets.models.base.AuthMixin),
|
||||||
|
),
|
||||||
|
]
|
||||||
40
apps/applications/migrations/0011_auto_20210826_1759.py
Normal file
40
apps/applications/migrations/0011_auto_20210826_1759.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
# Generated by Django 3.1.12 on 2021-08-26 09:59
|
||||||
|
|
||||||
|
from django.db import migrations, transaction
|
||||||
|
from django.db.models import F
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_app_account(apps, schema_editor):
|
||||||
|
db_alias = schema_editor.connection.alias
|
||||||
|
app_perm_model = apps.get_model("perms", "ApplicationPermission")
|
||||||
|
app_account_model = apps.get_model("applications", 'Account')
|
||||||
|
|
||||||
|
queryset = app_perm_model.objects \
|
||||||
|
.exclude(system_users__isnull=True) \
|
||||||
|
.exclude(applications__isnull=True) \
|
||||||
|
.annotate(systemuser=F('system_users')) \
|
||||||
|
.annotate(app=F('applications')) \
|
||||||
|
.values('app', 'systemuser', 'org_id')
|
||||||
|
|
||||||
|
accounts = []
|
||||||
|
for p in queryset:
|
||||||
|
if not p['app']:
|
||||||
|
continue
|
||||||
|
account = app_account_model(
|
||||||
|
app_id=p['app'], systemuser_id=p['systemuser'],
|
||||||
|
version=1, org_id=p['org_id']
|
||||||
|
)
|
||||||
|
accounts.append(account)
|
||||||
|
|
||||||
|
app_account_model.objects.using(db_alias).bulk_create(accounts, ignore_conflicts=True)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('applications', '0010_appaccount_historicalappaccount'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(migrate_app_account)
|
||||||
|
]
|
||||||
23
apps/applications/migrations/0012_auto_20211014_2209.py
Normal file
23
apps/applications/migrations/0012_auto_20211014_2209.py
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
# Generated by Django 3.1.13 on 2021-10-14 14:09
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('applications', '0011_auto_20210826_1759'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='account',
|
||||||
|
name='username',
|
||||||
|
field=models.CharField(blank=True, db_index=True, max_length=128, verbose_name='Username'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='historicalaccount',
|
||||||
|
name='username',
|
||||||
|
field=models.CharField(blank=True, db_index=True, max_length=128, verbose_name='Username'),
|
||||||
|
),
|
||||||
|
]
|
||||||
17
apps/applications/migrations/0013_auto_20211026_1711.py
Normal file
17
apps/applications/migrations/0013_auto_20211026_1711.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Generated by Django 3.1.13 on 2021-10-26 09:11
|
||||||
|
|
||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('applications', '0012_auto_20211014_2209'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterModelOptions(
|
||||||
|
name='application',
|
||||||
|
options={'ordering': ('name',), 'verbose_name': 'Application'},
|
||||||
|
),
|
||||||
|
]
|
||||||
18
apps/applications/migrations/0014_auto_20211105_1605.py
Normal file
18
apps/applications/migrations/0014_auto_20211105_1605.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Generated by Django 3.1.12 on 2021-11-05 08:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('applications', '0013_auto_20211026_1711'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='application',
|
||||||
|
name='type',
|
||||||
|
field=models.CharField(choices=[('mysql', 'MySQL'), ('oracle', 'Oracle'), ('postgresql', 'PostgreSQL'), ('mariadb', 'MariaDB'), ('sqlserver', 'SQLServer'), ('chrome', 'Chrome'), ('mysql_workbench', 'MySQL Workbench'), ('vmware_client', 'vSphere Client'), ('custom', 'Custom'), ('k8s', 'Kubernetes')], max_length=16, verbose_name='Type'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1 +1,2 @@
|
|||||||
from .application import *
|
from .application import *
|
||||||
|
from .account import *
|
||||||
|
|||||||
88
apps/applications/models/account.py
Normal file
88
apps/applications/models/account.py
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
from django.db import models
|
||||||
|
from simple_history.models import HistoricalRecords
|
||||||
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
|
from common.utils import lazyproperty
|
||||||
|
from assets.models.base import BaseUser
|
||||||
|
|
||||||
|
|
||||||
|
class Account(BaseUser):
|
||||||
|
app = models.ForeignKey('applications.Application', on_delete=models.CASCADE, null=True, verbose_name=_('Database'))
|
||||||
|
systemuser = models.ForeignKey('assets.SystemUser', on_delete=models.CASCADE, null=True, verbose_name=_("System user"))
|
||||||
|
version = models.IntegerField(default=1, verbose_name=_('Version'))
|
||||||
|
history = HistoricalRecords()
|
||||||
|
|
||||||
|
auth_attrs = ['username', 'password', 'private_key', 'public_key']
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = _('Account')
|
||||||
|
unique_together = [('username', 'app', 'systemuser')]
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.auth_snapshot = {}
|
||||||
|
|
||||||
|
def get_or_systemuser_attr(self, attr):
|
||||||
|
val = getattr(self, attr, None)
|
||||||
|
if val:
|
||||||
|
return val
|
||||||
|
if self.systemuser:
|
||||||
|
return getattr(self.systemuser, attr, '')
|
||||||
|
return ''
|
||||||
|
|
||||||
|
def load_auth(self):
|
||||||
|
for attr in self.auth_attrs:
|
||||||
|
value = self.get_or_systemuser_attr(attr)
|
||||||
|
self.auth_snapshot[attr] = [getattr(self, attr), value]
|
||||||
|
setattr(self, attr, value)
|
||||||
|
|
||||||
|
def unload_auth(self):
|
||||||
|
if not self.systemuser:
|
||||||
|
return
|
||||||
|
|
||||||
|
for attr, values in self.auth_snapshot.items():
|
||||||
|
origin_value, loaded_value = values
|
||||||
|
current_value = getattr(self, attr, '')
|
||||||
|
if current_value == loaded_value:
|
||||||
|
setattr(self, attr, origin_value)
|
||||||
|
|
||||||
|
def save(self, *args, **kwargs):
|
||||||
|
self.unload_auth()
|
||||||
|
instance = super().save(*args, **kwargs)
|
||||||
|
self.load_auth()
|
||||||
|
return instance
|
||||||
|
|
||||||
|
@lazyproperty
|
||||||
|
def category(self):
|
||||||
|
return self.app.category
|
||||||
|
|
||||||
|
@lazyproperty
|
||||||
|
def type(self):
|
||||||
|
return self.app.type
|
||||||
|
|
||||||
|
@lazyproperty
|
||||||
|
def app_display(self):
|
||||||
|
return self.systemuser.name
|
||||||
|
|
||||||
|
@property
|
||||||
|
def username_display(self):
|
||||||
|
return self.get_or_systemuser_attr('username') or ''
|
||||||
|
|
||||||
|
@lazyproperty
|
||||||
|
def systemuser_display(self):
|
||||||
|
if not self.systemuser:
|
||||||
|
return ''
|
||||||
|
return str(self.systemuser)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def smart_name(self):
|
||||||
|
username = self.username_display
|
||||||
|
|
||||||
|
if self.app:
|
||||||
|
app = str(self.app)
|
||||||
|
else:
|
||||||
|
app = '*'
|
||||||
|
return '{}@{}'.format(username, app)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.smart_name
|
||||||
@@ -1,19 +1,174 @@
|
|||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from orgs.mixins.models import OrgModelMixin
|
from orgs.mixins.models import OrgModelMixin
|
||||||
from common.mixins import CommonModelMixin
|
from common.mixins import CommonModelMixin
|
||||||
|
from common.tree import TreeNode
|
||||||
from assets.models import Asset, SystemUser
|
from assets.models import Asset, SystemUser
|
||||||
from .. import const
|
from .. import const
|
||||||
|
|
||||||
|
|
||||||
class Application(CommonModelMixin, OrgModelMixin):
|
class ApplicationTreeNodeMixin:
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
type: str
|
||||||
|
category: str
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create_choice_node(cls, c, id_, pid, tp, opened=False, counts=None,
|
||||||
|
show_empty=True, show_count=True):
|
||||||
|
count = counts.get(c.value, 0)
|
||||||
|
if count == 0 and not show_empty:
|
||||||
|
return None
|
||||||
|
label = c.label
|
||||||
|
if count is not None and show_count:
|
||||||
|
label = '{} ({})'.format(label, count)
|
||||||
|
data = {
|
||||||
|
'id': id_,
|
||||||
|
'name': label,
|
||||||
|
'title': label,
|
||||||
|
'pId': pid,
|
||||||
|
'isParent': bool(count),
|
||||||
|
'open': opened,
|
||||||
|
'iconSkin': '',
|
||||||
|
'meta': {
|
||||||
|
'type': tp,
|
||||||
|
'data': {
|
||||||
|
'name': c.name,
|
||||||
|
'value': c.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return TreeNode(**data)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create_root_tree_node(cls, queryset, show_count=True):
|
||||||
|
count = queryset.count() if show_count else None
|
||||||
|
root_id = 'applications'
|
||||||
|
root_name = _('Applications')
|
||||||
|
if count is not None and show_count:
|
||||||
|
root_name = '{} ({})'.format(root_name, count)
|
||||||
|
node = TreeNode(**{
|
||||||
|
'id': root_id,
|
||||||
|
'name': root_name,
|
||||||
|
'title': root_name,
|
||||||
|
'pId': '',
|
||||||
|
'isParent': True,
|
||||||
|
'open': True,
|
||||||
|
'iconSkin': '',
|
||||||
|
'meta': {
|
||||||
|
'type': 'applications_root',
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return node
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create_category_tree_nodes(cls, root_node, counts=None, show_empty=True, show_count=True):
|
||||||
|
nodes = []
|
||||||
|
categories = const.AppType.category_types_mapper().keys()
|
||||||
|
for category in categories:
|
||||||
|
i = root_node.id + '_' + category.value
|
||||||
|
node = cls.create_choice_node(
|
||||||
|
category, i, pid=root_node.id, tp='category',
|
||||||
|
counts=counts, opened=False, show_empty=show_empty,
|
||||||
|
show_count=show_count
|
||||||
|
)
|
||||||
|
if not node:
|
||||||
|
continue
|
||||||
|
nodes.append(node)
|
||||||
|
return nodes
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create_types_tree_nodes(cls, root_node, counts, show_empty=True, show_count=True):
|
||||||
|
nodes = []
|
||||||
|
type_category_mapper = const.AppType.type_category_mapper()
|
||||||
|
for tp in const.AppType.type_category_mapper().keys():
|
||||||
|
category = type_category_mapper.get(tp)
|
||||||
|
pid = root_node.id + '_' + category.value
|
||||||
|
i = root_node.id + '_' + tp.value
|
||||||
|
node = cls.create_choice_node(
|
||||||
|
tp, i, pid, tp='type', counts=counts, opened=False,
|
||||||
|
show_empty=show_empty, show_count=show_count
|
||||||
|
)
|
||||||
|
if not node:
|
||||||
|
continue
|
||||||
|
nodes.append(node)
|
||||||
|
return nodes
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_tree_node_counts(queryset):
|
||||||
|
counts = defaultdict(int)
|
||||||
|
values = queryset.values_list('type', 'category')
|
||||||
|
for i in values:
|
||||||
|
tp = i[0]
|
||||||
|
category = i[1]
|
||||||
|
counts[tp] += 1
|
||||||
|
counts[category] += 1
|
||||||
|
return counts
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create_tree_nodes(cls, queryset, root_node=None, show_empty=True, show_count=True):
|
||||||
|
counts = cls.get_tree_node_counts(queryset)
|
||||||
|
tree_nodes = []
|
||||||
|
|
||||||
|
# 根节点有可能是组织名称
|
||||||
|
if root_node is None:
|
||||||
|
root_node = cls.create_root_tree_node(queryset, show_count=show_count)
|
||||||
|
tree_nodes.append(root_node)
|
||||||
|
|
||||||
|
# 类别的节点
|
||||||
|
tree_nodes += cls.create_category_tree_nodes(
|
||||||
|
root_node, counts, show_empty=show_empty,
|
||||||
|
show_count=show_count
|
||||||
|
)
|
||||||
|
|
||||||
|
# 类型的节点
|
||||||
|
tree_nodes += cls.create_types_tree_nodes(
|
||||||
|
root_node, counts, show_empty=show_empty,
|
||||||
|
show_count=show_count
|
||||||
|
)
|
||||||
|
|
||||||
|
# 应用的节点
|
||||||
|
for app in queryset:
|
||||||
|
pid = root_node.id + '_' + app.type
|
||||||
|
tree_nodes.append(app.as_tree_node(pid))
|
||||||
|
return tree_nodes
|
||||||
|
|
||||||
|
def as_tree_node(self, pid):
|
||||||
|
icon_skin_category_mapper = {
|
||||||
|
'remote_app': 'chrome',
|
||||||
|
'db': 'database',
|
||||||
|
'cloud': 'cloud'
|
||||||
|
}
|
||||||
|
icon_skin = icon_skin_category_mapper.get(self.category, 'file')
|
||||||
|
node = TreeNode(**{
|
||||||
|
'id': str(self.id),
|
||||||
|
'name': self.name,
|
||||||
|
'title': self.name,
|
||||||
|
'pId': pid,
|
||||||
|
'isParent': False,
|
||||||
|
'open': False,
|
||||||
|
'iconSkin': icon_skin,
|
||||||
|
'meta': {
|
||||||
|
'type': 'application',
|
||||||
|
'data': {
|
||||||
|
'category': self.category,
|
||||||
|
'type': self.type,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return node
|
||||||
|
|
||||||
|
|
||||||
|
class Application(CommonModelMixin, OrgModelMixin, ApplicationTreeNodeMixin):
|
||||||
name = models.CharField(max_length=128, verbose_name=_('Name'))
|
name = models.CharField(max_length=128, verbose_name=_('Name'))
|
||||||
category = models.CharField(
|
category = models.CharField(
|
||||||
max_length=16, choices=const.ApplicationCategoryChoices.choices, verbose_name=_('Category')
|
max_length=16, choices=const.AppCategory.choices, verbose_name=_('Category')
|
||||||
)
|
)
|
||||||
type = models.CharField(
|
type = models.CharField(
|
||||||
max_length=16, choices=const.ApplicationTypeChoices.choices, verbose_name=_('Type')
|
max_length=16, choices=const.AppType.choices, verbose_name=_('Type')
|
||||||
)
|
)
|
||||||
domain = models.ForeignKey(
|
domain = models.ForeignKey(
|
||||||
'assets.Domain', null=True, blank=True, related_name='applications',
|
'assets.Domain', null=True, blank=True, related_name='applications',
|
||||||
@@ -25,6 +180,7 @@ class Application(CommonModelMixin, OrgModelMixin):
|
|||||||
)
|
)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
verbose_name = _('Application')
|
||||||
unique_together = [('org_id', 'name')]
|
unique_together = [('org_id', 'name')]
|
||||||
ordering = ('name',)
|
ordering = ('name',)
|
||||||
|
|
||||||
@@ -35,7 +191,7 @@ class Application(CommonModelMixin, OrgModelMixin):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def category_remote_app(self):
|
def category_remote_app(self):
|
||||||
return self.category == const.ApplicationCategoryChoices.remote_app.value
|
return self.category == const.AppCategory.remote_app.value
|
||||||
|
|
||||||
def get_rdp_remote_app_setting(self):
|
def get_rdp_remote_app_setting(self):
|
||||||
from applications.serializers.attrs import get_serializer_class_by_application_type
|
from applications.serializers.attrs import get_serializer_class_by_application_type
|
||||||
|
|||||||
@@ -3,19 +3,24 @@
|
|||||||
|
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
||||||
|
from assets.serializers.base import AuthSerializerMixin
|
||||||
from common.drf.serializers import MethodSerializer
|
from common.drf.serializers import MethodSerializer
|
||||||
from .attrs import category_serializer_classes_mapping, type_serializer_classes_mapping
|
from .attrs import (
|
||||||
from assets.serializers import SystemUserSerializer
|
category_serializer_classes_mapping,
|
||||||
|
type_serializer_classes_mapping
|
||||||
|
)
|
||||||
from .. import models
|
from .. import models
|
||||||
|
from .. import const
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'ApplicationSerializer', 'ApplicationSerializerMixin',
|
'AppSerializer', 'MiniAppSerializer', 'AppSerializerMixin',
|
||||||
'ApplicationUserSerializer', 'ApplicationUserWithAuthInfoSerializer'
|
'AppAccountSerializer', 'AppAccountSecretSerializer'
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class ApplicationSerializerMixin(serializers.Serializer):
|
class AppSerializerMixin(serializers.Serializer):
|
||||||
attrs = MethodSerializer()
|
attrs = MethodSerializer()
|
||||||
|
|
||||||
def get_attrs_serializer(self):
|
def get_attrs_serializer(self):
|
||||||
@@ -43,18 +48,23 @@ class ApplicationSerializerMixin(serializers.Serializer):
|
|||||||
serializer = serializer_class
|
serializer = serializer_class
|
||||||
return serializer
|
return serializer
|
||||||
|
|
||||||
|
def create(self, validated_data):
|
||||||
|
return super().create(validated_data)
|
||||||
|
|
||||||
class ApplicationSerializer(ApplicationSerializerMixin, BulkOrgResourceModelSerializer):
|
def update(self, instance, validated_data):
|
||||||
category_display = serializers.ReadOnlyField(source='get_category_display', label=_('Category(Display)'))
|
return super().update(instance, validated_data)
|
||||||
type_display = serializers.ReadOnlyField(source='get_type_display', label=_('Type(Dispaly)'))
|
|
||||||
|
|
||||||
|
class AppSerializer(AppSerializerMixin, BulkOrgResourceModelSerializer):
|
||||||
|
category_display = serializers.ReadOnlyField(source='get_category_display', label=_('Category display'))
|
||||||
|
type_display = serializers.ReadOnlyField(source='get_type_display', label=_('Type display'))
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = models.Application
|
model = models.Application
|
||||||
fields_mini = ['id', 'name']
|
fields_mini = ['id', 'name']
|
||||||
fields_small = fields_mini + [
|
fields_small = fields_mini + [
|
||||||
'category', 'category_display', 'type', 'type_display', 'attrs',
|
'category', 'category_display', 'type', 'type_display',
|
||||||
'date_created', 'date_updated',
|
'attrs', 'date_created', 'date_updated', 'created_by', 'comment'
|
||||||
'created_by', 'comment'
|
|
||||||
]
|
]
|
||||||
fields_fk = ['domain']
|
fields_fk = ['domain']
|
||||||
fields = fields_small + fields_fk
|
fields = fields_small + fields_fk
|
||||||
@@ -68,41 +78,63 @@ class ApplicationSerializer(ApplicationSerializerMixin, BulkOrgResourceModelSeri
|
|||||||
return _attrs
|
return _attrs
|
||||||
|
|
||||||
|
|
||||||
class ApplicationUserSerializer(SystemUserSerializer):
|
class MiniAppSerializer(serializers.ModelSerializer):
|
||||||
application_name = serializers.SerializerMethodField(label=_('Application name'))
|
class Meta:
|
||||||
application_category = serializers.SerializerMethodField(label=_('Application category'))
|
model = models.Application
|
||||||
application_type = serializers.SerializerMethodField(label=_('Application type'))
|
fields = AppSerializer.Meta.fields_mini
|
||||||
|
|
||||||
class Meta(SystemUserSerializer.Meta):
|
|
||||||
model = models.ApplicationUser
|
class AppAccountSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
||||||
fields_mini = [
|
category = serializers.ChoiceField(label=_('Category'), choices=const.AppCategory.choices, read_only=True)
|
||||||
'id', 'application_name', 'application_category', 'application_type', 'name', 'username'
|
category_display = serializers.SerializerMethodField(label=_('Category display'))
|
||||||
|
type = serializers.ChoiceField(label=_('Type'), choices=const.AppType.choices, read_only=True)
|
||||||
|
type_display = serializers.SerializerMethodField(label=_('Type display'))
|
||||||
|
|
||||||
|
category_mapper = dict(const.AppCategory.choices)
|
||||||
|
type_mapper = dict(const.AppType.choices)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = models.Account
|
||||||
|
fields_mini = ['id', 'username', 'version']
|
||||||
|
fields_write_only = ['password', 'private_key']
|
||||||
|
fields_fk = ['systemuser', 'systemuser_display', 'app', 'app_display']
|
||||||
|
fields = fields_mini + fields_fk + fields_write_only + [
|
||||||
|
'type', 'type_display', 'category', 'category_display',
|
||||||
]
|
]
|
||||||
fields_small = fields_mini + [
|
|
||||||
'protocol', 'login_mode', 'login_mode_display', 'priority',
|
|
||||||
"username_same_with_user", 'comment',
|
|
||||||
]
|
|
||||||
fields = fields_small
|
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'login_mode_display': {'label': _('Login mode display')},
|
'username': {'default': '', 'required': False},
|
||||||
'created_by': {'read_only': True},
|
'password': {'write_only': True},
|
||||||
|
'app_display': {'label': _('Application display')},
|
||||||
|
'systemuser_display': {'label': _('System User')}
|
||||||
|
}
|
||||||
|
use_model_bulk_create = True
|
||||||
|
model_bulk_create_kwargs = {
|
||||||
|
'ignore_conflicts': True
|
||||||
}
|
}
|
||||||
|
|
||||||
@property
|
def get_category_display(self, obj):
|
||||||
def application(self):
|
return self.category_mapper.get(obj.category)
|
||||||
return self.context['application']
|
|
||||||
|
|
||||||
def get_application_name(self, obj):
|
def get_type_display(self, obj):
|
||||||
return self.application.name
|
return self.type_mapper.get(obj.type)
|
||||||
|
|
||||||
def get_application_category(self, obj):
|
@classmethod
|
||||||
return self.application.get_category_display()
|
def setup_eager_loading(cls, queryset):
|
||||||
|
""" Perform necessary eager loading of data. """
|
||||||
|
queryset = queryset.prefetch_related('systemuser', 'app')
|
||||||
|
return queryset
|
||||||
|
|
||||||
def get_application_type(self, obj):
|
def to_representation(self, instance):
|
||||||
return self.application.get_type_display()
|
instance.load_auth()
|
||||||
|
return super().to_representation(instance)
|
||||||
|
|
||||||
|
|
||||||
class ApplicationUserWithAuthInfoSerializer(ApplicationUserSerializer):
|
class AppAccountSecretSerializer(AppAccountSerializer):
|
||||||
|
class Meta(AppAccountSerializer.Meta):
|
||||||
class Meta(ApplicationUserSerializer.Meta):
|
extra_kwargs = {
|
||||||
fields = ApplicationUserSerializer.Meta.fields + ['password', 'token']
|
'password': {'write_only': False},
|
||||||
|
'private_key': {'write_only': False},
|
||||||
|
'public_key': {'write_only': False},
|
||||||
|
'app_display': {'label': _('Application display')},
|
||||||
|
'systemuser_display': {'label': _('System User')}
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from rest_framework import serializers
|
|||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from django.core.exceptions import ObjectDoesNotExist
|
from django.core.exceptions import ObjectDoesNotExist
|
||||||
|
|
||||||
from common.utils import get_logger, is_uuid
|
from common.utils import get_logger, is_uuid, get_object_or_none
|
||||||
from assets.models import Asset
|
from assets.models import Asset
|
||||||
|
|
||||||
logger = get_logger(__file__)
|
logger = get_logger(__file__)
|
||||||
@@ -14,28 +14,37 @@ logger = get_logger(__file__)
|
|||||||
__all__ = ['RemoteAppSerializer']
|
__all__ = ['RemoteAppSerializer']
|
||||||
|
|
||||||
|
|
||||||
class CharPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
|
class ExistAssetPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
|
||||||
|
|
||||||
def to_internal_value(self, data):
|
def to_internal_value(self, data):
|
||||||
instance = super().to_internal_value(data)
|
instance = super().to_internal_value(data)
|
||||||
return str(instance.id)
|
return str(instance.id)
|
||||||
|
|
||||||
def to_representation(self, value):
|
def to_representation(self, _id):
|
||||||
# value is instance.id
|
# _id 是 instance.id
|
||||||
if self.pk_field is not None:
|
if self.pk_field is not None:
|
||||||
return self.pk_field.to_representation(value)
|
return self.pk_field.to_representation(_id)
|
||||||
return value
|
# 解决删除资产后,远程应用更新页面会显示资产ID的问题
|
||||||
|
asset = get_object_or_none(Asset, id=_id)
|
||||||
|
if not asset:
|
||||||
|
return None
|
||||||
|
return _id
|
||||||
|
|
||||||
|
|
||||||
class RemoteAppSerializer(serializers.Serializer):
|
class RemoteAppSerializer(serializers.Serializer):
|
||||||
asset_info = serializers.SerializerMethodField()
|
asset_info = serializers.SerializerMethodField()
|
||||||
asset = CharPrimaryKeyRelatedField(
|
asset = ExistAssetPrimaryKeyRelatedField(
|
||||||
queryset=Asset.objects, required=False, label=_("Asset"), allow_null=True
|
queryset=Asset.objects, required=True, label=_("Asset"), allow_null=True
|
||||||
)
|
)
|
||||||
path = serializers.CharField(
|
path = serializers.CharField(
|
||||||
max_length=128, label=_('Application path'), allow_null=True
|
max_length=128, label=_('Application path'), allow_null=True
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def validate_asset(self, asset):
|
||||||
|
if not asset:
|
||||||
|
raise serializers.ValidationError(_('This field is required.'))
|
||||||
|
return asset
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_asset_info(obj):
|
def get_asset_info(obj):
|
||||||
asset_id = obj.get('asset')
|
asset_id = obj.get('asset')
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from .mysql import *
|
|||||||
from .mariadb import *
|
from .mariadb import *
|
||||||
from .oracle import *
|
from .oracle import *
|
||||||
from .pgsql import *
|
from .pgsql import *
|
||||||
|
from .sqlserver import *
|
||||||
|
|
||||||
from .chrome import *
|
from .chrome import *
|
||||||
from .mysql_workbench import *
|
from .mysql_workbench import *
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from rest_framework import serializers
|
||||||
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
|
from ..application_category import DBSerializer
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ['SQLServerSerializer']
|
||||||
|
|
||||||
|
|
||||||
|
class SQLServerSerializer(DBSerializer):
|
||||||
|
port = serializers.IntegerField(default=1433, label=_('Port'), allow_null=True)
|
||||||
|
|
||||||
@@ -14,9 +14,9 @@ __all__ = [
|
|||||||
# ---------------------------------------------------
|
# ---------------------------------------------------
|
||||||
|
|
||||||
category_serializer_classes_mapping = {
|
category_serializer_classes_mapping = {
|
||||||
const.ApplicationCategoryChoices.db.value: application_category.DBSerializer,
|
const.AppCategory.db.value: application_category.DBSerializer,
|
||||||
const.ApplicationCategoryChoices.remote_app.value: application_category.RemoteAppSerializer,
|
const.AppCategory.remote_app.value: application_category.RemoteAppSerializer,
|
||||||
const.ApplicationCategoryChoices.cloud.value: application_category.CloudSerializer,
|
const.AppCategory.cloud.value: application_category.CloudSerializer,
|
||||||
}
|
}
|
||||||
|
|
||||||
# define `attrs` field `type serializers mapping`
|
# define `attrs` field `type serializers mapping`
|
||||||
@@ -24,17 +24,18 @@ category_serializer_classes_mapping = {
|
|||||||
|
|
||||||
type_serializer_classes_mapping = {
|
type_serializer_classes_mapping = {
|
||||||
# db
|
# db
|
||||||
const.ApplicationTypeChoices.mysql.value: application_type.MySQLSerializer,
|
const.AppType.mysql.value: application_type.MySQLSerializer,
|
||||||
const.ApplicationTypeChoices.mariadb.value: application_type.MariaDBSerializer,
|
const.AppType.mariadb.value: application_type.MariaDBSerializer,
|
||||||
const.ApplicationTypeChoices.oracle.value: application_type.OracleSerializer,
|
const.AppType.oracle.value: application_type.OracleSerializer,
|
||||||
const.ApplicationTypeChoices.pgsql.value: application_type.PostgreSerializer,
|
const.AppType.pgsql.value: application_type.PostgreSerializer,
|
||||||
|
const.AppType.sqlserver.value: application_type.SQLServerSerializer,
|
||||||
# remote-app
|
# remote-app
|
||||||
const.ApplicationTypeChoices.chrome.value: application_type.ChromeSerializer,
|
const.AppType.chrome.value: application_type.ChromeSerializer,
|
||||||
const.ApplicationTypeChoices.mysql_workbench.value: application_type.MySQLWorkbenchSerializer,
|
const.AppType.mysql_workbench.value: application_type.MySQLWorkbenchSerializer,
|
||||||
const.ApplicationTypeChoices.vmware_client.value: application_type.VMwareClientSerializer,
|
const.AppType.vmware_client.value: application_type.VMwareClientSerializer,
|
||||||
const.ApplicationTypeChoices.custom.value: application_type.CustomSerializer,
|
const.AppType.custom.value: application_type.CustomSerializer,
|
||||||
# cloud
|
# cloud
|
||||||
const.ApplicationTypeChoices.k8s.value: application_type.K8SSerializer
|
const.AppType.k8s.value: application_type.K8SSerializer
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -10,12 +10,14 @@ app_name = 'applications'
|
|||||||
|
|
||||||
router = BulkRouter()
|
router = BulkRouter()
|
||||||
router.register(r'applications', api.ApplicationViewSet, 'application')
|
router.register(r'applications', api.ApplicationViewSet, 'application')
|
||||||
|
router.register(r'accounts', api.ApplicationAccountViewSet, 'application-account')
|
||||||
|
router.register(r'account-secrets', api.ApplicationAccountSecretViewSet, 'application-account-secret')
|
||||||
|
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('remote-apps/<uuid:pk>/connection-info/', api.RemoteAppConnectionInfoApi.as_view(), name='remote-app-connection-info'),
|
path('remote-apps/<uuid:pk>/connection-info/', api.RemoteAppConnectionInfoApi.as_view(), name='remote-app-connection-info'),
|
||||||
path('application-users/', api.ApplicationUserListApi.as_view(), name='application-user'),
|
# path('accounts/', api.ApplicationAccountViewSet.as_view(), name='application-account'),
|
||||||
path('application-user-auth-infos/', api.ApplicationUserAuthInfoListApi.as_view(), name='application-user-auth-info')
|
# path('account-secrets/', api.ApplicationAccountSecretViewSet.as_view(), name='application-account-secret')
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
from django.db.models import F, Q
|
from django.db.models import F, Q
|
||||||
from django.conf import settings
|
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from django_filters import rest_framework as filters
|
from django_filters import rest_framework as filters
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from django.shortcuts import get_object_or_404
|
||||||
from rest_framework.generics import CreateAPIView
|
from rest_framework.generics import CreateAPIView
|
||||||
|
|
||||||
from orgs.mixins.api import OrgBulkModelViewSet
|
from orgs.mixins.api import OrgBulkModelViewSet
|
||||||
from common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, NeedMFAVerify
|
from common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, NeedMFAVerify
|
||||||
from common.drf.filters import BaseFilterSet
|
from common.drf.filters import BaseFilterSet
|
||||||
from ..tasks.account_connectivity import test_accounts_connectivity_manual
|
from ..tasks.account_connectivity import test_accounts_connectivity_manual
|
||||||
from ..models import AuthBook
|
from ..models import AuthBook, Node
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
|
|
||||||
__all__ = ['AccountViewSet', 'AccountSecretsViewSet', 'AccountTaskCreateAPI']
|
__all__ = ['AccountViewSet', 'AccountSecretsViewSet', 'AccountTaskCreateAPI']
|
||||||
@@ -19,11 +19,13 @@ class AccountFilterSet(BaseFilterSet):
|
|||||||
username = filters.CharFilter(method='do_nothing')
|
username = filters.CharFilter(method='do_nothing')
|
||||||
ip = filters.CharFilter(field_name='ip', lookup_expr='exact')
|
ip = filters.CharFilter(field_name='ip', lookup_expr='exact')
|
||||||
hostname = filters.CharFilter(field_name='hostname', lookup_expr='exact')
|
hostname = filters.CharFilter(field_name='hostname', lookup_expr='exact')
|
||||||
|
node = filters.CharFilter(method='do_nothing')
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def qs(self):
|
def qs(self):
|
||||||
qs = super().qs
|
qs = super().qs
|
||||||
qs = self.filter_username(qs)
|
qs = self.filter_username(qs)
|
||||||
|
qs = self.filter_node(qs)
|
||||||
return qs
|
return qs
|
||||||
|
|
||||||
def filter_username(self, qs):
|
def filter_username(self, qs):
|
||||||
@@ -33,6 +35,16 @@ class AccountFilterSet(BaseFilterSet):
|
|||||||
qs = qs.filter(Q(username=username) | Q(systemuser__username=username)).distinct()
|
qs = qs.filter(Q(username=username) | Q(systemuser__username=username)).distinct()
|
||||||
return qs
|
return qs
|
||||||
|
|
||||||
|
def filter_node(self, qs):
|
||||||
|
node_id = self.get_query_param('node')
|
||||||
|
if not node_id:
|
||||||
|
return qs
|
||||||
|
node = get_object_or_404(Node, pk=node_id)
|
||||||
|
node_ids = node.get_all_children(with_self=True).values_list('id', flat=True)
|
||||||
|
node_ids = list(node_ids)
|
||||||
|
qs = qs.filter(asset__nodes__in=node_ids)
|
||||||
|
return qs
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = AuthBook
|
model = AuthBook
|
||||||
fields = [
|
fields = [
|
||||||
@@ -74,11 +86,6 @@ class AccountSecretsViewSet(AccountViewSet):
|
|||||||
permission_classes = (IsOrgAdmin, NeedMFAVerify)
|
permission_classes = (IsOrgAdmin, NeedMFAVerify)
|
||||||
http_method_names = ['get']
|
http_method_names = ['get']
|
||||||
|
|
||||||
def get_permissions(self):
|
|
||||||
if not settings.SECURITY_VIEW_AUTH_NEED_MFA:
|
|
||||||
self.permission_classes = [IsOrgAdminOrAppUser]
|
|
||||||
return super().get_permissions()
|
|
||||||
|
|
||||||
|
|
||||||
class AccountTaskCreateAPI(CreateAPIView):
|
class AccountTaskCreateAPI(CreateAPIView):
|
||||||
permission_classes = (IsOrgAdminOrAppUser,)
|
permission_classes = (IsOrgAdminOrAppUser,)
|
||||||
@@ -103,4 +110,5 @@ class AccountTaskCreateAPI(CreateAPIView):
|
|||||||
def get_exception_handler(self):
|
def get_exception_handler(self):
|
||||||
def handler(e, context):
|
def handler(e, context):
|
||||||
return Response({"error": str(e)}, status=400)
|
return Response({"error": str(e)}, status=400)
|
||||||
|
|
||||||
return handler
|
return handler
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ class AdminUserViewSet(OrgBulkModelViewSet):
|
|||||||
search_fields = filterset_fields
|
search_fields = filterset_fields
|
||||||
serializer_class = serializers.AdminUserSerializer
|
serializer_class = serializers.AdminUserSerializer
|
||||||
permission_classes = (IsOrgAdmin,)
|
permission_classes = (IsOrgAdmin,)
|
||||||
|
ordering_fields = ('name',)
|
||||||
|
ordering = ('name', )
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
queryset = super().get_queryset().filter(type=SystemUser.Type.admin)
|
queryset = super().get_queryset().filter(type=SystemUser.Type.admin)
|
||||||
|
|||||||
@@ -2,30 +2,40 @@
|
|||||||
#
|
#
|
||||||
from assets.api import FilterAssetByNodeMixin
|
from assets.api import FilterAssetByNodeMixin
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
from rest_framework.generics import RetrieveAPIView
|
from rest_framework.generics import RetrieveAPIView, ListAPIView
|
||||||
from django.shortcuts import get_object_or_404
|
from django.shortcuts import get_object_or_404
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
from common.utils import get_logger, get_object_or_none
|
from common.utils import get_logger, get_object_or_none
|
||||||
from common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, IsSuperUser
|
from common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, IsSuperUser
|
||||||
|
from common.mixins.api import SuggestionMixin
|
||||||
|
from users.models import User, UserGroup
|
||||||
|
from users.serializers import UserSerializer, UserGroupSerializer
|
||||||
|
from users.filters import UserFilter
|
||||||
|
from perms.models import AssetPermission
|
||||||
|
from perms.serializers import AssetPermissionSerializer
|
||||||
|
from perms.filters import AssetPermissionFilter
|
||||||
from orgs.mixins.api import OrgBulkModelViewSet
|
from orgs.mixins.api import OrgBulkModelViewSet
|
||||||
from orgs.mixins import generics
|
from orgs.mixins import generics
|
||||||
from ..models import Asset, Node, Platform
|
from ..models import Asset, Node, Platform
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
from ..tasks import (
|
from ..tasks import (
|
||||||
update_assets_hardware_info_manual, test_assets_connectivity_manual
|
update_assets_hardware_info_manual, test_assets_connectivity_manual,
|
||||||
|
test_system_users_connectivity_a_asset, push_system_users_a_asset
|
||||||
)
|
)
|
||||||
from ..filters import FilterAssetByNodeFilterBackend, LabelFilterBackend, IpInFilterBackend
|
from ..filters import FilterAssetByNodeFilterBackend, LabelFilterBackend, IpInFilterBackend
|
||||||
|
|
||||||
|
|
||||||
logger = get_logger(__file__)
|
logger = get_logger(__file__)
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'AssetViewSet', 'AssetPlatformRetrieveApi',
|
'AssetViewSet', 'AssetPlatformRetrieveApi',
|
||||||
'AssetGatewayListApi', 'AssetPlatformViewSet',
|
'AssetGatewayListApi', 'AssetPlatformViewSet',
|
||||||
'AssetTaskCreateApi', 'AssetsTaskCreateApi',
|
'AssetTaskCreateApi', 'AssetsTaskCreateApi',
|
||||||
|
'AssetPermUserListApi', 'AssetPermUserPermissionsListApi',
|
||||||
|
'AssetPermUserGroupListApi', 'AssetPermUserGroupPermissionsListApi',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class AssetViewSet(FilterAssetByNodeMixin, OrgBulkModelViewSet):
|
class AssetViewSet(SuggestionMixin, FilterAssetByNodeMixin, OrgBulkModelViewSet):
|
||||||
"""
|
"""
|
||||||
API endpoint that allows Asset to be viewed or edited.
|
API endpoint that allows Asset to be viewed or edited.
|
||||||
"""
|
"""
|
||||||
@@ -40,8 +50,10 @@ class AssetViewSet(FilterAssetByNodeMixin, OrgBulkModelViewSet):
|
|||||||
}
|
}
|
||||||
search_fields = ("hostname", "ip")
|
search_fields = ("hostname", "ip")
|
||||||
ordering_fields = ("hostname", "ip", "port", "cpu_cores")
|
ordering_fields = ("hostname", "ip", "port", "cpu_cores")
|
||||||
|
ordering = ('hostname', )
|
||||||
serializer_classes = {
|
serializer_classes = {
|
||||||
'default': serializers.AssetSerializer,
|
'default': serializers.AssetSerializer,
|
||||||
|
'suggestion': serializers.MiniAssetSerializer
|
||||||
}
|
}
|
||||||
permission_classes = (IsOrgAdminOrAppUser,)
|
permission_classes = (IsOrgAdminOrAppUser,)
|
||||||
extra_filter_backends = [FilterAssetByNodeFilterBackend, LabelFilterBackend, IpInFilterBackend]
|
extra_filter_backends = [FilterAssetByNodeFilterBackend, LabelFilterBackend, IpInFilterBackend]
|
||||||
@@ -94,21 +106,27 @@ class AssetPlatformViewSet(ModelViewSet):
|
|||||||
|
|
||||||
|
|
||||||
class AssetsTaskMixin:
|
class AssetsTaskMixin:
|
||||||
|
|
||||||
def perform_assets_task(self, serializer):
|
def perform_assets_task(self, serializer):
|
||||||
data = serializer.validated_data
|
data = serializer.validated_data
|
||||||
assets = data['assets']
|
|
||||||
action = data['action']
|
action = data['action']
|
||||||
|
assets = data.get('assets', [])
|
||||||
if action == "refresh":
|
if action == "refresh":
|
||||||
task = update_assets_hardware_info_manual.delay(assets)
|
task = update_assets_hardware_info_manual.delay(assets)
|
||||||
else:
|
else:
|
||||||
|
# action == 'test':
|
||||||
task = test_assets_connectivity_manual.delay(assets)
|
task = test_assets_connectivity_manual.delay(assets)
|
||||||
|
return task
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
task = self.perform_assets_task(serializer)
|
||||||
|
self.set_task_to_serializer_data(serializer, task)
|
||||||
|
|
||||||
|
def set_task_to_serializer_data(self, serializer, task):
|
||||||
data = getattr(serializer, '_data', {})
|
data = getattr(serializer, '_data', {})
|
||||||
data["task"] = task.id
|
data["task"] = task.id
|
||||||
setattr(serializer, '_data', data)
|
setattr(serializer, '_data', data)
|
||||||
|
|
||||||
def perform_create(self, serializer):
|
|
||||||
self.perform_assets_task(serializer)
|
|
||||||
|
|
||||||
|
|
||||||
class AssetTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView):
|
class AssetTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView):
|
||||||
model = Asset
|
model = Asset
|
||||||
@@ -117,13 +135,37 @@ class AssetTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView):
|
|||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
def create(self, request, *args, **kwargs):
|
||||||
pk = self.kwargs.get('pk')
|
pk = self.kwargs.get('pk')
|
||||||
|
request.data['asset'] = pk
|
||||||
request.data['assets'] = [pk]
|
request.data['assets'] = [pk]
|
||||||
return super().create(request, *args, **kwargs)
|
return super().create(request, *args, **kwargs)
|
||||||
|
|
||||||
|
def perform_asset_task(self, serializer):
|
||||||
|
data = serializer.validated_data
|
||||||
|
action = data['action']
|
||||||
|
if action not in ['push_system_user', 'test_system_user']:
|
||||||
|
return
|
||||||
|
asset = data['asset']
|
||||||
|
system_users = data.get('system_users')
|
||||||
|
if not system_users:
|
||||||
|
system_users = asset.get_all_system_users()
|
||||||
|
if action == 'push_system_user':
|
||||||
|
task = push_system_users_a_asset.delay(system_users, asset=asset)
|
||||||
|
elif action == 'test_system_user':
|
||||||
|
task = test_system_users_connectivity_a_asset.delay(system_users, asset=asset)
|
||||||
|
else:
|
||||||
|
task = None
|
||||||
|
return task
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
task = self.perform_asset_task(serializer)
|
||||||
|
if not task:
|
||||||
|
task = self.perform_assets_task(serializer)
|
||||||
|
self.set_task_to_serializer_data(serializer, task)
|
||||||
|
|
||||||
|
|
||||||
class AssetsTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView):
|
class AssetsTaskCreateApi(AssetsTaskMixin, generics.CreateAPIView):
|
||||||
model = Asset
|
model = Asset
|
||||||
serializer_class = serializers.AssetTaskSerializer
|
serializer_class = serializers.AssetsTaskSerializer
|
||||||
permission_classes = (IsOrgAdmin,)
|
permission_classes = (IsOrgAdmin,)
|
||||||
|
|
||||||
|
|
||||||
@@ -138,3 +180,102 @@ class AssetGatewayListApi(generics.ListAPIView):
|
|||||||
return []
|
return []
|
||||||
queryset = asset.domain.gateways.filter(protocol='ssh')
|
queryset = asset.domain.gateways.filter(protocol='ssh')
|
||||||
return queryset
|
return queryset
|
||||||
|
|
||||||
|
|
||||||
|
class BaseAssetPermUserOrUserGroupListApi(ListAPIView):
|
||||||
|
permission_classes = (IsOrgAdmin,)
|
||||||
|
|
||||||
|
def get_object(self):
|
||||||
|
asset_id = self.kwargs.get('pk')
|
||||||
|
asset = get_object_or_404(Asset, pk=asset_id)
|
||||||
|
return asset
|
||||||
|
|
||||||
|
def get_asset_related_perms(self):
|
||||||
|
asset = self.get_object()
|
||||||
|
nodes = asset.get_all_nodes(flat=True)
|
||||||
|
perms = AssetPermission.objects.filter(Q(assets=asset) | Q(nodes__in=nodes))
|
||||||
|
return perms
|
||||||
|
|
||||||
|
|
||||||
|
class AssetPermUserListApi(BaseAssetPermUserOrUserGroupListApi):
|
||||||
|
filterset_class = UserFilter
|
||||||
|
search_fields = ('username', 'email', 'name', 'id', 'source', 'role')
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
perms = self.get_asset_related_perms()
|
||||||
|
users = User.objects.filter(
|
||||||
|
Q(assetpermissions__in=perms) | Q(groups__assetpermissions__in=perms)
|
||||||
|
).distinct()
|
||||||
|
return users
|
||||||
|
|
||||||
|
|
||||||
|
class AssetPermUserGroupListApi(BaseAssetPermUserOrUserGroupListApi):
|
||||||
|
serializer_class = UserGroupSerializer
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
perms = self.get_asset_related_perms()
|
||||||
|
user_groups = UserGroup.objects.filter(assetpermissions__in=perms).distinct()
|
||||||
|
return user_groups
|
||||||
|
|
||||||
|
|
||||||
|
class BaseAssetPermUserOrUserGroupPermissionsListApiMixin(generics.ListAPIView):
|
||||||
|
permission_classes = (IsOrgAdmin,)
|
||||||
|
model = AssetPermission
|
||||||
|
serializer_class = AssetPermissionSerializer
|
||||||
|
filterset_class = AssetPermissionFilter
|
||||||
|
search_fields = ('name',)
|
||||||
|
|
||||||
|
def get_object(self):
|
||||||
|
asset_id = self.kwargs.get('pk')
|
||||||
|
asset = get_object_or_404(Asset, pk=asset_id)
|
||||||
|
return asset
|
||||||
|
|
||||||
|
def filter_asset_related(self, queryset):
|
||||||
|
asset = self.get_object()
|
||||||
|
nodes = asset.get_all_nodes(flat=True)
|
||||||
|
perms = queryset.filter(Q(assets=asset) | Q(nodes__in=nodes))
|
||||||
|
return perms
|
||||||
|
|
||||||
|
def filter_queryset(self, queryset):
|
||||||
|
queryset = super().filter_queryset(queryset)
|
||||||
|
queryset = self.filter_asset_related(queryset)
|
||||||
|
return queryset
|
||||||
|
|
||||||
|
|
||||||
|
class AssetPermUserPermissionsListApi(BaseAssetPermUserOrUserGroupPermissionsListApiMixin):
|
||||||
|
def filter_queryset(self, queryset):
|
||||||
|
queryset = super().filter_queryset(queryset)
|
||||||
|
queryset = self.filter_user_related(queryset)
|
||||||
|
queryset = queryset.distinct()
|
||||||
|
return queryset
|
||||||
|
|
||||||
|
def filter_user_related(self, queryset):
|
||||||
|
user = self.get_perm_user()
|
||||||
|
user_groups = user.groups.all()
|
||||||
|
perms = queryset.filter(Q(users=user) | Q(user_groups__in=user_groups))
|
||||||
|
return perms
|
||||||
|
|
||||||
|
def get_perm_user(self):
|
||||||
|
user_id = self.kwargs.get('perm_user_id')
|
||||||
|
user = get_object_or_404(User, pk=user_id)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
class AssetPermUserGroupPermissionsListApi(BaseAssetPermUserOrUserGroupPermissionsListApiMixin):
|
||||||
|
def filter_queryset(self, queryset):
|
||||||
|
queryset = super().filter_queryset(queryset)
|
||||||
|
queryset = self.filter_user_group_related(queryset)
|
||||||
|
queryset = queryset.distinct()
|
||||||
|
return queryset
|
||||||
|
|
||||||
|
def filter_user_group_related(self, queryset):
|
||||||
|
user_group = self.get_perm_user_group()
|
||||||
|
perms = queryset.filter(user_groups=user_group)
|
||||||
|
return perms
|
||||||
|
|
||||||
|
def get_perm_user_group(self):
|
||||||
|
user_group_id = self.kwargs.get('perm_user_group_id')
|
||||||
|
user_group = get_object_or_404(UserGroup, pk=user_group_id)
|
||||||
|
return user_group
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ from ..hands import IsOrgAdmin, IsAppUser
|
|||||||
from ..models import CommandFilter, CommandFilterRule
|
from ..models import CommandFilter, CommandFilterRule
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'CommandFilterViewSet', 'CommandFilterRuleViewSet', 'CommandConfirmAPI',
|
'CommandFilterViewSet', 'CommandFilterRuleViewSet', 'CommandConfirmAPI',
|
||||||
'CommandConfirmStatusAPI'
|
'CommandConfirmStatusAPI'
|
||||||
@@ -30,7 +29,7 @@ class CommandFilterViewSet(OrgBulkModelViewSet):
|
|||||||
|
|
||||||
class CommandFilterRuleViewSet(OrgBulkModelViewSet):
|
class CommandFilterRuleViewSet(OrgBulkModelViewSet):
|
||||||
model = CommandFilterRule
|
model = CommandFilterRule
|
||||||
filterset_fields = ("content",)
|
filterset_fields = ('content',)
|
||||||
search_fields = filterset_fields
|
search_fields = filterset_fields
|
||||||
permission_classes = (IsOrgAdmin,)
|
permission_classes = (IsOrgAdmin,)
|
||||||
serializer_class = serializers.CommandFilterRuleSerializer
|
serializer_class = serializers.CommandFilterRuleSerializer
|
||||||
@@ -73,11 +72,12 @@ class CommandConfirmAPI(CreateAPIView):
|
|||||||
external=True, api_to_ui=True
|
external=True, api_to_ui=True
|
||||||
)
|
)
|
||||||
ticket_detail_url = '{url}?type={type}'.format(url=ticket_detail_url, type=ticket.type)
|
ticket_detail_url = '{url}?type={type}'.format(url=ticket_detail_url, type=ticket.type)
|
||||||
|
ticket_assignees = ticket.current_node.first().ticket_assignees.all()
|
||||||
return {
|
return {
|
||||||
'check_confirm_status': {'method': 'GET', 'url': confirm_status_url},
|
'check_confirm_status': {'method': 'GET', 'url': confirm_status_url},
|
||||||
'close_confirm': {'method': 'DELETE', 'url': confirm_status_url},
|
'close_confirm': {'method': 'DELETE', 'url': confirm_status_url},
|
||||||
'ticket_detail_url': ticket_detail_url,
|
'ticket_detail_url': ticket_detail_url,
|
||||||
'reviewers': [str(user) for user in ticket.assignees.all()]
|
'reviewers': [str(ticket_assignee.assignee) for ticket_assignee in ticket_assignees]
|
||||||
}
|
}
|
||||||
|
|
||||||
@lazyproperty
|
@lazyproperty
|
||||||
@@ -89,4 +89,3 @@ class CommandConfirmAPI(CreateAPIView):
|
|||||||
|
|
||||||
class CommandConfirmStatusAPI(GenericTicketStatusRetrieveCloseAPI):
|
class CommandConfirmStatusAPI(GenericTicketStatusRetrieveCloseAPI):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ class DomainViewSet(OrgBulkModelViewSet):
|
|||||||
search_fields = filterset_fields
|
search_fields = filterset_fields
|
||||||
permission_classes = (IsOrgAdminOrAppUser,)
|
permission_classes = (IsOrgAdminOrAppUser,)
|
||||||
serializer_class = serializers.DomainSerializer
|
serializer_class = serializers.DomainSerializer
|
||||||
|
ordering_fields = ('name',)
|
||||||
|
ordering = ('name', )
|
||||||
|
|
||||||
def get_serializer_class(self):
|
def get_serializer_class(self):
|
||||||
if self.request.query_params.get('gateway'):
|
if self.request.query_params.get('gateway'):
|
||||||
@@ -33,7 +35,7 @@ class GatewayViewSet(OrgBulkModelViewSet):
|
|||||||
model = Gateway
|
model = Gateway
|
||||||
filterset_fields = ("domain__name", "name", "username", "ip", "domain")
|
filterset_fields = ("domain__name", "name", "username", "ip", "domain")
|
||||||
search_fields = ("domain__name", "name", "username", "ip")
|
search_fields = ("domain__name", "name", "username", "ip")
|
||||||
permission_classes = (IsOrgAdmin,)
|
permission_classes = (IsOrgAdminOrAppUser,)
|
||||||
serializer_class = serializers.GatewaySerializer
|
serializer_class = serializers.GatewaySerializer
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ class SerializeToTreeNodeMixin:
|
|||||||
'isParent': True,
|
'isParent': True,
|
||||||
'open': node.is_org_root(),
|
'open': node.is_org_root(),
|
||||||
'meta': {
|
'meta': {
|
||||||
'node': {
|
'data': {
|
||||||
"id": node.id,
|
"id": node.id,
|
||||||
"key": node.key,
|
"key": node.key,
|
||||||
"value": node.value,
|
"value": node.value,
|
||||||
@@ -65,7 +65,7 @@ class SerializeToTreeNodeMixin:
|
|||||||
'chkDisabled': not asset.is_active,
|
'chkDisabled': not asset.is_active,
|
||||||
'meta': {
|
'meta': {
|
||||||
'type': 'asset',
|
'type': 'asset',
|
||||||
'asset': {
|
'data': {
|
||||||
'id': asset.id,
|
'id': asset.id,
|
||||||
'hostname': asset.hostname,
|
'hostname': asset.hostname,
|
||||||
'ip': asset.ip,
|
'ip': asset.ip,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from django.db.models.signals import m2m_changed
|
|||||||
from common.const.http import POST
|
from common.const.http import POST
|
||||||
from common.exceptions import SomeoneIsDoingThis
|
from common.exceptions import SomeoneIsDoingThis
|
||||||
from common.const.signals import PRE_REMOVE, POST_REMOVE
|
from common.const.signals import PRE_REMOVE, POST_REMOVE
|
||||||
|
from common.mixins.api import SuggestionMixin
|
||||||
from assets.models import Asset
|
from assets.models import Asset
|
||||||
from common.utils import get_logger, get_object_or_none
|
from common.utils import get_logger, get_object_or_none
|
||||||
from common.tree import TreeNodeSerializer
|
from common.tree import TreeNodeSerializer
|
||||||
@@ -41,7 +42,7 @@ __all__ = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class NodeViewSet(OrgModelViewSet):
|
class NodeViewSet(SuggestionMixin, OrgModelViewSet):
|
||||||
model = Node
|
model = Node
|
||||||
filterset_fields = ('value', 'key', 'id')
|
filterset_fields = ('value', 'key', 'id')
|
||||||
search_fields = ('value', )
|
search_fields = ('value', )
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
# ~*~ coding: utf-8 ~*~
|
# ~*~ coding: utf-8 ~*~
|
||||||
from django.shortcuts import get_object_or_404
|
from django.shortcuts import get_object_or_404
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
from common.utils import get_logger
|
from common.utils import get_logger, get_object_or_none
|
||||||
from common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, IsValidUser
|
from common.permissions import IsOrgAdmin, IsOrgAdminOrAppUser, IsValidUser
|
||||||
from orgs.mixins.api import OrgBulkModelViewSet
|
from orgs.mixins.api import OrgBulkModelViewSet
|
||||||
from orgs.mixins import generics
|
from orgs.mixins import generics
|
||||||
|
from common.mixins.api import SuggestionMixin
|
||||||
from orgs.utils import tmp_to_root_org
|
from orgs.utils import tmp_to_root_org
|
||||||
from ..models import SystemUser, Asset
|
from rest_framework.decorators import action
|
||||||
|
from users.models import User, UserGroup
|
||||||
|
from applications.models import Application
|
||||||
|
from ..models import SystemUser, Asset, CommandFilter, CommandFilterRule
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
from ..serializers import SystemUserWithAuthInfoSerializer, SystemUserTempAuthSerializer
|
from ..serializers import SystemUserWithAuthInfoSerializer, SystemUserTempAuthSerializer
|
||||||
from ..tasks import (
|
from ..tasks import (
|
||||||
@@ -15,7 +20,6 @@ from ..tasks import (
|
|||||||
push_system_user_to_assets
|
push_system_user_to_assets
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
logger = get_logger(__file__)
|
logger = get_logger(__file__)
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'SystemUserViewSet', 'SystemUserAuthInfoApi', 'SystemUserAssetAuthInfoApi',
|
'SystemUserViewSet', 'SystemUserAuthInfoApi', 'SystemUserAssetAuthInfoApi',
|
||||||
@@ -24,7 +28,7 @@ __all__ = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class SystemUserViewSet(OrgBulkModelViewSet):
|
class SystemUserViewSet(SuggestionMixin, OrgBulkModelViewSet):
|
||||||
"""
|
"""
|
||||||
System user api set, for add,delete,update,list,retrieve resource
|
System user api set, for add,delete,update,list,retrieve resource
|
||||||
"""
|
"""
|
||||||
@@ -39,9 +43,38 @@ class SystemUserViewSet(OrgBulkModelViewSet):
|
|||||||
serializer_class = serializers.SystemUserSerializer
|
serializer_class = serializers.SystemUserSerializer
|
||||||
serializer_classes = {
|
serializer_classes = {
|
||||||
'default': serializers.SystemUserSerializer,
|
'default': serializers.SystemUserSerializer,
|
||||||
|
'suggestion': serializers.MiniSystemUserSerializer
|
||||||
}
|
}
|
||||||
|
ordering_fields = ('name', 'protocol', 'login_mode')
|
||||||
|
ordering = ('name', )
|
||||||
permission_classes = (IsOrgAdminOrAppUser,)
|
permission_classes = (IsOrgAdminOrAppUser,)
|
||||||
|
|
||||||
|
@action(methods=['get'], detail=False, url_path='su-from')
|
||||||
|
def su_from(self, request, *args, **kwargs):
|
||||||
|
""" API 获取可选的 su_from 系统用户"""
|
||||||
|
queryset = self.filter_queryset(self.get_queryset())
|
||||||
|
queryset = queryset.filter(
|
||||||
|
protocol=SystemUser.Protocol.ssh, login_mode=SystemUser.LOGIN_AUTO
|
||||||
|
)
|
||||||
|
return self.get_paginate_response_if_need(queryset)
|
||||||
|
|
||||||
|
@action(methods=['get'], detail=True, url_path='su-to')
|
||||||
|
def su_to(self, request, *args, **kwargs):
|
||||||
|
""" 获取系统用户的所有 su_to 系统用户 """
|
||||||
|
pk = kwargs.get('pk')
|
||||||
|
system_user = get_object_or_404(SystemUser, pk=pk)
|
||||||
|
queryset = system_user.su_to.all()
|
||||||
|
queryset = self.filter_queryset(queryset)
|
||||||
|
return self.get_paginate_response_if_need(queryset)
|
||||||
|
|
||||||
|
def get_paginate_response_if_need(self, queryset):
|
||||||
|
page = self.paginate_queryset(queryset)
|
||||||
|
if page is not None:
|
||||||
|
serializer = self.get_serializer(page, many=True)
|
||||||
|
return self.get_paginated_response(serializer.data)
|
||||||
|
serializer = self.get_serializer(queryset, many=True)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
|
||||||
class SystemUserAuthInfoApi(generics.RetrieveUpdateDestroyAPIView):
|
class SystemUserAuthInfoApi(generics.RetrieveUpdateDestroyAPIView):
|
||||||
"""
|
"""
|
||||||
@@ -72,7 +105,7 @@ class SystemUserTempAuthInfoApi(generics.CreateAPIView):
|
|||||||
|
|
||||||
with tmp_to_root_org():
|
with tmp_to_root_org():
|
||||||
instance = get_object_or_404(SystemUser, pk=pk)
|
instance = get_object_or_404(SystemUser, pk=pk)
|
||||||
instance.set_temp_auth(instance_id, user, data)
|
instance.set_temp_auth(instance_id, user.id, data)
|
||||||
return Response(serializer.data, status=201)
|
return Response(serializer.data, status=201)
|
||||||
|
|
||||||
|
|
||||||
@@ -89,7 +122,7 @@ class SystemUserAssetAuthInfoApi(generics.RetrieveAPIView):
|
|||||||
asset_id = self.kwargs.get('asset_id')
|
asset_id = self.kwargs.get('asset_id')
|
||||||
user_id = self.request.query_params.get("user_id")
|
user_id = self.request.query_params.get("user_id")
|
||||||
username = self.request.query_params.get("username")
|
username = self.request.query_params.get("username")
|
||||||
instance.load_asset_more_auth(asset_id=asset_id, user_id=user_id, username=username)
|
instance.load_asset_more_auth(asset_id, username, user_id)
|
||||||
return instance
|
return instance
|
||||||
|
|
||||||
|
|
||||||
@@ -105,8 +138,8 @@ class SystemUserAppAuthInfoApi(generics.RetrieveAPIView):
|
|||||||
instance = super().get_object()
|
instance = super().get_object()
|
||||||
app_id = self.kwargs.get('app_id')
|
app_id = self.kwargs.get('app_id')
|
||||||
user_id = self.request.query_params.get("user_id")
|
user_id = self.request.query_params.get("user_id")
|
||||||
if user_id:
|
username = self.request.query_params.get("username")
|
||||||
instance.load_app_more_auth(app_id, user_id)
|
instance.load_app_more_auth(app_id, username, user_id)
|
||||||
return instance
|
return instance
|
||||||
|
|
||||||
|
|
||||||
@@ -163,9 +196,42 @@ class SystemUserCommandFilterRuleListApi(generics.ListAPIView):
|
|||||||
return CommandFilterRuleSerializer
|
return CommandFilterRuleSerializer
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
pk = self.kwargs.get('pk', None)
|
user_groups = []
|
||||||
system_user = get_object_or_404(SystemUser, pk=pk)
|
user_id = self.request.query_params.get('user_id')
|
||||||
return system_user.cmd_filter_rules
|
user = get_object_or_none(User, pk=user_id)
|
||||||
|
if user:
|
||||||
|
user_groups.extend(list(user.groups.all()))
|
||||||
|
user_group_id = self.request.query_params.get('user_group_id')
|
||||||
|
user_group = get_object_or_none(UserGroup, pk=user_group_id)
|
||||||
|
if user_group:
|
||||||
|
user_groups.append(user_group)
|
||||||
|
system_user_id = self.kwargs.get('pk', None)
|
||||||
|
system_user = get_object_or_none(SystemUser, pk=system_user_id)
|
||||||
|
if not system_user:
|
||||||
|
system_user_id = self.request.query_params.get('system_user_id')
|
||||||
|
system_user = get_object_or_none(SystemUser, pk=system_user_id)
|
||||||
|
asset_id = self.request.query_params.get('asset_id')
|
||||||
|
asset = get_object_or_none(Asset, pk=asset_id)
|
||||||
|
application_id = self.request.query_params.get('application_id')
|
||||||
|
application = get_object_or_none(Application, pk=application_id)
|
||||||
|
q = Q()
|
||||||
|
if user:
|
||||||
|
q |= Q(users=user)
|
||||||
|
if user_groups:
|
||||||
|
q |= Q(user_groups__in=set(user_groups))
|
||||||
|
if system_user:
|
||||||
|
q |= Q(system_users=system_user)
|
||||||
|
if asset:
|
||||||
|
q |= Q(assets=asset)
|
||||||
|
if application:
|
||||||
|
q |= Q(applications=application)
|
||||||
|
if q:
|
||||||
|
cmd_filters = CommandFilter.objects.filter(q).filter(is_active=True)
|
||||||
|
rule_ids = cmd_filters.values_list('rules', flat=True)
|
||||||
|
rules = CommandFilterRule.objects.filter(id__in=rule_ids)
|
||||||
|
else:
|
||||||
|
rules = CommandFilterRule.objects.none()
|
||||||
|
return rules
|
||||||
|
|
||||||
|
|
||||||
class SystemUserAssetsListView(generics.ListAPIView):
|
class SystemUserAssetsListView(generics.ListAPIView):
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
#
|
#
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from django.db.models import F, Value
|
from django.db.models import F, Value, Model
|
||||||
from django.db.models.signals import m2m_changed
|
from django.db.models.signals import m2m_changed
|
||||||
from django.db.models.functions import Concat
|
from django.db.models.functions import Concat
|
||||||
|
|
||||||
@@ -13,13 +13,15 @@ from .. import models, serializers
|
|||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'SystemUserAssetRelationViewSet', 'SystemUserNodeRelationViewSet',
|
'SystemUserAssetRelationViewSet', 'SystemUserNodeRelationViewSet',
|
||||||
'SystemUserUserRelationViewSet',
|
'SystemUserUserRelationViewSet', 'BaseRelationViewSet',
|
||||||
]
|
]
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class RelationMixin:
|
class RelationMixin:
|
||||||
|
model: Model
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
queryset = self.model.objects.all()
|
queryset = self.model.objects.all()
|
||||||
if not current_org.is_root():
|
if not current_org.is_root():
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
# Generated by Django 3.1.6 on 2021-06-04 16:46
|
# Generated by Django 3.1.6 on 2021-06-04 16:46
|
||||||
|
import uuid
|
||||||
from django.db import migrations, models, transaction
|
from django.db import migrations, models, transaction
|
||||||
import django.db.models.deletion
|
import django.db.models.deletion
|
||||||
|
from django.db import IntegrityError
|
||||||
from django.db.models import F
|
from django.db.models import F
|
||||||
|
|
||||||
|
|
||||||
@@ -15,7 +16,7 @@ def migrate_admin_user_to_system_user(apps, schema_editor):
|
|||||||
for admin_user in admin_users:
|
for admin_user in admin_users:
|
||||||
kwargs = {}
|
kwargs = {}
|
||||||
for attr in [
|
for attr in [
|
||||||
'id', 'org_id', 'username', 'password', 'private_key', 'public_key',
|
'org_id', 'username', 'password', 'private_key', 'public_key',
|
||||||
'comment', 'date_created', 'date_updated', 'created_by',
|
'comment', 'date_created', 'date_updated', 'created_by',
|
||||||
]:
|
]:
|
||||||
value = getattr(admin_user, attr)
|
value = getattr(admin_user, attr)
|
||||||
@@ -27,7 +28,16 @@ def migrate_admin_user_to_system_user(apps, schema_editor):
|
|||||||
).exists()
|
).exists()
|
||||||
if exist:
|
if exist:
|
||||||
name = admin_user.name + '_' + str(admin_user.id)[:5]
|
name = admin_user.name + '_' + str(admin_user.id)[:5]
|
||||||
|
|
||||||
|
i = admin_user.id
|
||||||
|
exist = system_user_model.objects.using(db_alias).filter(
|
||||||
|
id=i, org_id=admin_user.org_id
|
||||||
|
).exists()
|
||||||
|
if exist:
|
||||||
|
i = uuid.uuid4()
|
||||||
|
|
||||||
kwargs.update({
|
kwargs.update({
|
||||||
|
'id': i,
|
||||||
'name': name,
|
'name': name,
|
||||||
'type': 'admin',
|
'type': 'admin',
|
||||||
'protocol': 'ssh',
|
'protocol': 'ssh',
|
||||||
@@ -36,6 +46,10 @@ def migrate_admin_user_to_system_user(apps, schema_editor):
|
|||||||
|
|
||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
s = system_user_model(**kwargs)
|
s = system_user_model(**kwargs)
|
||||||
|
try:
|
||||||
|
s.save()
|
||||||
|
except IntegrityError:
|
||||||
|
s.id = None
|
||||||
s.save()
|
s.save()
|
||||||
print(" Migrate admin user to system user: {} => {}".format(admin_user.name, s.name))
|
print(" Migrate admin user to system user: {} => {}".format(admin_user.name, s.name))
|
||||||
assets = admin_user.assets.all()
|
assets = admin_user.assets.all()
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ def migrate_old_authbook_to_history(apps, schema_editor):
|
|||||||
|
|
||||||
print()
|
print()
|
||||||
while True:
|
while True:
|
||||||
authbooks = authbook_model.objects.using(db_alias).filter(is_latest=False)[:20]
|
authbooks = authbook_model.objects.using(db_alias).filter(is_latest=False)[:1000]
|
||||||
if not authbooks:
|
if not authbooks:
|
||||||
break
|
break
|
||||||
historys = []
|
historys = []
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ def migrate_system_assets_to_authbook(apps, schema_editor):
|
|||||||
system_users = system_user_model.objects.all()
|
system_users = system_user_model.objects.all()
|
||||||
for s in system_users:
|
for s in system_users:
|
||||||
while True:
|
while True:
|
||||||
systemuser_asset_relations = system_user_asset_model.objects.filter(systemuser=s)[:20]
|
systemuser_asset_relations = system_user_asset_model.objects.filter(systemuser=s)[:1000]
|
||||||
if not systemuser_asset_relations:
|
if not systemuser_asset_relations:
|
||||||
break
|
break
|
||||||
authbooks = []
|
authbooks = []
|
||||||
|
|||||||
24
apps/assets/migrations/0077_auto_20211012_1642.py
Normal file
24
apps/assets/migrations/0077_auto_20211012_1642.py
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Generated by Django 3.1.12 on 2021-10-12 08:42
|
||||||
|
|
||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_platform_win2016(apps, schema_editor):
|
||||||
|
platform_model = apps.get_model("assets", "Platform")
|
||||||
|
win2016 = platform_model.objects.filter(name='Windows2016').first()
|
||||||
|
if not win2016:
|
||||||
|
print("Error: Not found Windows2016 platform")
|
||||||
|
return
|
||||||
|
win2016.meta = {"security": "any"}
|
||||||
|
win2016.save()
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('assets', '0076_delete_assetuser'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(migrate_platform_win2016)
|
||||||
|
]
|
||||||
38
apps/assets/migrations/0078_auto_20211014_2209.py
Normal file
38
apps/assets/migrations/0078_auto_20211014_2209.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# Generated by Django 3.1.13 on 2021-10-14 14:09
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('assets', '0077_auto_20211012_1642'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='adminuser',
|
||||||
|
name='username',
|
||||||
|
field=models.CharField(blank=True, db_index=True, max_length=128, verbose_name='Username'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='authbook',
|
||||||
|
name='username',
|
||||||
|
field=models.CharField(blank=True, db_index=True, max_length=128, verbose_name='Username'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='gateway',
|
||||||
|
name='username',
|
||||||
|
field=models.CharField(blank=True, db_index=True, max_length=128, verbose_name='Username'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='historicalauthbook',
|
||||||
|
name='username',
|
||||||
|
field=models.CharField(blank=True, db_index=True, max_length=128, verbose_name='Username'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='systemuser',
|
||||||
|
name='username',
|
||||||
|
field=models.CharField(blank=True, db_index=True, max_length=128, verbose_name='Username'),
|
||||||
|
),
|
||||||
|
]
|
||||||
33
apps/assets/migrations/0079_auto_20211102_1922.py
Normal file
33
apps/assets/migrations/0079_auto_20211102_1922.py
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
# Generated by Django 3.1.12 on 2021-11-02 11:22
|
||||||
|
|
||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
def create_internal_platform(apps, schema_editor):
|
||||||
|
model = apps.get_model("assets", "Platform")
|
||||||
|
db_alias = schema_editor.connection.alias
|
||||||
|
type_platforms = (
|
||||||
|
('Windows-RDP', 'Windows', {'security': 'rdp'}),
|
||||||
|
('Windows-TLS', 'Windows', {'security': 'tls'}),
|
||||||
|
)
|
||||||
|
for name, base, meta in type_platforms:
|
||||||
|
defaults = {'name': name, 'base': base, 'meta': meta, 'internal': True}
|
||||||
|
model.objects.using(db_alias).update_or_create(
|
||||||
|
name=name, defaults=defaults
|
||||||
|
)
|
||||||
|
|
||||||
|
win2016 = model.objects.filter(name='Windows2016').first()
|
||||||
|
if win2016:
|
||||||
|
win2016.internal = False
|
||||||
|
win2016.save(update_fields=['internal'])
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('assets', '0078_auto_20211014_2209'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(create_internal_platform)
|
||||||
|
]
|
||||||
24
apps/assets/migrations/0080_auto_20211104_1347.py
Normal file
24
apps/assets/migrations/0080_auto_20211104_1347.py
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Generated by Django 3.1.13 on 2021-11-04 05:47
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('assets', '0079_auto_20211102_1922'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='systemuser',
|
||||||
|
name='su_enabled',
|
||||||
|
field=models.BooleanField(default=False, verbose_name='User switch'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='systemuser',
|
||||||
|
name='su_from',
|
||||||
|
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='su_to', to='assets.systemuser', verbose_name='Switch from'),
|
||||||
|
),
|
||||||
|
]
|
||||||
18
apps/assets/migrations/0081_auto_20211105_1605.py
Normal file
18
apps/assets/migrations/0081_auto_20211105_1605.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Generated by Django 3.1.12 on 2021-11-05 08:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('assets', '0080_auto_20211104_1347'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='systemuser',
|
||||||
|
name='protocol',
|
||||||
|
field=models.CharField(choices=[('ssh', 'SSH'), ('rdp', 'RDP'), ('telnet', 'Telnet'), ('vnc', 'VNC'), ('mysql', 'MySQL'), ('oracle', 'Oracle'), ('mariadb', 'MariaDB'), ('postgresql', 'PostgreSQL'), ('sqlserver', 'SQLServer'), ('k8s', 'K8S')], default='ssh', max_length=16, verbose_name='Protocol'),
|
||||||
|
),
|
||||||
|
]
|
||||||
74
apps/assets/migrations/0082_auto_20211209_1440.py
Normal file
74
apps/assets/migrations/0082_auto_20211209_1440.py
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
# Generated by Django 3.1.13 on 2021-12-09 06:40
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_system_users_cmd_filters(apps, schema_editor):
|
||||||
|
system_user_model = apps.get_model("assets", "SystemUser")
|
||||||
|
cmd_filter_model = apps.get_model("assets", "CommandFilter")
|
||||||
|
su_through = system_user_model.cmd_filters.through
|
||||||
|
cf_through = cmd_filter_model.system_users.through
|
||||||
|
|
||||||
|
su_relation_objects = su_through.objects.all()
|
||||||
|
cf_relation_objects = [
|
||||||
|
cf_through(**{
|
||||||
|
'id': su_relation.id,
|
||||||
|
'systemuser_id': su_relation.systemuser_id,
|
||||||
|
'commandfilter_id': su_relation.commandfilter_id
|
||||||
|
})
|
||||||
|
for su_relation in su_relation_objects
|
||||||
|
]
|
||||||
|
cf_through.objects.bulk_create(cf_relation_objects)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('applications', '0014_auto_20211105_1605'),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
('assets', '0081_auto_20211105_1605'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='commandfilter',
|
||||||
|
name='applications',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to='applications.Application', verbose_name='Application'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='commandfilter',
|
||||||
|
name='assets',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to='assets.Asset', verbose_name='Asset'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='commandfilter',
|
||||||
|
name='system_users',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='cmd_filters_pre', to='assets.SystemUser', verbose_name='System user'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='commandfilter',
|
||||||
|
name='users',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to=settings.AUTH_USER_MODEL, verbose_name='User'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='commandfilter',
|
||||||
|
name='user_groups',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to='users.UserGroup', verbose_name='User group'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='systemuser',
|
||||||
|
name='cmd_filters',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='system_users_bak', to='assets.CommandFilter', verbose_name='Command filter'),
|
||||||
|
),
|
||||||
|
migrations.RunPython(migrate_system_users_cmd_filters),
|
||||||
|
migrations.RemoveField(
|
||||||
|
model_name='systemuser',
|
||||||
|
name='cmd_filters',
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='commandfilter',
|
||||||
|
name='system_users',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='cmd_filters', to='assets.SystemUser', verbose_name='System user'),
|
||||||
|
),
|
||||||
|
]
|
||||||
27
apps/assets/migrations/0083_auto_20211215_1436.py
Normal file
27
apps/assets/migrations/0083_auto_20211215_1436.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Generated by Django 3.1.13 on 2021-12-15 06:36
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
OLD_ACTION_ALLOW = 1
|
||||||
|
NEW_ACTION_ALLOW = 9
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_action(apps, schema_editor):
|
||||||
|
model = apps.get_model("assets", "CommandFilterRule")
|
||||||
|
model.objects.filter(action=OLD_ACTION_ALLOW).update(action=NEW_ACTION_ALLOW)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('assets', '0082_auto_20211209_1440'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(migrate_action),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='commandfilterrule',
|
||||||
|
name='action',
|
||||||
|
field=models.IntegerField(choices=[(0, 'Deny'), (9, 'Allow'), (2, 'Reconfirm')], default=0, verbose_name='Action'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -164,38 +164,7 @@ class Platform(models.Model):
|
|||||||
# ordering = ('name',)
|
# ordering = ('name',)
|
||||||
|
|
||||||
|
|
||||||
class Asset(AbsConnectivity, ProtocolsMixin, NodesRelationMixin, OrgModelMixin):
|
class AbsHardwareInfo(models.Model):
|
||||||
# Important
|
|
||||||
PLATFORM_CHOICES = (
|
|
||||||
('Linux', 'Linux'),
|
|
||||||
('Unix', 'Unix'),
|
|
||||||
('MacOS', 'MacOS'),
|
|
||||||
('BSD', 'BSD'),
|
|
||||||
('Windows', 'Windows'),
|
|
||||||
('Windows2016', 'Windows(2016)'),
|
|
||||||
('Other', 'Other'),
|
|
||||||
)
|
|
||||||
|
|
||||||
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
|
||||||
ip = models.CharField(max_length=128, verbose_name=_('IP'), db_index=True)
|
|
||||||
hostname = models.CharField(max_length=128, verbose_name=_('Hostname'))
|
|
||||||
protocol = models.CharField(max_length=128, default=ProtocolsMixin.Protocol.ssh,
|
|
||||||
choices=ProtocolsMixin.Protocol.choices,
|
|
||||||
verbose_name=_('Protocol'))
|
|
||||||
port = models.IntegerField(default=22, verbose_name=_('Port'))
|
|
||||||
protocols = models.CharField(max_length=128, default='ssh/22', blank=True, verbose_name=_("Protocols"))
|
|
||||||
platform = models.ForeignKey(Platform, default=Platform.default, on_delete=models.PROTECT, verbose_name=_("Platform"), related_name='assets')
|
|
||||||
domain = models.ForeignKey("assets.Domain", null=True, blank=True, related_name='assets', verbose_name=_("Domain"), on_delete=models.SET_NULL)
|
|
||||||
nodes = models.ManyToManyField('assets.Node', default=default_node, related_name='assets', verbose_name=_("Nodes"))
|
|
||||||
is_active = models.BooleanField(default=True, verbose_name=_('Is active'))
|
|
||||||
|
|
||||||
# Auth
|
|
||||||
admin_user = models.ForeignKey('assets.SystemUser', on_delete=models.SET_NULL, null=True, verbose_name=_("Admin user"), related_name='admin_assets')
|
|
||||||
|
|
||||||
# Some information
|
|
||||||
public_ip = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Public IP'))
|
|
||||||
number = models.CharField(max_length=32, null=True, blank=True, verbose_name=_('Asset number'))
|
|
||||||
|
|
||||||
# Collect
|
# Collect
|
||||||
vendor = models.CharField(max_length=64, null=True, blank=True, verbose_name=_('Vendor'))
|
vendor = models.CharField(max_length=64, null=True, blank=True, verbose_name=_('Vendor'))
|
||||||
model = models.CharField(max_length=54, null=True, blank=True, verbose_name=_('Model'))
|
model = models.CharField(max_length=54, null=True, blank=True, verbose_name=_('Model'))
|
||||||
@@ -214,6 +183,49 @@ class Asset(AbsConnectivity, ProtocolsMixin, NodesRelationMixin, OrgModelMixin):
|
|||||||
os_arch = models.CharField(max_length=16, blank=True, null=True, verbose_name=_('OS arch'))
|
os_arch = models.CharField(max_length=16, blank=True, null=True, verbose_name=_('OS arch'))
|
||||||
hostname_raw = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Hostname raw'))
|
hostname_raw = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Hostname raw'))
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
abstract = True
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cpu_info(self):
|
||||||
|
info = ""
|
||||||
|
if self.cpu_model:
|
||||||
|
info += self.cpu_model
|
||||||
|
if self.cpu_count and self.cpu_cores:
|
||||||
|
info += "{}*{}".format(self.cpu_count, self.cpu_cores)
|
||||||
|
return info
|
||||||
|
|
||||||
|
@property
|
||||||
|
def hardware_info(self):
|
||||||
|
if self.cpu_count:
|
||||||
|
return '{} Core {} {}'.format(
|
||||||
|
self.cpu_vcpus or self.cpu_count * self.cpu_cores,
|
||||||
|
self.memory, self.disk_total
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
class Asset(AbsConnectivity, AbsHardwareInfo, ProtocolsMixin, NodesRelationMixin, OrgModelMixin):
|
||||||
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||||||
|
ip = models.CharField(max_length=128, verbose_name=_('IP'), db_index=True)
|
||||||
|
hostname = models.CharField(max_length=128, verbose_name=_('Hostname'))
|
||||||
|
protocol = models.CharField(max_length=128, default=ProtocolsMixin.Protocol.ssh,
|
||||||
|
choices=ProtocolsMixin.Protocol.choices, verbose_name=_('Protocol'))
|
||||||
|
port = models.IntegerField(default=22, verbose_name=_('Port'))
|
||||||
|
protocols = models.CharField(max_length=128, default='ssh/22', blank=True, verbose_name=_("Protocols"))
|
||||||
|
platform = models.ForeignKey(Platform, default=Platform.default, on_delete=models.PROTECT, verbose_name=_("Platform"), related_name='assets')
|
||||||
|
domain = models.ForeignKey("assets.Domain", null=True, blank=True, related_name='assets', verbose_name=_("Domain"), on_delete=models.SET_NULL)
|
||||||
|
nodes = models.ManyToManyField('assets.Node', default=default_node, related_name='assets', verbose_name=_("Nodes"))
|
||||||
|
is_active = models.BooleanField(default=True, verbose_name=_('Is active'))
|
||||||
|
|
||||||
|
# Auth
|
||||||
|
admin_user = models.ForeignKey('assets.SystemUser', on_delete=models.SET_NULL, null=True, verbose_name=_("Admin user"), related_name='admin_assets')
|
||||||
|
|
||||||
|
# Some information
|
||||||
|
public_ip = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Public IP'))
|
||||||
|
number = models.CharField(max_length=32, null=True, blank=True, verbose_name=_('Asset number'))
|
||||||
|
|
||||||
labels = models.ManyToManyField('assets.Label', blank=True, related_name='assets', verbose_name=_("Labels"))
|
labels = models.ManyToManyField('assets.Label', blank=True, related_name='assets', verbose_name=_("Labels"))
|
||||||
created_by = models.CharField(max_length=128, null=True, blank=True, verbose_name=_('Created by'))
|
created_by = models.CharField(max_length=128, null=True, blank=True, verbose_name=_('Created by'))
|
||||||
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name=_('Date created'))
|
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name=_('Date created'))
|
||||||
@@ -269,25 +281,6 @@ class Asset(AbsConnectivity, ProtocolsMixin, NodesRelationMixin, OrgModelMixin):
|
|||||||
def is_support_ansible(self):
|
def is_support_ansible(self):
|
||||||
return self.has_protocol('ssh') and self.platform_base not in ("Other",)
|
return self.has_protocol('ssh') and self.platform_base not in ("Other",)
|
||||||
|
|
||||||
@property
|
|
||||||
def cpu_info(self):
|
|
||||||
info = ""
|
|
||||||
if self.cpu_model:
|
|
||||||
info += self.cpu_model
|
|
||||||
if self.cpu_count and self.cpu_cores:
|
|
||||||
info += "{}*{}".format(self.cpu_count, self.cpu_cores)
|
|
||||||
return info
|
|
||||||
|
|
||||||
@property
|
|
||||||
def hardware_info(self):
|
|
||||||
if self.cpu_count:
|
|
||||||
return '{} Core {} {}'.format(
|
|
||||||
self.cpu_vcpus or self.cpu_count * self.cpu_cores,
|
|
||||||
self.memory, self.disk_total
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
return ''
|
|
||||||
|
|
||||||
def get_auth_info(self):
|
def get_auth_info(self):
|
||||||
if not self.admin_user:
|
if not self.admin_user:
|
||||||
return {}
|
return {}
|
||||||
@@ -306,6 +299,12 @@ class Asset(AbsConnectivity, ProtocolsMixin, NodesRelationMixin, OrgModelMixin):
|
|||||||
names.append(n.full_value)
|
names.append(n.full_value)
|
||||||
return names
|
return names
|
||||||
|
|
||||||
|
def labels_display(self):
|
||||||
|
names = []
|
||||||
|
for n in self.labels.all():
|
||||||
|
names.append(n.name + ':' + n.value)
|
||||||
|
return names
|
||||||
|
|
||||||
def as_node(self):
|
def as_node(self):
|
||||||
from .node import Node
|
from .node import Node
|
||||||
fake_node = Node()
|
fake_node = Node()
|
||||||
@@ -333,7 +332,7 @@ class Asset(AbsConnectivity, ProtocolsMixin, NodesRelationMixin, OrgModelMixin):
|
|||||||
'iconSkin': icon_skin,
|
'iconSkin': icon_skin,
|
||||||
'meta': {
|
'meta': {
|
||||||
'type': 'asset',
|
'type': 'asset',
|
||||||
'asset': {
|
'data': {
|
||||||
'id': self.id,
|
'id': self.id,
|
||||||
'hostname': self.hostname,
|
'hostname': self.hostname,
|
||||||
'ip': self.ip,
|
'ip': self.ip,
|
||||||
@@ -345,6 +344,13 @@ class Asset(AbsConnectivity, ProtocolsMixin, NodesRelationMixin, OrgModelMixin):
|
|||||||
tree_node = TreeNode(**data)
|
tree_node = TreeNode(**data)
|
||||||
return tree_node
|
return tree_node
|
||||||
|
|
||||||
|
def get_all_system_users(self):
|
||||||
|
from .user import SystemUser
|
||||||
|
system_user_ids = SystemUser.assets.through.objects.filter(asset=self)\
|
||||||
|
.values_list('systemuser_id', flat=True)
|
||||||
|
system_users = SystemUser.objects.filter(id__in=system_user_ids)
|
||||||
|
return system_users
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
unique_together = [('org_id', 'hostname')]
|
unique_together = [('org_id', 'hostname')]
|
||||||
verbose_name = _("Asset")
|
verbose_name = _("Asset")
|
||||||
|
|||||||
@@ -5,9 +5,12 @@ from django.db import models
|
|||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from simple_history.models import HistoricalRecords
|
from simple_history.models import HistoricalRecords
|
||||||
|
|
||||||
from common.utils import lazyproperty
|
from common.utils import lazyproperty, get_logger
|
||||||
from .base import BaseUser, AbsConnectivity
|
from .base import BaseUser, AbsConnectivity
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
__all__ = ['AuthBook']
|
__all__ = ['AuthBook']
|
||||||
|
|
||||||
|
|
||||||
@@ -16,7 +19,6 @@ class AuthBook(BaseUser, AbsConnectivity):
|
|||||||
systemuser = models.ForeignKey('assets.SystemUser', on_delete=models.CASCADE, null=True, verbose_name=_("System user"))
|
systemuser = models.ForeignKey('assets.SystemUser', on_delete=models.CASCADE, null=True, verbose_name=_("System user"))
|
||||||
version = models.IntegerField(default=1, verbose_name=_('Version'))
|
version = models.IntegerField(default=1, verbose_name=_('Version'))
|
||||||
history = HistoricalRecords()
|
history = HistoricalRecords()
|
||||||
_systemuser_display = ''
|
|
||||||
|
|
||||||
auth_attrs = ['username', 'password', 'private_key', 'public_key']
|
auth_attrs = ['username', 'password', 'private_key', 'public_key']
|
||||||
|
|
||||||
@@ -64,8 +66,6 @@ class AuthBook(BaseUser, AbsConnectivity):
|
|||||||
|
|
||||||
@lazyproperty
|
@lazyproperty
|
||||||
def systemuser_display(self):
|
def systemuser_display(self):
|
||||||
if self._systemuser_display:
|
|
||||||
return self._systemuser_display
|
|
||||||
if not self.systemuser:
|
if not self.systemuser:
|
||||||
return ''
|
return ''
|
||||||
return str(self.systemuser)
|
return str(self.systemuser)
|
||||||
@@ -94,7 +94,27 @@ class AuthBook(BaseUser, AbsConnectivity):
|
|||||||
i.private_key = self.private_key
|
i.private_key = self.private_key
|
||||||
i.public_key = self.public_key
|
i.public_key = self.public_key
|
||||||
i.comment = 'Update triggered by account {}'.format(self.id)
|
i.comment = 'Update triggered by account {}'.format(self.id)
|
||||||
i.save(update_fields=['password', 'private_key', 'public_key'])
|
|
||||||
|
# 不触发post_save信号
|
||||||
|
self.__class__.objects.bulk_update(matched, fields=['password', 'private_key', 'public_key'])
|
||||||
|
|
||||||
|
def remove_asset_admin_user_if_need(self):
|
||||||
|
if not self.asset or not self.systemuser:
|
||||||
|
return
|
||||||
|
if not self.systemuser.is_admin_user or self.asset.admin_user != self.systemuser:
|
||||||
|
return
|
||||||
|
self.asset.admin_user = None
|
||||||
|
self.asset.save()
|
||||||
|
logger.debug('Remove asset admin user: {} {}'.format(self.asset, self.systemuser))
|
||||||
|
|
||||||
|
def update_asset_admin_user_if_need(self):
|
||||||
|
if not self.asset or not self.systemuser:
|
||||||
|
return
|
||||||
|
if not self.systemuser.is_admin_user or self.asset.admin_user == self.systemuser:
|
||||||
|
return
|
||||||
|
self.asset.admin_user = self.systemuser
|
||||||
|
self.asset.save()
|
||||||
|
logger.debug('Update asset admin user: {} {}'.format(self.asset, self.systemuser))
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.smart_name
|
return self.smart_name
|
||||||
|
|||||||
@@ -67,7 +67,10 @@ class AuthMixin:
|
|||||||
if self.public_key:
|
if self.public_key:
|
||||||
public_key = self.public_key
|
public_key = self.public_key
|
||||||
elif self.private_key:
|
elif self.private_key:
|
||||||
|
try:
|
||||||
public_key = ssh_pubkey_gen(private_key=self.private_key, password=self.password)
|
public_key = ssh_pubkey_gen(private_key=self.private_key, password=self.password)
|
||||||
|
except IOError as e:
|
||||||
|
return str(e)
|
||||||
else:
|
else:
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
@@ -170,7 +173,7 @@ class AuthMixin:
|
|||||||
class BaseUser(OrgModelMixin, AuthMixin):
|
class BaseUser(OrgModelMixin, AuthMixin):
|
||||||
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||||||
name = models.CharField(max_length=128, verbose_name=_('Name'))
|
name = models.CharField(max_length=128, verbose_name=_('Name'))
|
||||||
username = models.CharField(max_length=128, blank=True, verbose_name=_('Username'), validators=[alphanumeric], db_index=True)
|
username = models.CharField(max_length=128, blank=True, verbose_name=_('Username'), db_index=True)
|
||||||
password = fields.EncryptCharField(max_length=256, blank=True, null=True, verbose_name=_('Password'))
|
password = fields.EncryptCharField(max_length=256, blank=True, null=True, verbose_name=_('Password'))
|
||||||
private_key = fields.EncryptTextField(blank=True, null=True, verbose_name=_('SSH private key'))
|
private_key = fields.EncryptTextField(blank=True, null=True, verbose_name=_('SSH private key'))
|
||||||
public_key = fields.EncryptTextField(blank=True, null=True, verbose_name=_('SSH public key'))
|
public_key = fields.EncryptTextField(blank=True, null=True, verbose_name=_('SSH public key'))
|
||||||
@@ -182,10 +185,18 @@ class BaseUser(OrgModelMixin, AuthMixin):
|
|||||||
ASSETS_AMOUNT_CACHE_KEY = "ASSET_USER_{}_ASSETS_AMOUNT"
|
ASSETS_AMOUNT_CACHE_KEY = "ASSET_USER_{}_ASSETS_AMOUNT"
|
||||||
ASSET_USER_CACHE_TIME = 600
|
ASSET_USER_CACHE_TIME = 600
|
||||||
|
|
||||||
|
APPS_AMOUNT_CACHE_KEY = "APP_USER_{}_APPS_AMOUNT"
|
||||||
|
APP_USER_CACHE_TIME = 600
|
||||||
|
|
||||||
def get_related_assets(self):
|
def get_related_assets(self):
|
||||||
assets = self.assets.filter(org_id=self.org_id)
|
assets = self.assets.filter(org_id=self.org_id)
|
||||||
return assets
|
return assets
|
||||||
|
|
||||||
|
def get_related_apps(self):
|
||||||
|
from applications.models import Account
|
||||||
|
apps = Account.objects.filter(systemuser=self)
|
||||||
|
return apps
|
||||||
|
|
||||||
def get_username(self):
|
def get_username(self):
|
||||||
return self.username
|
return self.username
|
||||||
|
|
||||||
@@ -198,6 +209,15 @@ class BaseUser(OrgModelMixin, AuthMixin):
|
|||||||
cache.set(cache_key, cached, self.ASSET_USER_CACHE_TIME)
|
cache.set(cache_key, cached, self.ASSET_USER_CACHE_TIME)
|
||||||
return cached
|
return cached
|
||||||
|
|
||||||
|
@property
|
||||||
|
def apps_amount(self):
|
||||||
|
cache_key = self.APPS_AMOUNT_CACHE_KEY.format(self.id)
|
||||||
|
cached = cache.get(cache_key)
|
||||||
|
if not cached:
|
||||||
|
cached = self.get_related_apps().count()
|
||||||
|
cache.set(cache_key, cached, self.APP_USER_CACHE_TIME)
|
||||||
|
return cached
|
||||||
|
|
||||||
def expire_assets_amount(self):
|
def expire_assets_amount(self):
|
||||||
cache_key = self.ASSETS_AMOUNT_CACHE_KEY.format(self.id)
|
cache_key = self.ASSETS_AMOUNT_CACHE_KEY.format(self.id)
|
||||||
cache.delete(cache_key)
|
cache.delete(cache_key)
|
||||||
|
|||||||
@@ -7,9 +7,11 @@ from django.db import models
|
|||||||
from django.core.validators import MinValueValidator, MaxValueValidator
|
from django.core.validators import MinValueValidator, MaxValueValidator
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from common.utils import lazyproperty
|
from common.utils import lazyproperty, get_logger
|
||||||
from orgs.mixins.models import OrgModelMixin
|
from orgs.mixins.models import OrgModelMixin
|
||||||
|
|
||||||
|
logger = get_logger(__file__)
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'CommandFilter', 'CommandFilterRule'
|
'CommandFilter', 'CommandFilterRule'
|
||||||
@@ -19,11 +21,32 @@ __all__ = [
|
|||||||
class CommandFilter(OrgModelMixin):
|
class CommandFilter(OrgModelMixin):
|
||||||
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||||||
name = models.CharField(max_length=64, verbose_name=_("Name"))
|
name = models.CharField(max_length=64, verbose_name=_("Name"))
|
||||||
|
users = models.ManyToManyField(
|
||||||
|
'users.User', related_name='cmd_filters', blank=True,
|
||||||
|
verbose_name=_("User")
|
||||||
|
)
|
||||||
|
user_groups = models.ManyToManyField(
|
||||||
|
'users.UserGroup', related_name='cmd_filters', blank=True,
|
||||||
|
verbose_name=_("User group"),
|
||||||
|
)
|
||||||
|
assets = models.ManyToManyField(
|
||||||
|
'assets.Asset', related_name='cmd_filters', blank=True,
|
||||||
|
verbose_name=_("Asset")
|
||||||
|
)
|
||||||
|
system_users = models.ManyToManyField(
|
||||||
|
'assets.SystemUser', related_name='cmd_filters', blank=True,
|
||||||
|
verbose_name=_("System user"))
|
||||||
|
applications = models.ManyToManyField(
|
||||||
|
'applications.Application', related_name='cmd_filters', blank=True,
|
||||||
|
verbose_name=_("Application")
|
||||||
|
)
|
||||||
is_active = models.BooleanField(default=True, verbose_name=_('Is active'))
|
is_active = models.BooleanField(default=True, verbose_name=_('Is active'))
|
||||||
comment = models.TextField(blank=True, default='', verbose_name=_("Comment"))
|
comment = models.TextField(blank=True, default='', verbose_name=_("Comment"))
|
||||||
date_created = models.DateTimeField(auto_now_add=True)
|
date_created = models.DateTimeField(auto_now_add=True)
|
||||||
date_updated = models.DateTimeField(auto_now=True)
|
date_updated = models.DateTimeField(auto_now=True)
|
||||||
created_by = models.CharField(max_length=128, blank=True, default='', verbose_name=_('Created by'))
|
created_by = models.CharField(
|
||||||
|
max_length=128, blank=True, default='', verbose_name=_('Created by')
|
||||||
|
)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.name
|
return self.name
|
||||||
@@ -45,7 +68,7 @@ class CommandFilterRule(OrgModelMixin):
|
|||||||
|
|
||||||
class ActionChoices(models.IntegerChoices):
|
class ActionChoices(models.IntegerChoices):
|
||||||
deny = 0, _('Deny')
|
deny = 0, _('Deny')
|
||||||
allow = 1, _('Allow')
|
allow = 9, _('Allow')
|
||||||
confirm = 2, _('Reconfirm')
|
confirm = 2, _('Reconfirm')
|
||||||
|
|
||||||
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||||||
@@ -71,28 +94,52 @@ class CommandFilterRule(OrgModelMixin):
|
|||||||
verbose_name = _("Command filter rule")
|
verbose_name = _("Command filter rule")
|
||||||
|
|
||||||
@lazyproperty
|
@lazyproperty
|
||||||
def _pattern(self):
|
def pattern(self):
|
||||||
if self.type == 'command':
|
if self.type == 'command':
|
||||||
|
s = self.construct_command_regex(content=self.content)
|
||||||
|
else:
|
||||||
|
s = r'{0}'.format(self.content)
|
||||||
|
|
||||||
|
return s
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def construct_command_regex(cls, content):
|
||||||
regex = []
|
regex = []
|
||||||
content = self.content.replace('\r\n', '\n')
|
content = content.replace('\r\n', '\n')
|
||||||
for cmd in content.split('\n'):
|
for _cmd in content.split('\n'):
|
||||||
|
cmd = re.sub(r'\s+', ' ', _cmd)
|
||||||
cmd = re.escape(cmd)
|
cmd = re.escape(cmd)
|
||||||
cmd = cmd.replace('\\ ', '\s+')
|
cmd = cmd.replace('\\ ', '\s+')
|
||||||
|
|
||||||
|
# 有空格就不能 铆钉单词了
|
||||||
|
if ' ' in _cmd:
|
||||||
|
regex.append(cmd)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 如果是单个字符
|
||||||
if cmd[-1].isalpha():
|
if cmd[-1].isalpha():
|
||||||
regex.append(r'\b{0}\b'.format(cmd))
|
regex.append(r'\b{0}\b'.format(cmd))
|
||||||
else:
|
else:
|
||||||
regex.append(r'\b{0}'.format(cmd))
|
regex.append(r'\b{0}'.format(cmd))
|
||||||
s = r'{}'.format('|'.join(regex))
|
s = r'(?i){}'.format('|'.join(regex))
|
||||||
else:
|
return s
|
||||||
s = r'{0}'.format(self.content)
|
|
||||||
|
@staticmethod
|
||||||
|
def compile_regex(regex):
|
||||||
try:
|
try:
|
||||||
_pattern = re.compile(s)
|
pattern = re.compile(regex)
|
||||||
except:
|
except Exception as e:
|
||||||
_pattern = ''
|
error = _('The generated regular expression is incorrect: {}').format(str(e))
|
||||||
return _pattern
|
logger.error(error)
|
||||||
|
return False, error, None
|
||||||
|
return True, '', pattern
|
||||||
|
|
||||||
def match(self, data):
|
def match(self, data):
|
||||||
found = self._pattern.search(data)
|
succeed, error, pattern = self.compile_regex(regex=self.pattern)
|
||||||
|
if not succeed:
|
||||||
|
return self.ACTION_UNKNOWN, ''
|
||||||
|
|
||||||
|
found = pattern.search(data)
|
||||||
if not found:
|
if not found:
|
||||||
return self.ACTION_UNKNOWN, ''
|
return self.ACTION_UNKNOWN, ''
|
||||||
|
|
||||||
@@ -105,11 +152,11 @@ class CommandFilterRule(OrgModelMixin):
|
|||||||
return '{} % {}'.format(self.type, self.content)
|
return '{} % {}'.format(self.type, self.content)
|
||||||
|
|
||||||
def create_command_confirm_ticket(self, run_command, session, cmd_filter_rule, org_id):
|
def create_command_confirm_ticket(self, run_command, session, cmd_filter_rule, org_id):
|
||||||
from tickets.const import TicketTypeChoices
|
from tickets.const import TicketType
|
||||||
from tickets.models import Ticket
|
from tickets.models import Ticket
|
||||||
data = {
|
data = {
|
||||||
'title': _('Command confirm') + ' ({})'.format(session.user),
|
'title': _('Command confirm') + ' ({})'.format(session.user),
|
||||||
'type': TicketTypeChoices.command_confirm,
|
'type': TicketType.command_confirm,
|
||||||
'meta': {
|
'meta': {
|
||||||
'apply_run_user': session.user,
|
'apply_run_user': session.user,
|
||||||
'apply_run_asset': session.asset,
|
'apply_run_asset': session.asset,
|
||||||
@@ -122,6 +169,6 @@ class CommandFilterRule(OrgModelMixin):
|
|||||||
'org_id': org_id,
|
'org_id': org_id,
|
||||||
}
|
}
|
||||||
ticket = Ticket.objects.create(**data)
|
ticket = Ticket.objects.create(**data)
|
||||||
ticket.assignees.set(self.reviewers.all())
|
ticket.create_process_map_and_node(self.reviewers.all())
|
||||||
ticket.open(applicant=session.user_obj)
|
ticket.open(applicant=session.user_obj)
|
||||||
return ticket
|
return ticket
|
||||||
|
|||||||
@@ -3,17 +3,19 @@
|
|||||||
import socket
|
import socket
|
||||||
import uuid
|
import uuid
|
||||||
import random
|
import random
|
||||||
import re
|
|
||||||
|
|
||||||
|
from django.core.cache import cache
|
||||||
import paramiko
|
import paramiko
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.db.models import TextChoices
|
from django.db.models import TextChoices
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from common.utils.strings import no_special_chars
|
from common.utils import get_logger
|
||||||
from orgs.mixins.models import OrgModelMixin
|
from orgs.mixins.models import OrgModelMixin
|
||||||
from .base import BaseUser
|
from .base import BaseUser
|
||||||
|
|
||||||
|
logger = get_logger(__file__)
|
||||||
|
|
||||||
__all__ = ['Domain', 'Gateway']
|
__all__ = ['Domain', 'Gateway']
|
||||||
|
|
||||||
|
|
||||||
@@ -40,10 +42,19 @@ class Domain(OrgModelMixin):
|
|||||||
return self.gateway_set.filter(is_active=True)
|
return self.gateway_set.filter(is_active=True)
|
||||||
|
|
||||||
def random_gateway(self):
|
def random_gateway(self):
|
||||||
|
gateways = [gw for gw in self.gateways if gw.is_connective]
|
||||||
|
if gateways:
|
||||||
|
return random.choice(gateways)
|
||||||
|
else:
|
||||||
|
logger.warn(f'Gateway all bad. domain={self}, gateway_num={len(self.gateways)}.')
|
||||||
return random.choice(self.gateways)
|
return random.choice(self.gateways)
|
||||||
|
|
||||||
|
|
||||||
class Gateway(BaseUser):
|
class Gateway(BaseUser):
|
||||||
|
UNCONNECTIVE_KEY_TMPL = 'asset_unconnective_gateway_{}'
|
||||||
|
UNCONNECTIVE_SILENCE_PERIOD_KEY_TMPL = 'asset_unconnective_gateway_silence_period_{}'
|
||||||
|
UNCONNECTIVE_SILENCE_PERIOD_BEGIN_VALUE = 60 * 5
|
||||||
|
|
||||||
class Protocol(TextChoices):
|
class Protocol(TextChoices):
|
||||||
ssh = 'ssh', 'SSH'
|
ssh = 'ssh', 'SSH'
|
||||||
|
|
||||||
@@ -61,11 +72,40 @@ class Gateway(BaseUser):
|
|||||||
unique_together = [('name', 'org_id')]
|
unique_together = [('name', 'org_id')]
|
||||||
verbose_name = _("Gateway")
|
verbose_name = _("Gateway")
|
||||||
|
|
||||||
|
def set_unconnective(self):
|
||||||
|
unconnective_key = self.UNCONNECTIVE_KEY_TMPL.format(self.id)
|
||||||
|
unconnective_silence_period_key = self.UNCONNECTIVE_SILENCE_PERIOD_KEY_TMPL.format(self.id)
|
||||||
|
|
||||||
|
unconnective_silence_period = cache.get(unconnective_silence_period_key,
|
||||||
|
self.UNCONNECTIVE_SILENCE_PERIOD_BEGIN_VALUE)
|
||||||
|
cache.set(unconnective_silence_period_key, unconnective_silence_period * 2)
|
||||||
|
cache.set(unconnective_key, unconnective_silence_period, unconnective_silence_period)
|
||||||
|
|
||||||
|
def set_connective(self):
|
||||||
|
unconnective_key = self.UNCONNECTIVE_KEY_TMPL.format(self.id)
|
||||||
|
unconnective_silence_period_key = self.UNCONNECTIVE_SILENCE_PERIOD_KEY_TMPL.format(self.id)
|
||||||
|
|
||||||
|
cache.delete(unconnective_key)
|
||||||
|
cache.delete(unconnective_silence_period_key)
|
||||||
|
|
||||||
|
def get_is_unconnective(self):
|
||||||
|
unconnective_key = self.UNCONNECTIVE_KEY_TMPL.format(self.id)
|
||||||
|
return cache.get(unconnective_key, False)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_connective(self):
|
||||||
|
return not self.get_is_unconnective()
|
||||||
|
|
||||||
|
@is_connective.setter
|
||||||
|
def is_connective(self, value):
|
||||||
|
if value:
|
||||||
|
self.set_connective()
|
||||||
|
else:
|
||||||
|
self.set_unconnective()
|
||||||
|
|
||||||
def test_connective(self, local_port=None):
|
def test_connective(self, local_port=None):
|
||||||
if local_port is None:
|
if local_port is None:
|
||||||
local_port = self.port
|
local_port = self.port
|
||||||
if self.password and not no_special_chars(self.password):
|
|
||||||
return False, _("Password should not contains special characters")
|
|
||||||
|
|
||||||
client = paramiko.SSHClient()
|
client = paramiko.SSHClient()
|
||||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
@@ -80,9 +120,19 @@ class Gateway(BaseUser):
|
|||||||
except(paramiko.AuthenticationException,
|
except(paramiko.AuthenticationException,
|
||||||
paramiko.BadAuthenticationType,
|
paramiko.BadAuthenticationType,
|
||||||
paramiko.SSHException,
|
paramiko.SSHException,
|
||||||
|
paramiko.ChannelException,
|
||||||
paramiko.ssh_exception.NoValidConnectionsError,
|
paramiko.ssh_exception.NoValidConnectionsError,
|
||||||
socket.gaierror) as e:
|
socket.gaierror) as e:
|
||||||
return False, str(e)
|
err = str(e)
|
||||||
|
if err.startswith('[Errno None] Unable to connect to port'):
|
||||||
|
err = _('Unable to connect to port {port} on {ip}')
|
||||||
|
err = err.format(port=self.port, ip=self.ip)
|
||||||
|
elif err == 'Authentication failed.':
|
||||||
|
err = _('Authentication failed')
|
||||||
|
elif err == 'Connect failed':
|
||||||
|
err = _('Connect failed')
|
||||||
|
self.is_connective = False
|
||||||
|
return False, err
|
||||||
|
|
||||||
try:
|
try:
|
||||||
sock = proxy.get_transport().open_channel(
|
sock = proxy.get_transport().open_channel(
|
||||||
@@ -94,9 +144,18 @@ class Gateway(BaseUser):
|
|||||||
key_filename=self.private_key_file,
|
key_filename=self.private_key_file,
|
||||||
sock=sock,
|
sock=sock,
|
||||||
timeout=5)
|
timeout=5)
|
||||||
except (paramiko.SSHException, paramiko.ssh_exception.SSHException,
|
except (paramiko.SSHException,
|
||||||
paramiko.AuthenticationException, TimeoutError) as e:
|
paramiko.ssh_exception.SSHException,
|
||||||
return False, str(e)
|
paramiko.ChannelException,
|
||||||
|
paramiko.AuthenticationException,
|
||||||
|
TimeoutError) as e:
|
||||||
|
|
||||||
|
err = getattr(e, 'text', str(e))
|
||||||
|
if err == 'Connect failed':
|
||||||
|
err = _('Connect failed')
|
||||||
|
self.is_connective = False
|
||||||
|
return False, err
|
||||||
finally:
|
finally:
|
||||||
client.close()
|
client.close()
|
||||||
|
self.is_connective = True
|
||||||
return True, None
|
return True, None
|
||||||
|
|||||||
@@ -608,7 +608,7 @@ class Node(OrgModelMixin, SomeNodesMixin, FamilyMixin, NodeAssetsMixin):
|
|||||||
'isParent': True,
|
'isParent': True,
|
||||||
'open': self.is_org_root(),
|
'open': self.is_org_root(),
|
||||||
'meta': {
|
'meta': {
|
||||||
'node': {
|
'data': {
|
||||||
"id": self.id,
|
"id": self.id,
|
||||||
"name": self.name,
|
"name": self.name,
|
||||||
"value": self.value,
|
"value": self.value,
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ class ProtocolMixin:
|
|||||||
oracle = 'oracle', 'Oracle'
|
oracle = 'oracle', 'Oracle'
|
||||||
mariadb = 'mariadb', 'MariaDB'
|
mariadb = 'mariadb', 'MariaDB'
|
||||||
postgresql = 'postgresql', 'PostgreSQL'
|
postgresql = 'postgresql', 'PostgreSQL'
|
||||||
|
sqlserver = 'sqlserver', 'SQLServer'
|
||||||
k8s = 'k8s', 'K8S'
|
k8s = 'k8s', 'K8S'
|
||||||
|
|
||||||
SUPPORT_PUSH_PROTOCOLS = [Protocol.ssh, Protocol.rdp]
|
SUPPORT_PUSH_PROTOCOLS = [Protocol.ssh, Protocol.rdp]
|
||||||
@@ -43,7 +44,7 @@ class ProtocolMixin:
|
|||||||
Protocol.rdp
|
Protocol.rdp
|
||||||
]
|
]
|
||||||
APPLICATION_CATEGORY_DB_PROTOCOLS = [
|
APPLICATION_CATEGORY_DB_PROTOCOLS = [
|
||||||
Protocol.mysql, Protocol.oracle, Protocol.mariadb, Protocol.postgresql
|
Protocol.mysql, Protocol.oracle, Protocol.mariadb, Protocol.postgresql, Protocol.sqlserver
|
||||||
]
|
]
|
||||||
APPLICATION_CATEGORY_CLOUD_PROTOCOLS = [
|
APPLICATION_CATEGORY_CLOUD_PROTOCOLS = [
|
||||||
Protocol.k8s
|
Protocol.k8s
|
||||||
@@ -60,10 +61,10 @@ class ProtocolMixin:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_protocol_by_application_type(cls, app_type):
|
def get_protocol_by_application_type(cls, app_type):
|
||||||
from applications.const import ApplicationTypeChoices
|
from applications.const import AppType
|
||||||
if app_type in cls.APPLICATION_CATEGORY_PROTOCOLS:
|
if app_type in cls.APPLICATION_CATEGORY_PROTOCOLS:
|
||||||
protocol = app_type
|
protocol = app_type
|
||||||
elif app_type in ApplicationTypeChoices.remote_app_types():
|
elif app_type in AppType.remote_app_types():
|
||||||
protocol = cls.Protocol.rdp
|
protocol = cls.Protocol.rdp
|
||||||
else:
|
else:
|
||||||
protocol = None
|
protocol = None
|
||||||
@@ -73,6 +74,10 @@ class ProtocolMixin:
|
|||||||
def can_perm_to_asset(self):
|
def can_perm_to_asset(self):
|
||||||
return self.protocol in self.ASSET_CATEGORY_PROTOCOLS
|
return self.protocol in self.ASSET_CATEGORY_PROTOCOLS
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_asset_protocol(self):
|
||||||
|
return self.protocol in self.ASSET_CATEGORY_PROTOCOLS
|
||||||
|
|
||||||
|
|
||||||
class AuthMixin:
|
class AuthMixin:
|
||||||
username_same_with_user: bool
|
username_same_with_user: bool
|
||||||
@@ -99,16 +104,23 @@ class AuthMixin:
|
|||||||
password = cache.get(key)
|
password = cache.get(key)
|
||||||
return password
|
return password
|
||||||
|
|
||||||
def load_tmp_auth_if_has(self, asset_or_app_id, user):
|
def _clean_auth_info_if_manual_login_mode(self):
|
||||||
if not asset_or_app_id or not user:
|
if self.login_mode == self.LOGIN_MANUAL:
|
||||||
return
|
self.password = ''
|
||||||
|
self.private_key = ''
|
||||||
|
self.public_key = ''
|
||||||
|
|
||||||
|
def _load_tmp_auth_if_has(self, asset_or_app_id, user_id):
|
||||||
if self.login_mode != self.LOGIN_MANUAL:
|
if self.login_mode != self.LOGIN_MANUAL:
|
||||||
return
|
return
|
||||||
|
|
||||||
auth = self.get_temp_auth(asset_or_app_id, user)
|
if not asset_or_app_id or not user_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
auth = self.get_temp_auth(asset_or_app_id, user_id)
|
||||||
if not auth:
|
if not auth:
|
||||||
return
|
return
|
||||||
|
|
||||||
username = auth.get('username')
|
username = auth.get('username')
|
||||||
password = auth.get('password')
|
password = auth.get('password')
|
||||||
|
|
||||||
@@ -117,18 +129,21 @@ class AuthMixin:
|
|||||||
if password:
|
if password:
|
||||||
self.password = password
|
self.password = password
|
||||||
|
|
||||||
def load_app_more_auth(self, app_id=None, user_id=None):
|
def load_app_more_auth(self, app_id=None, username=None, user_id=None):
|
||||||
from users.models import User
|
self._clean_auth_info_if_manual_login_mode()
|
||||||
|
# 加载临时认证信息
|
||||||
if self.login_mode == self.LOGIN_MANUAL:
|
if self.login_mode == self.LOGIN_MANUAL:
|
||||||
self.password = ''
|
self._load_tmp_auth_if_has(app_id, user_id)
|
||||||
self.private_key = ''
|
|
||||||
if not user_id:
|
|
||||||
return
|
return
|
||||||
user = get_object_or_none(User, pk=user_id)
|
# 更新用户名
|
||||||
if not user:
|
from users.models import User
|
||||||
return
|
user = get_object_or_none(User, pk=user_id) if user_id else None
|
||||||
self.load_tmp_auth_if_has(app_id, user)
|
if self.username_same_with_user:
|
||||||
|
if user and not username:
|
||||||
|
_username = user.username
|
||||||
|
else:
|
||||||
|
_username = username
|
||||||
|
self.username = _username
|
||||||
|
|
||||||
def load_asset_special_auth(self, asset, username=''):
|
def load_asset_special_auth(self, asset, username=''):
|
||||||
"""
|
"""
|
||||||
@@ -148,34 +163,25 @@ class AuthMixin:
|
|||||||
|
|
||||||
def load_asset_more_auth(self, asset_id=None, username=None, user_id=None):
|
def load_asset_more_auth(self, asset_id=None, username=None, user_id=None):
|
||||||
from users.models import User
|
from users.models import User
|
||||||
|
self._clean_auth_info_if_manual_login_mode()
|
||||||
|
# 加载临时认证信息
|
||||||
if self.login_mode == self.LOGIN_MANUAL:
|
if self.login_mode == self.LOGIN_MANUAL:
|
||||||
self.password = ''
|
self._load_tmp_auth_if_has(asset_id, user_id)
|
||||||
self.private_key = ''
|
|
||||||
|
|
||||||
asset = None
|
|
||||||
if asset_id:
|
|
||||||
asset = get_object_or_none(Asset, pk=asset_id)
|
|
||||||
# 没有资产就没有必要继续了
|
|
||||||
if not asset:
|
|
||||||
logger.debug('Asset not found, pass')
|
|
||||||
return
|
return
|
||||||
|
# 更新用户名
|
||||||
user = None
|
user = get_object_or_none(User, pk=user_id) if user_id else None
|
||||||
if user_id:
|
|
||||||
user = get_object_or_none(User, pk=user_id)
|
|
||||||
|
|
||||||
_username = self.username
|
|
||||||
if self.username_same_with_user:
|
if self.username_same_with_user:
|
||||||
if user and not username:
|
if user and not username:
|
||||||
_username = user.username
|
_username = user.username
|
||||||
else:
|
else:
|
||||||
_username = username
|
_username = username
|
||||||
self.username = _username
|
self.username = _username
|
||||||
|
|
||||||
# 加载某个资产的特殊配置认证信息
|
# 加载某个资产的特殊配置认证信息
|
||||||
self.load_asset_special_auth(asset, _username)
|
asset = get_object_or_none(Asset, pk=asset_id) if asset_id else None
|
||||||
self.load_tmp_auth_if_has(asset_id, user)
|
if not asset:
|
||||||
|
logger.debug('Asset not found, pass')
|
||||||
|
return
|
||||||
|
self.load_asset_special_auth(asset, self.username)
|
||||||
|
|
||||||
|
|
||||||
class SystemUser(ProtocolMixin, AuthMixin, BaseUser):
|
class SystemUser(ProtocolMixin, AuthMixin, BaseUser):
|
||||||
@@ -206,12 +212,14 @@ class SystemUser(ProtocolMixin, AuthMixin, BaseUser):
|
|||||||
sudo = models.TextField(default='/bin/whoami', verbose_name=_('Sudo'))
|
sudo = models.TextField(default='/bin/whoami', verbose_name=_('Sudo'))
|
||||||
shell = models.CharField(max_length=64, default='/bin/bash', verbose_name=_('Shell'))
|
shell = models.CharField(max_length=64, default='/bin/bash', verbose_name=_('Shell'))
|
||||||
login_mode = models.CharField(choices=LOGIN_MODE_CHOICES, default=LOGIN_AUTO, max_length=10, verbose_name=_('Login mode'))
|
login_mode = models.CharField(choices=LOGIN_MODE_CHOICES, default=LOGIN_AUTO, max_length=10, verbose_name=_('Login mode'))
|
||||||
cmd_filters = models.ManyToManyField('CommandFilter', related_name='system_users', verbose_name=_("Command filter"), blank=True)
|
|
||||||
sftp_root = models.CharField(default='tmp', max_length=128, verbose_name=_("SFTP Root"))
|
sftp_root = models.CharField(default='tmp', max_length=128, verbose_name=_("SFTP Root"))
|
||||||
token = models.TextField(default='', verbose_name=_('Token'))
|
token = models.TextField(default='', verbose_name=_('Token'))
|
||||||
home = models.CharField(max_length=4096, default='', verbose_name=_('Home'), blank=True)
|
home = models.CharField(max_length=4096, default='', verbose_name=_('Home'), blank=True)
|
||||||
system_groups = models.CharField(default='', max_length=4096, verbose_name=_('System groups'), blank=True)
|
system_groups = models.CharField(default='', max_length=4096, verbose_name=_('System groups'), blank=True)
|
||||||
ad_domain = models.CharField(default='', max_length=256)
|
ad_domain = models.CharField(default='', max_length=256)
|
||||||
|
# linux su 命令 (switch user)
|
||||||
|
su_enabled = models.BooleanField(default=False, verbose_name=_('User switch'))
|
||||||
|
su_from = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='su_to', null=True, verbose_name=_("Switch from"))
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
username = self.username
|
username = self.username
|
||||||
@@ -271,6 +279,21 @@ class SystemUser(ProtocolMixin, AuthMixin, BaseUser):
|
|||||||
assets = Asset.objects.filter(id__in=asset_ids)
|
assets = Asset.objects.filter(id__in=asset_ids)
|
||||||
return assets
|
return assets
|
||||||
|
|
||||||
|
def add_related_assets(self, assets_or_ids):
|
||||||
|
self.assets.add(*tuple(assets_or_ids))
|
||||||
|
self.add_related_assets_to_su_from_if_need(assets_or_ids)
|
||||||
|
|
||||||
|
def add_related_assets_to_su_from_if_need(self, assets_or_ids):
|
||||||
|
if self.protocol not in [self.Protocol.ssh.value]:
|
||||||
|
return
|
||||||
|
if not self.su_enabled:
|
||||||
|
return
|
||||||
|
if not self.su_from:
|
||||||
|
return
|
||||||
|
if self.su_from.protocol != self.protocol:
|
||||||
|
return
|
||||||
|
self.su_from.assets.add(*tuple(assets_or_ids))
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
ordering = ['name']
|
ordering = ['name']
|
||||||
unique_together = [('name', 'org_id')]
|
unique_together = [('name', 'org_id')]
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from assets.models import AuthBook
|
|||||||
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
||||||
|
|
||||||
from .base import AuthSerializerMixin
|
from .base import AuthSerializerMixin
|
||||||
|
from .utils import validate_password_contains_left_double_curly_bracket
|
||||||
|
|
||||||
|
|
||||||
class AccountSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
class AccountSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
||||||
@@ -21,10 +22,15 @@ class AccountSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
fields = fields_small + fields_fk
|
fields = fields_small + fields_fk
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'username': {'required': True},
|
'username': {'required': True},
|
||||||
'password': {'write_only': True},
|
'password': {
|
||||||
|
'write_only': True,
|
||||||
|
"validators": [validate_password_contains_left_double_curly_bracket]
|
||||||
|
},
|
||||||
'private_key': {'write_only': True},
|
'private_key': {'write_only': True},
|
||||||
'public_key': {'write_only': True},
|
'public_key': {'write_only': True},
|
||||||
|
'systemuser_display': {'label': _('System user display')}
|
||||||
}
|
}
|
||||||
|
ref_name = 'AssetAccountSerializer'
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def setup_eager_loading(cls, queryset):
|
def setup_eager_loading(cls, queryset):
|
||||||
@@ -43,6 +49,7 @@ class AccountSecretSerializer(AccountSerializer):
|
|||||||
'password': {'write_only': False},
|
'password': {'write_only': False},
|
||||||
'private_key': {'write_only': False},
|
'private_key': {'write_only': False},
|
||||||
'public_key': {'write_only': False},
|
'public_key': {'write_only': False},
|
||||||
|
'systemuser_display': {'label': _('System user display')}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,19 +5,21 @@ from django.core.validators import RegexValidator
|
|||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
||||||
|
from users.models import User, UserGroup
|
||||||
|
from perms.models import AssetPermission
|
||||||
from ..models import Asset, Node, Platform, SystemUser
|
from ..models import Asset, Node, Platform, SystemUser
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'AssetSerializer', 'AssetSimpleSerializer',
|
'AssetSerializer', 'AssetSimpleSerializer', 'MiniAssetSerializer',
|
||||||
'ProtocolsField', 'PlatformSerializer',
|
'ProtocolsField', 'PlatformSerializer',
|
||||||
'AssetTaskSerializer',
|
'AssetTaskSerializer', 'AssetsTaskSerializer', 'ProtocolsField',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class ProtocolField(serializers.RegexField):
|
class ProtocolField(serializers.RegexField):
|
||||||
protocols = '|'.join(dict(Asset.Protocol.choices).keys())
|
protocols = '|'.join(dict(Asset.Protocol.choices).keys())
|
||||||
default_error_messages = {
|
default_error_messages = {
|
||||||
'invalid': _('Protocol format should {}/{}'.format(protocols, '1-65535'))
|
'invalid': _('Protocol format should {}/{}').format(protocols, '1-65535')
|
||||||
}
|
}
|
||||||
regex = r'^(%s)/(\d{1,5})$' % protocols
|
regex = r'^(%s)/(\d{1,5})$' % protocols
|
||||||
|
|
||||||
@@ -64,38 +66,47 @@ class AssetSerializer(BulkOrgResourceModelSerializer):
|
|||||||
)
|
)
|
||||||
protocols = ProtocolsField(label=_('Protocols'), required=False, default=['ssh/22'])
|
protocols = ProtocolsField(label=_('Protocols'), required=False, default=['ssh/22'])
|
||||||
domain_display = serializers.ReadOnlyField(source='domain.name', label=_('Domain name'))
|
domain_display = serializers.ReadOnlyField(source='domain.name', label=_('Domain name'))
|
||||||
nodes_display = serializers.ListField(child=serializers.CharField(), label=_('Nodes name'), required=False)
|
nodes_display = serializers.ListField(
|
||||||
|
child=serializers.CharField(), label=_('Nodes name'), required=False
|
||||||
|
)
|
||||||
|
labels_display = serializers.ListField(
|
||||||
|
child=serializers.CharField(), label=_('Labels name'), required=False, read_only=True
|
||||||
|
)
|
||||||
|
|
||||||
"""
|
"""
|
||||||
资产的数据结构
|
资产的数据结构
|
||||||
"""
|
"""
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Asset
|
model = Asset
|
||||||
fields_mini = ['id', 'hostname', 'ip']
|
fields_mini = ['id', 'hostname', 'ip', 'platform', 'protocols']
|
||||||
fields_small = fields_mini + [
|
fields_small = fields_mini + [
|
||||||
'protocol', 'port', 'protocols', 'is_active', 'public_ip',
|
'protocol', 'port', 'protocols', 'is_active',
|
||||||
'number', 'vendor', 'model', 'sn', 'cpu_model', 'cpu_count',
|
'public_ip', 'number', 'comment',
|
||||||
|
]
|
||||||
|
fields_hardware = [
|
||||||
|
'vendor', 'model', 'sn', 'cpu_model', 'cpu_count',
|
||||||
'cpu_cores', 'cpu_vcpus', 'memory', 'disk_total', 'disk_info',
|
'cpu_cores', 'cpu_vcpus', 'memory', 'disk_total', 'disk_info',
|
||||||
'os', 'os_version', 'os_arch', 'hostname_raw', 'comment',
|
'os', 'os_version', 'os_arch', 'hostname_raw',
|
||||||
'hardware_info', 'connectivity', 'date_verified'
|
'cpu_info', 'hardware_info',
|
||||||
]
|
]
|
||||||
fields_fk = [
|
fields_fk = [
|
||||||
'domain', 'domain_display', 'platform', 'admin_user', 'admin_user_display'
|
'domain', 'domain_display', 'platform', 'admin_user', 'admin_user_display'
|
||||||
]
|
]
|
||||||
fields_m2m = [
|
fields_m2m = [
|
||||||
'nodes', 'nodes_display', 'labels',
|
'nodes', 'nodes_display', 'labels', 'labels_display',
|
||||||
]
|
]
|
||||||
read_only_fields = [
|
read_only_fields = [
|
||||||
|
'connectivity', 'date_verified', 'cpu_info', 'hardware_info',
|
||||||
'created_by', 'date_created',
|
'created_by', 'date_created',
|
||||||
]
|
]
|
||||||
fields = fields_small + fields_fk + fields_m2m + read_only_fields
|
fields = fields_small + fields_hardware + fields_fk + fields_m2m + read_only_fields
|
||||||
|
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'protocol': {'write_only': True},
|
'protocol': {'write_only': True},
|
||||||
'port': {'write_only': True},
|
'port': {'write_only': True},
|
||||||
'hardware_info': {'label': _('Hardware info')},
|
'hardware_info': {'label': _('Hardware info'), 'read_only': True},
|
||||||
'org_name': {'label': _('Org name')},
|
'admin_user_display': {'label': _('Admin user display'), 'read_only': True},
|
||||||
'admin_user_display': {'label': _('Admin user display')}
|
'cpu_info': {'label': _('CPU info')},
|
||||||
}
|
}
|
||||||
|
|
||||||
def get_fields(self):
|
def get_fields(self):
|
||||||
@@ -157,6 +168,12 @@ class AssetSerializer(BulkOrgResourceModelSerializer):
|
|||||||
return instance
|
return instance
|
||||||
|
|
||||||
|
|
||||||
|
class MiniAssetSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Asset
|
||||||
|
fields = AssetSerializer.Meta.fields_mini
|
||||||
|
|
||||||
|
|
||||||
class PlatformSerializer(serializers.ModelSerializer):
|
class PlatformSerializer(serializers.ModelSerializer):
|
||||||
meta = serializers.DictField(required=False, allow_null=True, label=_('Meta'))
|
meta = serializers.DictField(required=False, allow_null=True, label=_('Meta'))
|
||||||
|
|
||||||
@@ -177,13 +194,12 @@ class PlatformSerializer(serializers.ModelSerializer):
|
|||||||
|
|
||||||
|
|
||||||
class AssetSimpleSerializer(serializers.ModelSerializer):
|
class AssetSimpleSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Asset
|
model = Asset
|
||||||
fields = ['id', 'hostname', 'ip', 'port', 'connectivity', 'date_verified']
|
fields = ['id', 'hostname', 'ip', 'port', 'connectivity', 'date_verified']
|
||||||
|
|
||||||
|
|
||||||
class AssetTaskSerializer(serializers.Serializer):
|
class AssetsTaskSerializer(serializers.Serializer):
|
||||||
ACTION_CHOICES = (
|
ACTION_CHOICES = (
|
||||||
('refresh', 'refresh'),
|
('refresh', 'refresh'),
|
||||||
('test', 'test'),
|
('test', 'test'),
|
||||||
@@ -193,3 +209,17 @@ class AssetTaskSerializer(serializers.Serializer):
|
|||||||
assets = serializers.PrimaryKeyRelatedField(
|
assets = serializers.PrimaryKeyRelatedField(
|
||||||
queryset=Asset.objects, required=False, allow_empty=True, many=True
|
queryset=Asset.objects, required=False, allow_empty=True, many=True
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AssetTaskSerializer(AssetsTaskSerializer):
|
||||||
|
ACTION_CHOICES = tuple(list(AssetsTaskSerializer.ACTION_CHOICES) + [
|
||||||
|
('push_system_user', 'push_system_user'),
|
||||||
|
('test_system_user', 'test_system_user')
|
||||||
|
])
|
||||||
|
action = serializers.ChoiceField(choices=ACTION_CHOICES, write_only=True)
|
||||||
|
asset = serializers.PrimaryKeyRelatedField(
|
||||||
|
queryset=Asset.objects, required=False, allow_empty=True, many=False
|
||||||
|
)
|
||||||
|
system_users = serializers.PrimaryKeyRelatedField(
|
||||||
|
queryset=SystemUser.objects, required=False, allow_empty=True, many=True
|
||||||
|
)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import re
|
import re
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from ..models import CommandFilter, CommandFilterRule
|
from ..models import CommandFilter, CommandFilterRule
|
||||||
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
||||||
from orgs.utils import tmp_to_root_org
|
from orgs.utils import tmp_to_root_org
|
||||||
@@ -22,16 +23,14 @@ class CommandFilterSerializer(BulkOrgResourceModelSerializer):
|
|||||||
'comment', 'created_by',
|
'comment', 'created_by',
|
||||||
]
|
]
|
||||||
fields_fk = ['rules']
|
fields_fk = ['rules']
|
||||||
fields_m2m = ['system_users']
|
fields_m2m = ['users', 'user_groups', 'system_users', 'assets', 'applications']
|
||||||
fields = fields_small + fields_fk + fields_m2m
|
fields = fields_small + fields_fk + fields_m2m
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'rules': {'read_only': True},
|
'rules': {'read_only': True}
|
||||||
'system_users': {'required': False},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
||||||
invalid_pattern = re.compile(r'[\.\*\+\[\\\?\{\}\^\$\|\(\)\#\<\>]')
|
|
||||||
type_display = serializers.ReadOnlyField(source='get_type_display')
|
type_display = serializers.ReadOnlyField(source='get_type_display')
|
||||||
action_display = serializers.ReadOnlyField(source='get_action_display')
|
action_display = serializers.ReadOnlyField(source='get_action_display')
|
||||||
|
|
||||||
@@ -39,13 +38,13 @@ class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
|||||||
model = CommandFilterRule
|
model = CommandFilterRule
|
||||||
fields_mini = ['id']
|
fields_mini = ['id']
|
||||||
fields_small = fields_mini + [
|
fields_small = fields_mini + [
|
||||||
'type', 'type_display', 'content', 'priority',
|
'type', 'type_display', 'content', 'pattern', 'priority',
|
||||||
'action', 'action_display', 'reviewers',
|
'action', 'action_display', 'reviewers',
|
||||||
'date_created', 'date_updated',
|
'date_created', 'date_updated',
|
||||||
'comment', 'created_by',
|
'comment', 'created_by',
|
||||||
]
|
]
|
||||||
fields_fk = ['filter']
|
fields_fk = ['filter']
|
||||||
fields = '__all__'
|
fields = fields_small + fields_fk
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
@@ -61,15 +60,16 @@ class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer):
|
|||||||
choices.pop(CommandFilterRule.ActionChoices.confirm, None)
|
choices.pop(CommandFilterRule.ActionChoices.confirm, None)
|
||||||
action._choices = choices
|
action._choices = choices
|
||||||
|
|
||||||
# def validate_content(self, content):
|
def validate_content(self, content):
|
||||||
# tp = self.initial_data.get("type")
|
tp = self.initial_data.get("type")
|
||||||
# if tp == CommandFilterRule.TYPE_REGEX:
|
if tp == CommandFilterRule.TYPE_COMMAND:
|
||||||
# return content
|
regex = CommandFilterRule.construct_command_regex(content)
|
||||||
# if self.invalid_pattern.search(content):
|
else:
|
||||||
# invalid_char = self.invalid_pattern.pattern.replace('\\', '')
|
regex = content
|
||||||
# msg = _("Content should not be contain: {}").format(invalid_char)
|
succeed, error, pattern = CommandFilterRule.compile_regex(regex)
|
||||||
# raise serializers.ValidationError(msg)
|
if not succeed:
|
||||||
# return content
|
raise serializers.ValidationError(error)
|
||||||
|
return content
|
||||||
|
|
||||||
|
|
||||||
class CommandConfirmSerializer(serializers.Serializer):
|
class CommandConfirmSerializer(serializers.Serializer):
|
||||||
|
|||||||
@@ -3,15 +3,15 @@
|
|||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
|
from common.validators import alphanumeric
|
||||||
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
||||||
from common.validators import NoSpecialChars
|
|
||||||
from ..models import Domain, Gateway
|
from ..models import Domain, Gateway
|
||||||
from .base import AuthSerializerMixin
|
from .base import AuthSerializerMixin
|
||||||
|
|
||||||
|
|
||||||
class DomainSerializer(BulkOrgResourceModelSerializer):
|
class DomainSerializer(BulkOrgResourceModelSerializer):
|
||||||
asset_count = serializers.SerializerMethodField(label=_('Assets count'))
|
asset_count = serializers.SerializerMethodField(label=_('Assets amount'))
|
||||||
application_count = serializers.SerializerMethodField(label=_('Applications count'))
|
application_count = serializers.SerializerMethodField(label=_('Applications amount'))
|
||||||
gateway_count = serializers.SerializerMethodField(label=_('Gateways count'))
|
gateway_count = serializers.SerializerMethodField(label=_('Gateways count'))
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
@@ -43,6 +43,8 @@ class DomainSerializer(BulkOrgResourceModelSerializer):
|
|||||||
|
|
||||||
|
|
||||||
class GatewaySerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
class GatewaySerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
||||||
|
is_connective = serializers.BooleanField(required=False)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Gateway
|
model = Gateway
|
||||||
fields_mini = ['id', 'name']
|
fields_mini = ['id', 'name']
|
||||||
@@ -51,14 +53,15 @@ class GatewaySerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
]
|
]
|
||||||
fields_small = fields_mini + fields_write_only + [
|
fields_small = fields_mini + fields_write_only + [
|
||||||
'username', 'ip', 'port', 'protocol',
|
'username', 'ip', 'port', 'protocol',
|
||||||
'is_active',
|
'is_active', 'is_connective',
|
||||||
'date_created', 'date_updated',
|
'date_created', 'date_updated',
|
||||||
'created_by', 'comment',
|
'created_by', 'comment',
|
||||||
]
|
]
|
||||||
fields_fk = ['domain']
|
fields_fk = ['domain']
|
||||||
fields = fields_small + fields_fk
|
fields = fields_small + fields_fk
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'password': {'write_only': True, 'validators': [NoSpecialChars()]},
|
'username': {"validators": [alphanumeric]},
|
||||||
|
'password': {'write_only': True},
|
||||||
'private_key': {"write_only": True},
|
'private_key': {"write_only": True},
|
||||||
'public_key': {"write_only": True},
|
'public_key': {"write_only": True},
|
||||||
}
|
}
|
||||||
@@ -67,7 +70,7 @@ class GatewaySerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
class GatewayWithAuthSerializer(GatewaySerializer):
|
class GatewayWithAuthSerializer(GatewaySerializer):
|
||||||
class Meta(GatewaySerializer.Meta):
|
class Meta(GatewaySerializer.Meta):
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'password': {'write_only': False, 'validators': [NoSpecialChars()]},
|
'password': {'write_only': False},
|
||||||
'private_key': {"write_only": False},
|
'private_key': {"write_only": False},
|
||||||
'public_key': {"write_only": False},
|
'public_key': {"write_only": False},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,16 +4,18 @@ from django.db.models import Count
|
|||||||
|
|
||||||
from common.mixins.serializers import BulkSerializerMixin
|
from common.mixins.serializers import BulkSerializerMixin
|
||||||
from common.utils import ssh_pubkey_gen
|
from common.utils import ssh_pubkey_gen
|
||||||
|
from common.validators import alphanumeric_re, alphanumeric_cn_re
|
||||||
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
||||||
from ..models import SystemUser, Asset
|
from ..models import SystemUser, Asset
|
||||||
|
from .utils import validate_password_contains_left_double_curly_bracket
|
||||||
from .base import AuthSerializerMixin
|
from .base import AuthSerializerMixin
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'SystemUserSerializer',
|
'SystemUserSerializer', 'MiniSystemUserSerializer',
|
||||||
'SystemUserSimpleSerializer', 'SystemUserAssetRelationSerializer',
|
'SystemUserSimpleSerializer', 'SystemUserAssetRelationSerializer',
|
||||||
'SystemUserNodeRelationSerializer', 'SystemUserTaskSerializer',
|
'SystemUserNodeRelationSerializer', 'SystemUserTaskSerializer',
|
||||||
'SystemUserUserRelationSerializer', 'SystemUserWithAuthInfoSerializer',
|
'SystemUserUserRelationSerializer', 'SystemUserWithAuthInfoSerializer',
|
||||||
'SystemUserTempAuthSerializer',
|
'SystemUserTempAuthSerializer', 'RelationMixin',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -24,23 +26,32 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
auto_generate_key = serializers.BooleanField(initial=True, required=False, write_only=True)
|
auto_generate_key = serializers.BooleanField(initial=True, required=False, write_only=True)
|
||||||
type_display = serializers.ReadOnlyField(source='get_type_display', label=_('Type display'))
|
type_display = serializers.ReadOnlyField(source='get_type_display', label=_('Type display'))
|
||||||
ssh_key_fingerprint = serializers.ReadOnlyField(label=_('SSH key fingerprint'))
|
ssh_key_fingerprint = serializers.ReadOnlyField(label=_('SSH key fingerprint'))
|
||||||
|
applications_amount = serializers.IntegerField(
|
||||||
|
source='apps_amount', read_only=True, label=_('Apps amount')
|
||||||
|
)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = SystemUser
|
model = SystemUser
|
||||||
fields_mini = ['id', 'name', 'username']
|
fields_mini = ['id', 'name', 'username']
|
||||||
fields_write_only = ['password', 'public_key', 'private_key']
|
fields_write_only = ['password', 'public_key', 'private_key']
|
||||||
fields_small = fields_mini + fields_write_only + [
|
fields_small = fields_mini + fields_write_only + [
|
||||||
'type', 'type_display', 'protocol', 'login_mode', 'login_mode_display',
|
'token', 'ssh_key_fingerprint',
|
||||||
'priority', 'sudo', 'shell', 'sftp_root', 'token', 'ssh_key_fingerprint',
|
'type', 'type_display', 'protocol', 'is_asset_protocol',
|
||||||
'home', 'system_groups', 'ad_domain',
|
'login_mode', 'login_mode_display', 'priority',
|
||||||
|
'sudo', 'shell', 'sftp_root', 'home', 'system_groups', 'ad_domain',
|
||||||
'username_same_with_user', 'auto_push', 'auto_generate_key',
|
'username_same_with_user', 'auto_push', 'auto_generate_key',
|
||||||
'date_created', 'date_updated',
|
'su_enabled', 'su_from',
|
||||||
'comment', 'created_by',
|
'date_created', 'date_updated', 'comment', 'created_by',
|
||||||
]
|
]
|
||||||
fields_m2m = ['cmd_filters', 'assets_amount']
|
fields_m2m = ['cmd_filters', 'assets_amount', 'applications_amount', 'nodes']
|
||||||
fields = fields_small + fields_m2m
|
fields = fields_small + fields_m2m
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'password': {"write_only": True},
|
'password': {
|
||||||
|
"write_only": True,
|
||||||
|
'trim_whitespace': False,
|
||||||
|
"validators": [validate_password_contains_left_double_curly_bracket]
|
||||||
|
},
|
||||||
|
'cmd_filters': {"required": False},
|
||||||
'public_key': {"write_only": True},
|
'public_key': {"write_only": True},
|
||||||
'private_key': {"write_only": True},
|
'private_key': {"write_only": True},
|
||||||
'token': {"write_only": True},
|
'token': {"write_only": True},
|
||||||
@@ -49,6 +60,8 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
'login_mode_display': {'label': _('Login mode display')},
|
'login_mode_display': {'label': _('Login mode display')},
|
||||||
'created_by': {'read_only': True},
|
'created_by': {'read_only': True},
|
||||||
'ad_domain': {'required': False, 'allow_blank': True, 'label': _('Ad domain')},
|
'ad_domain': {'required': False, 'allow_blank': True, 'label': _('Ad domain')},
|
||||||
|
'is_asset_protocol': {'label': _('Is asset protocol')},
|
||||||
|
'su_from': {'help_text': _('Only ssh and automatic login system users are supported')}
|
||||||
}
|
}
|
||||||
|
|
||||||
def validate_auto_push(self, value):
|
def validate_auto_push(self, value):
|
||||||
@@ -92,15 +105,20 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
raise serializers.ValidationError(error)
|
raise serializers.ValidationError(error)
|
||||||
|
|
||||||
def validate_username(self, username):
|
def validate_username(self, username):
|
||||||
if username:
|
|
||||||
return username
|
|
||||||
login_mode = self.get_initial_value("login_mode")
|
|
||||||
protocol = self.get_initial_value("protocol")
|
protocol = self.get_initial_value("protocol")
|
||||||
username_same_with_user = self.get_initial_value("username_same_with_user")
|
if username:
|
||||||
|
regx = alphanumeric_re
|
||||||
|
if protocol == SystemUser.Protocol.telnet:
|
||||||
|
regx = alphanumeric_cn_re
|
||||||
|
if not regx.match(username):
|
||||||
|
raise serializers.ValidationError(_('Special char not allowed'))
|
||||||
|
return username
|
||||||
|
|
||||||
|
username_same_with_user = self.get_initial_value("username_same_with_user")
|
||||||
if username_same_with_user:
|
if username_same_with_user:
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
login_mode = self.get_initial_value("login_mode")
|
||||||
if login_mode == SystemUser.LOGIN_AUTO and protocol != SystemUser.Protocol.vnc:
|
if login_mode == SystemUser.LOGIN_AUTO and protocol != SystemUser.Protocol.vnc:
|
||||||
msg = _('* Automatic login mode must fill in the username.')
|
msg = _('* Automatic login mode must fill in the username.')
|
||||||
raise serializers.ValidationError(msg)
|
raise serializers.ValidationError(msg)
|
||||||
@@ -112,7 +130,8 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
return ''
|
return ''
|
||||||
return home
|
return home
|
||||||
|
|
||||||
def validate_sftp_root(self, value):
|
@staticmethod
|
||||||
|
def validate_sftp_root(value):
|
||||||
if value in ['home', 'tmp']:
|
if value in ['home', 'tmp']:
|
||||||
return value
|
return value
|
||||||
if not value.startswith('/'):
|
if not value.startswith('/'):
|
||||||
@@ -120,19 +139,6 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
raise serializers.ValidationError(error)
|
raise serializers.ValidationError(error)
|
||||||
return value
|
return value
|
||||||
|
|
||||||
def validate_admin_user(self, attrs):
|
|
||||||
if self.instance:
|
|
||||||
tp = self.instance.type
|
|
||||||
else:
|
|
||||||
tp = attrs.get('type')
|
|
||||||
if tp != SystemUser.Type.admin:
|
|
||||||
return attrs
|
|
||||||
attrs['protocol'] = SystemUser.Protocol.ssh
|
|
||||||
attrs['login_mode'] = SystemUser.LOGIN_AUTO
|
|
||||||
attrs['username_same_with_user'] = False
|
|
||||||
attrs['auto_push'] = False
|
|
||||||
return attrs
|
|
||||||
|
|
||||||
def validate_password(self, password):
|
def validate_password(self, password):
|
||||||
super().validate_password(password)
|
super().validate_password(password)
|
||||||
auto_gen_key = self.get_initial_value("auto_generate_key", False)
|
auto_gen_key = self.get_initial_value("auto_generate_key", False)
|
||||||
@@ -144,7 +150,43 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
raise serializers.ValidationError(_("Password or private key required"))
|
raise serializers.ValidationError(_("Password or private key required"))
|
||||||
return password
|
return password
|
||||||
|
|
||||||
def validate_gen_key(self, attrs):
|
def validate_su_from(self, su_from: SystemUser):
|
||||||
|
# self: su enabled
|
||||||
|
su_enabled = self.get_initial_value('su_enabled', default=False)
|
||||||
|
if not su_enabled:
|
||||||
|
return
|
||||||
|
if not su_from:
|
||||||
|
error = _('This field is required.')
|
||||||
|
raise serializers.ValidationError(error)
|
||||||
|
# self: protocol ssh
|
||||||
|
protocol = self.get_initial_value('protocol', default=SystemUser.Protocol.ssh.value)
|
||||||
|
if protocol not in [SystemUser.Protocol.ssh.value]:
|
||||||
|
error = _('Only ssh protocol system users are allowed')
|
||||||
|
raise serializers.ValidationError(error)
|
||||||
|
# su_from: protocol same
|
||||||
|
if su_from.protocol != protocol:
|
||||||
|
error = _('The protocol must be consistent with the current user: {}').format(protocol)
|
||||||
|
raise serializers.ValidationError(error)
|
||||||
|
# su_from: login model auto
|
||||||
|
if su_from.login_mode != su_from.LOGIN_AUTO:
|
||||||
|
error = _('Only system users with automatic login are allowed')
|
||||||
|
raise serializers.ValidationError(error)
|
||||||
|
return su_from
|
||||||
|
|
||||||
|
def _validate_admin_user(self, attrs):
|
||||||
|
if self.instance:
|
||||||
|
tp = self.instance.type
|
||||||
|
else:
|
||||||
|
tp = attrs.get('type')
|
||||||
|
if tp != SystemUser.Type.admin:
|
||||||
|
return attrs
|
||||||
|
attrs['protocol'] = SystemUser.Protocol.ssh
|
||||||
|
attrs['login_mode'] = SystemUser.LOGIN_AUTO
|
||||||
|
attrs['username_same_with_user'] = False
|
||||||
|
attrs['auto_push'] = False
|
||||||
|
return attrs
|
||||||
|
|
||||||
|
def _validate_gen_key(self, attrs):
|
||||||
username = attrs.get("username", "manual")
|
username = attrs.get("username", "manual")
|
||||||
auto_gen_key = attrs.pop("auto_generate_key", False)
|
auto_gen_key = attrs.pop("auto_generate_key", False)
|
||||||
protocol = attrs.get("protocol")
|
protocol = attrs.get("protocol")
|
||||||
@@ -168,18 +210,40 @@ class SystemUserSerializer(AuthSerializerMixin, BulkOrgResourceModelSerializer):
|
|||||||
attrs["public_key"] = public_key
|
attrs["public_key"] = public_key
|
||||||
return attrs
|
return attrs
|
||||||
|
|
||||||
|
def _validate_login_mode(self, attrs):
|
||||||
|
if 'login_mode' in attrs:
|
||||||
|
login_mode = attrs['login_mode']
|
||||||
|
else:
|
||||||
|
login_mode = self.instance.login_mode if self.instance else SystemUser.LOGIN_AUTO
|
||||||
|
|
||||||
|
if login_mode == SystemUser.LOGIN_MANUAL:
|
||||||
|
attrs['password'] = ''
|
||||||
|
attrs['private_key'] = ''
|
||||||
|
attrs['public_key'] = ''
|
||||||
|
|
||||||
|
return attrs
|
||||||
|
|
||||||
def validate(self, attrs):
|
def validate(self, attrs):
|
||||||
attrs = self.validate_admin_user(attrs)
|
attrs = self._validate_admin_user(attrs)
|
||||||
attrs = self.validate_gen_key(attrs)
|
attrs = self._validate_gen_key(attrs)
|
||||||
|
attrs = self._validate_login_mode(attrs)
|
||||||
return attrs
|
return attrs
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def setup_eager_loading(cls, queryset):
|
def setup_eager_loading(cls, queryset):
|
||||||
""" Perform necessary eager loading of data. """
|
""" Perform necessary eager loading of data. """
|
||||||
queryset = queryset.annotate(assets_amount=Count("assets"))
|
queryset = queryset\
|
||||||
|
.annotate(assets_amount=Count("assets")) \
|
||||||
|
.prefetch_related('nodes', 'cmd_filters')
|
||||||
return queryset
|
return queryset
|
||||||
|
|
||||||
|
|
||||||
|
class MiniSystemUserSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = SystemUser
|
||||||
|
fields = SystemUserSerializer.Meta.fields_mini
|
||||||
|
|
||||||
|
|
||||||
class SystemUserWithAuthInfoSerializer(SystemUserSerializer):
|
class SystemUserWithAuthInfoSerializer(SystemUserSerializer):
|
||||||
class Meta(SystemUserSerializer.Meta):
|
class Meta(SystemUserSerializer.Meta):
|
||||||
fields_mini = ['id', 'name', 'username']
|
fields_mini = ['id', 'name', 'username']
|
||||||
@@ -203,6 +267,7 @@ class SystemUserSimpleSerializer(serializers.ModelSerializer):
|
|||||||
"""
|
"""
|
||||||
系统用户最基本信息的数据结构
|
系统用户最基本信息的数据结构
|
||||||
"""
|
"""
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = SystemUser
|
model = SystemUser
|
||||||
fields = ('id', 'name', 'username')
|
fields = ('id', 'name', 'username')
|
||||||
|
|||||||
9
apps/assets/serializers/utils.py
Normal file
9
apps/assets/serializers/utils.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
|
||||||
|
def validate_password_contains_left_double_curly_bracket(password):
|
||||||
|
# validate password contains left double curly bracket
|
||||||
|
# check password not contains `{{`
|
||||||
|
if '{{' in password:
|
||||||
|
raise serializers.ValidationError(_('Password can not contains `{{` '))
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from simple_history.signals import pre_create_historical_record
|
from simple_history.signals import pre_create_historical_record
|
||||||
from django.db.models.signals import post_save, pre_save
|
from django.db.models.signals import post_save, pre_save, pre_delete
|
||||||
|
|
||||||
from common.utils import get_logger
|
from common.utils import get_logger
|
||||||
from ..models import AuthBook, SystemUser
|
from ..models import AuthBook, SystemUser
|
||||||
@@ -28,15 +28,24 @@ def pre_create_historical_record_callback(sender, history_instance=None, **kwarg
|
|||||||
setattr(history_instance, attr, system_user_attr_value)
|
setattr(history_instance, attr, system_user_attr_value)
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(pre_delete, sender=AuthBook)
|
||||||
|
def on_authbook_post_delete(sender, instance, **kwargs):
|
||||||
|
instance.remove_asset_admin_user_if_need()
|
||||||
|
|
||||||
|
|
||||||
@receiver(post_save, sender=AuthBook)
|
@receiver(post_save, sender=AuthBook)
|
||||||
def on_authbook_post_create(sender, instance, **kwargs):
|
def on_authbook_post_create(sender, instance, created, **kwargs):
|
||||||
if not instance.systemuser:
|
|
||||||
instance.sync_to_system_user_account()
|
instance.sync_to_system_user_account()
|
||||||
|
if created:
|
||||||
|
pass
|
||||||
|
# # 不再自动更新资产管理用户,只允许用户手动指定。
|
||||||
|
# 只在创建时进行更新资产的管理用户
|
||||||
|
# instance.update_asset_admin_user_if_need()
|
||||||
|
|
||||||
|
|
||||||
@receiver(pre_save, sender=AuthBook)
|
@receiver(pre_save, sender=AuthBook)
|
||||||
def on_authbook_pre_create(sender, instance, **kwargs):
|
def on_authbook_pre_create(sender, instance, **kwargs):
|
||||||
# 升级版本号
|
# 升级版本号
|
||||||
instance.version = instance.history.all().count() + 1
|
instance.version += 1
|
||||||
# 即使在 root 组织也不怕
|
# 即使在 root 组织也不怕
|
||||||
instance.org_id = instance.asset.org_id
|
instance.org_id = instance.asset.org_id
|
||||||
|
|||||||
@@ -40,15 +40,10 @@ def expire_node_assets_mapping_for_memory(org_id):
|
|||||||
root_org_id = Organization.ROOT_ID
|
root_org_id = Organization.ROOT_ID
|
||||||
|
|
||||||
# 当前进程清除(cache 数据)
|
# 当前进程清除(cache 数据)
|
||||||
logger.debug(
|
|
||||||
"Expire node assets id mapping from cache of org={}, pid={}"
|
|
||||||
"".format(org_id, os.getpid())
|
|
||||||
)
|
|
||||||
Node.expire_node_all_asset_ids_mapping_from_cache(org_id)
|
Node.expire_node_all_asset_ids_mapping_from_cache(org_id)
|
||||||
Node.expire_node_all_asset_ids_mapping_from_cache(root_org_id)
|
Node.expire_node_all_asset_ids_mapping_from_cache(root_org_id)
|
||||||
|
|
||||||
node_assets_mapping_for_memory_pub_sub.publish(org_id)
|
node_assets_mapping_for_memory_pub_sub.publish(org_id)
|
||||||
node_assets_mapping_for_memory_pub_sub.publish(root_org_id)
|
|
||||||
|
|
||||||
|
|
||||||
@receiver(post_save, sender=Node)
|
@receiver(post_save, sender=Node)
|
||||||
@@ -78,23 +73,14 @@ def on_node_asset_change(sender, instance, **kwargs):
|
|||||||
def subscribe_node_assets_mapping_expire(sender, **kwargs):
|
def subscribe_node_assets_mapping_expire(sender, **kwargs):
|
||||||
logger.debug("Start subscribe for expire node assets id mapping from memory")
|
logger.debug("Start subscribe for expire node assets id mapping from memory")
|
||||||
|
|
||||||
def keep_subscribe():
|
def handle_node_relation_change(org_id):
|
||||||
while True:
|
root_org_id = Organization.ROOT_ID
|
||||||
try:
|
|
||||||
subscribe = node_assets_mapping_for_memory_pub_sub.subscribe()
|
|
||||||
for message in subscribe.listen():
|
|
||||||
if message["type"] != "message":
|
|
||||||
continue
|
|
||||||
org_id = message['data'].decode()
|
|
||||||
Node.expire_node_all_asset_ids_mapping_from_memory(org_id)
|
Node.expire_node_all_asset_ids_mapping_from_memory(org_id)
|
||||||
logger.debug(
|
Node.expire_node_all_asset_ids_mapping_from_memory(root_org_id)
|
||||||
"Expire node assets id mapping from memory of org={}, pid={}"
|
|
||||||
"".format(str(org_id), os.getpid())
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception(f'subscribe_node_assets_mapping_expire: {e}')
|
|
||||||
Node.expire_all_orgs_node_all_asset_ids_mapping_from_memory()
|
|
||||||
|
|
||||||
t = threading.Thread(target=keep_subscribe)
|
def keep_subscribe_node_assets_relation():
|
||||||
|
node_assets_mapping_for_memory_pub_sub.keep_handle_msg(handle_node_relation_change)
|
||||||
|
|
||||||
|
t = threading.Thread(target=keep_subscribe_node_assets_relation)
|
||||||
t.daemon = True
|
t.daemon = True
|
||||||
t.start()
|
t.start()
|
||||||
|
|||||||
@@ -131,8 +131,8 @@ def on_system_user_groups_change(instance, action, pk_set, reverse, **kwargs):
|
|||||||
@on_transaction_commit
|
@on_transaction_commit
|
||||||
def on_system_user_update(instance: SystemUser, created, **kwargs):
|
def on_system_user_update(instance: SystemUser, created, **kwargs):
|
||||||
"""
|
"""
|
||||||
当系统用户更新时,可能更新了秘钥,用户名等,这时要自动推送系统用户到资产上,
|
当系统用户更新时,可能更新了密钥,用户名等,这时要自动推送系统用户到资产上,
|
||||||
其实应该当 用户名,密码,秘钥 sudo等更新时再推送,这里偷个懒,
|
其实应该当 用户名,密码,密钥 sudo等更新时再推送,这里偷个懒,
|
||||||
这里直接取了 instance.assets 因为nodes和系统用户发生变化时,会自动将nodes下的资产
|
这里直接取了 instance.assets 因为nodes和系统用户发生变化时,会自动将nodes下的资产
|
||||||
关联到上面
|
关联到上面
|
||||||
"""
|
"""
|
||||||
@@ -140,3 +140,5 @@ def on_system_user_update(instance: SystemUser, created, **kwargs):
|
|||||||
logger.info("System user update signal recv: {}".format(instance))
|
logger.info("System user update signal recv: {}".format(instance))
|
||||||
assets = instance.assets.all().valid()
|
assets = instance.assets.all().valid()
|
||||||
push_system_user_to_assets.delay(instance.id, [_asset.id for _asset in assets])
|
push_system_user_to_assets.delay(instance.id, [_asset.id for _asset in assets])
|
||||||
|
# add assets to su_from
|
||||||
|
instance.add_related_assets_to_su_from_if_need(assets)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
from celery import shared_task
|
from celery import shared_task
|
||||||
|
|
||||||
from orgs.utils import tmp_to_root_org
|
from orgs.utils import tmp_to_root_org
|
||||||
|
from assets.models import AuthBook
|
||||||
|
|
||||||
__all__ = ['add_nodes_assets_to_system_users']
|
__all__ = ['add_nodes_assets_to_system_users']
|
||||||
|
|
||||||
@@ -12,7 +13,24 @@ __all__ = ['add_nodes_assets_to_system_users']
|
|||||||
@tmp_to_root_org()
|
@tmp_to_root_org()
|
||||||
def add_nodes_assets_to_system_users(nodes_keys, system_users):
|
def add_nodes_assets_to_system_users(nodes_keys, system_users):
|
||||||
from ..models import Node
|
from ..models import Node
|
||||||
|
from assets.tasks import push_system_user_to_assets
|
||||||
|
|
||||||
nodes = Node.objects.filter(key__in=nodes_keys)
|
nodes = Node.objects.filter(key__in=nodes_keys)
|
||||||
assets = Node.get_nodes_all_assets(*nodes)
|
assets = Node.get_nodes_all_assets(*nodes)
|
||||||
for system_user in system_users:
|
for system_user in system_users:
|
||||||
system_user.assets.add(*tuple(assets))
|
""" 解决资产和节点进行关联时,已经关联过的节点不会触发 authbook post_save 信号,
|
||||||
|
无法更新节点下所有资产的管理用户的问题 """
|
||||||
|
need_push_asset_ids = []
|
||||||
|
for asset in assets:
|
||||||
|
defaults = {'asset': asset, 'systemuser': system_user, 'org_id': asset.org_id}
|
||||||
|
instance, created = AuthBook.objects.update_or_create(
|
||||||
|
defaults=defaults, asset=asset, systemuser=system_user
|
||||||
|
)
|
||||||
|
if created:
|
||||||
|
need_push_asset_ids.append(asset.id)
|
||||||
|
# # 不再自动更新资产管理用户,只允许用户手动指定。
|
||||||
|
# 只要关联都需要更新资产的管理用户
|
||||||
|
# instance.update_asset_admin_user_if_need()
|
||||||
|
|
||||||
|
if need_push_asset_ids:
|
||||||
|
push_system_user_to_assets.delay(system_user.id, need_push_asset_ids)
|
||||||
|
|||||||
@@ -60,9 +60,12 @@ def parse_windows_result_to_users(result):
|
|||||||
task_result.pop()
|
task_result.pop()
|
||||||
|
|
||||||
for line in task_result:
|
for line in task_result:
|
||||||
user = space.split(line)
|
username_list = space.split(line)
|
||||||
if user[0]:
|
# such as: ['Admini', 'appadm', 'DefaultAccount', '']
|
||||||
users[user[0]] = {}
|
for username in username_list:
|
||||||
|
if not username:
|
||||||
|
continue
|
||||||
|
users[username] = {}
|
||||||
return users
|
return users
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from itertools import groupby
|
|||||||
from celery import shared_task
|
from celery import shared_task
|
||||||
from common.db.utils import get_object_if_need, get_objects
|
from common.db.utils import get_object_if_need, get_objects
|
||||||
from django.utils.translation import ugettext as _
|
from django.utils.translation import ugettext as _
|
||||||
from django.db.models import Empty
|
from django.db.models import Empty, Q
|
||||||
|
|
||||||
from common.utils import encrypt_password, get_logger
|
from common.utils import encrypt_password, get_logger
|
||||||
from assets.models import SystemUser, Asset, AuthBook
|
from assets.models import SystemUser, Asset, AuthBook
|
||||||
@@ -17,6 +17,7 @@ logger = get_logger(__file__)
|
|||||||
__all__ = [
|
__all__ = [
|
||||||
'push_system_user_util', 'push_system_user_to_assets',
|
'push_system_user_util', 'push_system_user_to_assets',
|
||||||
'push_system_user_to_assets_manual', 'push_system_user_a_asset_manual',
|
'push_system_user_to_assets_manual', 'push_system_user_a_asset_manual',
|
||||||
|
'push_system_users_a_asset'
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -137,7 +138,7 @@ def get_push_unixlike_system_user_tasks(system_user, username=None):
|
|||||||
return tasks
|
return tasks
|
||||||
|
|
||||||
|
|
||||||
def get_push_windows_system_user_tasks(system_user, username=None):
|
def get_push_windows_system_user_tasks(system_user: SystemUser, username=None):
|
||||||
if username is None:
|
if username is None:
|
||||||
username = system_user.username
|
username = system_user.username
|
||||||
password = system_user.password
|
password = system_user.password
|
||||||
@@ -150,6 +151,11 @@ def get_push_windows_system_user_tasks(system_user, username=None):
|
|||||||
if not password:
|
if not password:
|
||||||
logger.error("Error: no password found")
|
logger.error("Error: no password found")
|
||||||
return tasks
|
return tasks
|
||||||
|
|
||||||
|
if system_user.ad_domain:
|
||||||
|
logger.error('System user with AD domain do not support push.')
|
||||||
|
return tasks
|
||||||
|
|
||||||
task = {
|
task = {
|
||||||
'name': 'Add user {}'.format(username),
|
'name': 'Add user {}'.format(username),
|
||||||
'action': {
|
'action': {
|
||||||
@@ -238,9 +244,12 @@ def push_system_user_util(system_user, assets, task_name, username=None):
|
|||||||
no_special_auth = []
|
no_special_auth = []
|
||||||
special_auth_set = set()
|
special_auth_set = set()
|
||||||
|
|
||||||
auth_books = AuthBook.objects.filter(username__in=usernames, asset_id__in=asset_ids)
|
auth_books = AuthBook.objects.filter(asset_id__in=asset_ids).filter(
|
||||||
|
Q(username__in=usernames) | Q(systemuser__username__in=usernames)
|
||||||
|
).prefetch_related('systemuser')
|
||||||
|
|
||||||
for auth_book in auth_books:
|
for auth_book in auth_books:
|
||||||
|
auth_book.load_auth()
|
||||||
special_auth_set.add((auth_book.username, auth_book.asset_id))
|
special_auth_set.add((auth_book.username, auth_book.asset_id))
|
||||||
|
|
||||||
for _username in usernames:
|
for _username in usernames:
|
||||||
@@ -280,14 +289,21 @@ def push_system_user_a_asset_manual(system_user, asset, username=None):
|
|||||||
"""
|
"""
|
||||||
将系统用户推送到一个资产上
|
将系统用户推送到一个资产上
|
||||||
"""
|
"""
|
||||||
if username is None:
|
# if username is None:
|
||||||
username = system_user.username
|
# username = system_user.username
|
||||||
task_name = _("Push system users to asset: {}({}) => {}").format(
|
task_name = _("Push system users to asset: {}({}) => {}").format(
|
||||||
system_user.name, username, asset
|
system_user.name, username, asset
|
||||||
)
|
)
|
||||||
return push_system_user_util(system_user, [asset], task_name=task_name, username=username)
|
return push_system_user_util(system_user, [asset], task_name=task_name, username=username)
|
||||||
|
|
||||||
|
|
||||||
|
@shared_task(queue="ansible")
|
||||||
|
@tmp_to_root_org()
|
||||||
|
def push_system_users_a_asset(system_users, asset):
|
||||||
|
for system_user in system_users:
|
||||||
|
push_system_user_a_asset_manual(system_user, asset)
|
||||||
|
|
||||||
|
|
||||||
@shared_task(queue="ansible")
|
@shared_task(queue="ansible")
|
||||||
@tmp_to_root_org()
|
@tmp_to_root_org()
|
||||||
def push_system_user_to_assets(system_user_id, asset_ids, username=None):
|
def push_system_user_to_assets(system_user_id, asset_ids, username=None):
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ logger = get_logger(__name__)
|
|||||||
__all__ = [
|
__all__ = [
|
||||||
'test_system_user_connectivity_util', 'test_system_user_connectivity_manual',
|
'test_system_user_connectivity_util', 'test_system_user_connectivity_manual',
|
||||||
'test_system_user_connectivity_period', 'test_system_user_connectivity_a_asset',
|
'test_system_user_connectivity_period', 'test_system_user_connectivity_a_asset',
|
||||||
|
'test_system_users_connectivity_a_asset'
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -131,6 +132,12 @@ def test_system_user_connectivity_a_asset(system_user, asset):
|
|||||||
test_system_user_connectivity_util(system_user, [asset], task_name)
|
test_system_user_connectivity_util(system_user, [asset], task_name)
|
||||||
|
|
||||||
|
|
||||||
|
@shared_task(queue="ansible")
|
||||||
|
def test_system_users_connectivity_a_asset(system_users, asset):
|
||||||
|
for system_user in system_users:
|
||||||
|
test_system_user_connectivity_a_asset(system_user, asset)
|
||||||
|
|
||||||
|
|
||||||
@shared_task(queue="ansible")
|
@shared_task(queue="ansible")
|
||||||
def test_system_user_connectivity_period():
|
def test_system_user_connectivity_period():
|
||||||
if not const.PERIOD_TASK_ENABLED:
|
if not const.PERIOD_TASK_ENABLED:
|
||||||
|
|||||||
@@ -36,6 +36,10 @@ urlpatterns = [
|
|||||||
path('assets/<uuid:pk>/platform/', api.AssetPlatformRetrieveApi.as_view(), name='asset-platform-detail'),
|
path('assets/<uuid:pk>/platform/', api.AssetPlatformRetrieveApi.as_view(), name='asset-platform-detail'),
|
||||||
path('assets/<uuid:pk>/tasks/', api.AssetTaskCreateApi.as_view(), name='asset-task-create'),
|
path('assets/<uuid:pk>/tasks/', api.AssetTaskCreateApi.as_view(), name='asset-task-create'),
|
||||||
path('assets/tasks/', api.AssetsTaskCreateApi.as_view(), name='assets-task-create'),
|
path('assets/tasks/', api.AssetsTaskCreateApi.as_view(), name='assets-task-create'),
|
||||||
|
path('assets/<uuid:pk>/perm-users/', api.AssetPermUserListApi.as_view(), name='asset-perm-user-list'),
|
||||||
|
path('assets/<uuid:pk>/perm-users/<uuid:perm_user_id>/permissions/', api.AssetPermUserPermissionsListApi.as_view(), name='asset-perm-user-permission-list'),
|
||||||
|
path('assets/<uuid:pk>/perm-user-groups/', api.AssetPermUserGroupListApi.as_view(), name='asset-perm-user-group-list'),
|
||||||
|
path('assets/<uuid:pk>/perm-user-groups/<uuid:perm_user_group_id>/permissions/', api.AssetPermUserGroupPermissionsListApi.as_view(), name='asset-perm-user-group-permission-list'),
|
||||||
|
|
||||||
path('system-users/<uuid:pk>/auth-info/', api.SystemUserAuthInfoApi.as_view(), name='system-user-auth-info'),
|
path('system-users/<uuid:pk>/auth-info/', api.SystemUserAuthInfoApi.as_view(), name='system-user-auth-info'),
|
||||||
path('system-users/<uuid:pk>/assets/', api.SystemUserAssetsListView.as_view(), name='system-user-assets'),
|
path('system-users/<uuid:pk>/assets/', api.SystemUserAssetsListView.as_view(), name='system-user-assets'),
|
||||||
@@ -44,6 +48,7 @@ urlpatterns = [
|
|||||||
path('system-users/<uuid:pk>/temp-auth/', api.SystemUserTempAuthInfoApi.as_view(), name='system-user-asset-temp-info'),
|
path('system-users/<uuid:pk>/temp-auth/', api.SystemUserTempAuthInfoApi.as_view(), name='system-user-asset-temp-info'),
|
||||||
path('system-users/<uuid:pk>/tasks/', api.SystemUserTaskApi.as_view(), name='system-user-task-create'),
|
path('system-users/<uuid:pk>/tasks/', api.SystemUserTaskApi.as_view(), name='system-user-task-create'),
|
||||||
path('system-users/<uuid:pk>/cmd-filter-rules/', api.SystemUserCommandFilterRuleListApi.as_view(), name='system-user-cmd-filter-rule-list'),
|
path('system-users/<uuid:pk>/cmd-filter-rules/', api.SystemUserCommandFilterRuleListApi.as_view(), name='system-user-cmd-filter-rule-list'),
|
||||||
|
path('cmd-filter-rules/', api.SystemUserCommandFilterRuleListApi.as_view(), name='cmd-filter-rules'),
|
||||||
|
|
||||||
path('accounts/tasks/', api.AccountTaskCreateAPI.as_view(), name='account-task-create'),
|
path('accounts/tasks/', api.AccountTaskCreateAPI.as_view(), name='account-task-create'),
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,8 @@ class UserLoginLogViewSet(ListModelMixin, CommonGenericViewSet):
|
|||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
queryset = super().get_queryset()
|
queryset = super().get_queryset()
|
||||||
if not current_org.is_default():
|
if current_org.is_root():
|
||||||
|
return queryset
|
||||||
users = self.get_org_members()
|
users = self.get_org_members()
|
||||||
queryset = queryset.filter(username__in=users)
|
queryset = queryset.filter(username__in=users)
|
||||||
return queryset
|
return queryset
|
||||||
|
|||||||
5
apps/audits/const.py
Normal file
5
apps/audits/const.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
|
DEFAULT_CITY = _("Unknown")
|
||||||
@@ -5,7 +5,7 @@ from django.db.models import Q
|
|||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
|
||||||
from orgs.mixins.models import OrgModelMixin
|
from orgs.mixins.models import OrgModelMixin, Organization
|
||||||
from orgs.utils import current_org
|
from orgs.utils import current_org
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
@@ -63,6 +63,11 @@ class OperateLog(OrgModelMixin):
|
|||||||
def __str__(self):
|
def __str__(self):
|
||||||
return "<{}> {} <{}>".format(self.user, self.action, self.resource)
|
return "<{}> {} <{}>".format(self.user, self.action, self.resource)
|
||||||
|
|
||||||
|
def save(self, *args, **kwargs):
|
||||||
|
if current_org.is_root() and not self.org_id:
|
||||||
|
self.org_id = Organization.ROOT_ID
|
||||||
|
return super(OperateLog, self).save(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
class PasswordChangeLog(models.Model):
|
class PasswordChangeLog(models.Model):
|
||||||
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||||||
|
|||||||
@@ -35,13 +35,14 @@ class UserLoginLogSerializer(serializers.ModelSerializer):
|
|||||||
fields_mini = ['id']
|
fields_mini = ['id']
|
||||||
fields_small = fields_mini + [
|
fields_small = fields_mini + [
|
||||||
'username', 'type', 'type_display', 'ip', 'city', 'user_agent',
|
'username', 'type', 'type_display', 'ip', 'city', 'user_agent',
|
||||||
'mfa', 'mfa_display', 'reason', 'backend',
|
'mfa', 'mfa_display', 'reason', 'reason_display', 'backend',
|
||||||
'status', 'status_display',
|
'status', 'status_display',
|
||||||
'datetime',
|
'datetime',
|
||||||
]
|
]
|
||||||
fields = fields_small
|
fields = fields_small
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
"user_agent": {'label': _('User agent')}
|
"user_agent": {'label': _('User agent')},
|
||||||
|
"reason_display": {'label': _('Reason display')}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
#
|
#
|
||||||
from django.db.models.signals import post_save, post_delete
|
from django.db.models.signals import (
|
||||||
|
post_save, m2m_changed, pre_delete
|
||||||
|
)
|
||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
@@ -11,29 +13,34 @@ from django.utils.translation import ugettext_lazy as _
|
|||||||
from rest_framework.renderers import JSONRenderer
|
from rest_framework.renderers import JSONRenderer
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
|
|
||||||
|
from assets.models import Asset, SystemUser
|
||||||
|
from authentication.signals import post_auth_failed, post_auth_success
|
||||||
|
from authentication.utils import check_different_city_login_if_need
|
||||||
from jumpserver.utils import current_request
|
from jumpserver.utils import current_request
|
||||||
from common.utils import get_request_ip, get_logger, get_syslogger
|
|
||||||
from users.models import User
|
from users.models import User
|
||||||
from users.signals import post_user_change_password
|
from users.signals import post_user_change_password
|
||||||
from authentication.signals import post_auth_failed, post_auth_success
|
|
||||||
from terminal.models import Session, Command
|
from terminal.models import Session, Command
|
||||||
from common.utils.encode import model_to_json
|
|
||||||
from .utils import write_login_log
|
from .utils import write_login_log
|
||||||
from . import models
|
from . import models
|
||||||
|
from .models import OperateLog
|
||||||
|
from orgs.utils import current_org
|
||||||
|
from perms.models import AssetPermission, ApplicationPermission
|
||||||
|
from common.const.signals import POST_ADD, POST_REMOVE, POST_CLEAR
|
||||||
|
from common.utils import get_request_ip, get_logger, get_syslogger
|
||||||
|
from common.utils.encode import model_to_json
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
sys_logger = get_syslogger(__name__)
|
sys_logger = get_syslogger(__name__)
|
||||||
json_render = JSONRenderer()
|
json_render = JSONRenderer()
|
||||||
|
|
||||||
|
|
||||||
MODELS_NEED_RECORD = (
|
MODELS_NEED_RECORD = (
|
||||||
# users
|
# users
|
||||||
'User', 'UserGroup',
|
'User', 'UserGroup',
|
||||||
# acls
|
# acls
|
||||||
'LoginACL', 'LoginAssetACL',
|
'LoginACL', 'LoginAssetACL', 'LoginConfirmSetting',
|
||||||
# assets
|
# assets
|
||||||
'Asset', 'Node', 'AdminUser', 'SystemUser', 'Domain', 'Gateway', 'CommandFilterRule',
|
'Asset', 'Node', 'AdminUser', 'SystemUser', 'Domain', 'Gateway', 'CommandFilterRule',
|
||||||
'CommandFilter', 'Platform',
|
'CommandFilter', 'Platform', 'AuthBook',
|
||||||
# applications
|
# applications
|
||||||
'Application',
|
'Application',
|
||||||
# orgs
|
# orgs
|
||||||
@@ -90,6 +97,123 @@ def create_operate_log(action, sender, resource):
|
|||||||
logger.error("Create operate log error: {}".format(e))
|
logger.error("Create operate log error: {}".format(e))
|
||||||
|
|
||||||
|
|
||||||
|
M2M_NEED_RECORD = {
|
||||||
|
'OrganizationMember': (
|
||||||
|
_('User and Organization'),
|
||||||
|
_('{User} JOINED {Organization}'),
|
||||||
|
_('{User} LEFT {Organization}')
|
||||||
|
),
|
||||||
|
User.groups.through._meta.object_name: (
|
||||||
|
_('User and Group'),
|
||||||
|
_('{User} JOINED {UserGroup}'),
|
||||||
|
_('{User} LEFT {UserGroup}')
|
||||||
|
),
|
||||||
|
SystemUser.assets.through._meta.object_name: (
|
||||||
|
_('Asset and SystemUser'),
|
||||||
|
_('{Asset} ADD {SystemUser}'),
|
||||||
|
_('{Asset} REMOVE {SystemUser}')
|
||||||
|
),
|
||||||
|
Asset.nodes.through._meta.object_name: (
|
||||||
|
_('Node and Asset'),
|
||||||
|
_('{Node} ADD {Asset}'),
|
||||||
|
_('{Node} REMOVE {Asset}')
|
||||||
|
),
|
||||||
|
AssetPermission.users.through._meta.object_name: (
|
||||||
|
_('User asset permissions'),
|
||||||
|
_('{AssetPermission} ADD {User}'),
|
||||||
|
_('{AssetPermission} REMOVE {User}'),
|
||||||
|
),
|
||||||
|
AssetPermission.user_groups.through._meta.object_name: (
|
||||||
|
_('User group asset permissions'),
|
||||||
|
_('{AssetPermission} ADD {UserGroup}'),
|
||||||
|
_('{AssetPermission} REMOVE {UserGroup}'),
|
||||||
|
),
|
||||||
|
AssetPermission.assets.through._meta.object_name: (
|
||||||
|
_('Asset permission'),
|
||||||
|
_('{AssetPermission} ADD {Asset}'),
|
||||||
|
_('{AssetPermission} REMOVE {Asset}'),
|
||||||
|
),
|
||||||
|
AssetPermission.nodes.through._meta.object_name: (
|
||||||
|
_('Node permission'),
|
||||||
|
_('{AssetPermission} ADD {Node}'),
|
||||||
|
_('{AssetPermission} REMOVE {Node}'),
|
||||||
|
),
|
||||||
|
AssetPermission.system_users.through._meta.object_name: (
|
||||||
|
_('Asset permission and SystemUser'),
|
||||||
|
_('{AssetPermission} ADD {SystemUser}'),
|
||||||
|
_('{AssetPermission} REMOVE {SystemUser}'),
|
||||||
|
),
|
||||||
|
ApplicationPermission.users.through._meta.object_name: (
|
||||||
|
_('User application permissions'),
|
||||||
|
_('{ApplicationPermission} ADD {User}'),
|
||||||
|
_('{ApplicationPermission} REMOVE {User}'),
|
||||||
|
),
|
||||||
|
ApplicationPermission.user_groups.through._meta.object_name: (
|
||||||
|
_('User group application permissions'),
|
||||||
|
_('{ApplicationPermission} ADD {UserGroup}'),
|
||||||
|
_('{ApplicationPermission} REMOVE {UserGroup}'),
|
||||||
|
),
|
||||||
|
ApplicationPermission.applications.through._meta.object_name: (
|
||||||
|
_('Application permission'),
|
||||||
|
_('{ApplicationPermission} ADD {Application}'),
|
||||||
|
_('{ApplicationPermission} REMOVE {Application}'),
|
||||||
|
),
|
||||||
|
ApplicationPermission.system_users.through._meta.object_name: (
|
||||||
|
_('Application permission and SystemUser'),
|
||||||
|
_('{ApplicationPermission} ADD {SystemUser}'),
|
||||||
|
_('{ApplicationPermission} REMOVE {SystemUser}'),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
M2M_ACTION = {
|
||||||
|
POST_ADD: 'add',
|
||||||
|
POST_REMOVE: 'remove',
|
||||||
|
POST_CLEAR: 'remove',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(m2m_changed)
|
||||||
|
def on_m2m_changed(sender, action, instance, reverse, model, pk_set, **kwargs):
|
||||||
|
if action not in M2M_ACTION:
|
||||||
|
return
|
||||||
|
|
||||||
|
user = current_request.user if current_request else None
|
||||||
|
if not user or not user.is_authenticated:
|
||||||
|
return
|
||||||
|
|
||||||
|
sender_name = sender._meta.object_name
|
||||||
|
if sender_name in M2M_NEED_RECORD:
|
||||||
|
action = M2M_ACTION[action]
|
||||||
|
org_id = current_org.id
|
||||||
|
remote_addr = get_request_ip(current_request)
|
||||||
|
user = str(user)
|
||||||
|
resource_type, resource_tmpl_add, resource_tmpl_remove = M2M_NEED_RECORD[sender_name]
|
||||||
|
if action == 'add':
|
||||||
|
resource_tmpl = resource_tmpl_add
|
||||||
|
elif action == 'remove':
|
||||||
|
resource_tmpl = resource_tmpl_remove
|
||||||
|
|
||||||
|
to_create = []
|
||||||
|
objs = model.objects.filter(pk__in=pk_set)
|
||||||
|
|
||||||
|
instance_name = instance._meta.object_name
|
||||||
|
instance_value = str(instance)
|
||||||
|
|
||||||
|
model_name = model._meta.object_name
|
||||||
|
|
||||||
|
for obj in objs:
|
||||||
|
resource = resource_tmpl.format(**{
|
||||||
|
instance_name: instance_value,
|
||||||
|
model_name: str(obj)
|
||||||
|
})[:128] # `resource` 字段只有 128 个字符长 😔
|
||||||
|
|
||||||
|
to_create.append(OperateLog(
|
||||||
|
user=user, action=action, resource_type=resource_type,
|
||||||
|
resource=resource, remote_addr=remote_addr, org_id=org_id
|
||||||
|
))
|
||||||
|
OperateLog.objects.bulk_create(to_create)
|
||||||
|
|
||||||
|
|
||||||
@receiver(post_save)
|
@receiver(post_save)
|
||||||
def on_object_created_or_update(sender, instance=None, created=False, update_fields=None, **kwargs):
|
def on_object_created_or_update(sender, instance=None, created=False, update_fields=None, **kwargs):
|
||||||
# last_login 改变是最后登录日期, 每次登录都会改变
|
# last_login 改变是最后登录日期, 每次登录都会改变
|
||||||
@@ -103,7 +227,7 @@ def on_object_created_or_update(sender, instance=None, created=False, update_fie
|
|||||||
create_operate_log(action, sender, instance)
|
create_operate_log(action, sender, instance)
|
||||||
|
|
||||||
|
|
||||||
@receiver(post_delete)
|
@receiver(pre_delete)
|
||||||
def on_object_delete(sender, instance=None, **kwargs):
|
def on_object_delete(sender, instance=None, **kwargs):
|
||||||
create_operate_log(models.OperateLog.ACTION_DELETE, sender, instance)
|
create_operate_log(models.OperateLog.ACTION_DELETE, sender, instance)
|
||||||
|
|
||||||
@@ -180,6 +304,7 @@ def generate_data(username, request, login_type=None):
|
|||||||
@receiver(post_auth_success)
|
@receiver(post_auth_success)
|
||||||
def on_user_auth_success(sender, user, request, login_type=None, **kwargs):
|
def on_user_auth_success(sender, user, request, login_type=None, **kwargs):
|
||||||
logger.debug('User login success: {}'.format(user.username))
|
logger.debug('User login success: {}'.format(user.username))
|
||||||
|
check_different_city_login_if_need(user, request)
|
||||||
data = generate_data(user.username, request, login_type=login_type)
|
data = generate_data(user.username, request, login_type=login_type)
|
||||||
data.update({'mfa': int(user.mfa_enabled), 'status': True})
|
data.update({'mfa': int(user.mfa_enabled), 'status': True})
|
||||||
write_login_log(**data)
|
write_login_log(**data)
|
||||||
|
|||||||
@@ -5,14 +5,12 @@ from django.utils import timezone
|
|||||||
from celery import shared_task
|
from celery import shared_task
|
||||||
|
|
||||||
from ops.celery.decorator import (
|
from ops.celery.decorator import (
|
||||||
register_as_period_task, after_app_shutdown_clean_periodic
|
register_as_period_task
|
||||||
)
|
)
|
||||||
from .models import UserLoginLog, OperateLog
|
from .models import UserLoginLog, OperateLog
|
||||||
from common.utils import get_log_keep_day
|
from common.utils import get_log_keep_day
|
||||||
|
|
||||||
|
|
||||||
@shared_task
|
|
||||||
@after_app_shutdown_clean_periodic
|
|
||||||
def clean_login_log_period():
|
def clean_login_log_period():
|
||||||
now = timezone.now()
|
now = timezone.now()
|
||||||
days = get_log_keep_day('LOGIN_LOG_KEEP_DAYS')
|
days = get_log_keep_day('LOGIN_LOG_KEEP_DAYS')
|
||||||
@@ -20,8 +18,6 @@ def clean_login_log_period():
|
|||||||
UserLoginLog.objects.filter(datetime__lt=expired_day).delete()
|
UserLoginLog.objects.filter(datetime__lt=expired_day).delete()
|
||||||
|
|
||||||
|
|
||||||
@shared_task
|
|
||||||
@after_app_shutdown_clean_periodic
|
|
||||||
def clean_operation_log_period():
|
def clean_operation_log_period():
|
||||||
now = timezone.now()
|
now = timezone.now()
|
||||||
days = get_log_keep_day('OPERATE_LOG_KEEP_DAYS')
|
days = get_log_keep_day('OPERATE_LOG_KEEP_DAYS')
|
||||||
@@ -29,7 +25,6 @@ def clean_operation_log_period():
|
|||||||
OperateLog.objects.filter(datetime__lt=expired_day).delete()
|
OperateLog.objects.filter(datetime__lt=expired_day).delete()
|
||||||
|
|
||||||
|
|
||||||
@shared_task
|
|
||||||
def clean_ftp_log_period():
|
def clean_ftp_log_period():
|
||||||
now = timezone.now()
|
now = timezone.now()
|
||||||
days = get_log_keep_day('FTP_LOG_KEEP_DAYS')
|
days = get_log_keep_day('FTP_LOG_KEEP_DAYS')
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import csv
|
import csv
|
||||||
import codecs
|
import codecs
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
from django.utils.translation import ugettext as _
|
|
||||||
|
|
||||||
|
from .const import DEFAULT_CITY
|
||||||
from common.utils import validate_ip, get_ip_city
|
from common.utils import validate_ip, get_ip_city
|
||||||
|
|
||||||
|
|
||||||
@@ -27,12 +27,12 @@ def write_content_to_excel(response, header=None, login_logs=None, fields=None):
|
|||||||
|
|
||||||
def write_login_log(*args, **kwargs):
|
def write_login_log(*args, **kwargs):
|
||||||
from audits.models import UserLoginLog
|
from audits.models import UserLoginLog
|
||||||
default_city = _("Unknown")
|
|
||||||
ip = kwargs.get('ip') or ''
|
ip = kwargs.get('ip') or ''
|
||||||
if not (ip and validate_ip(ip)):
|
if not (ip and validate_ip(ip)):
|
||||||
ip = ip[:15]
|
ip = ip[:15]
|
||||||
city = default_city
|
city = DEFAULT_CITY
|
||||||
else:
|
else:
|
||||||
city = get_ip_city(ip) or default_city
|
city = get_ip_city(ip) or DEFAULT_CITY
|
||||||
kwargs.update({'ip': ip, 'city': city})
|
kwargs.update({'ip': ip, 'city': city})
|
||||||
UserLoginLog.objects.create(**kwargs)
|
UserLoginLog.objects.create(**kwargs)
|
||||||
|
|||||||
@@ -9,4 +9,5 @@ from .login_confirm import *
|
|||||||
from .sso import *
|
from .sso import *
|
||||||
from .wecom import *
|
from .wecom import *
|
||||||
from .dingtalk import *
|
from .dingtalk import *
|
||||||
|
from .feishu import *
|
||||||
from .password import *
|
from .password import *
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
#
|
#
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
|
import json
|
||||||
|
from typing import Callable
|
||||||
|
import os
|
||||||
|
import base64
|
||||||
|
import ctypes
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
@@ -8,99 +13,58 @@ from django.shortcuts import get_object_or_404
|
|||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
from django.utils.translation import ugettext as _
|
from django.utils.translation import ugettext as _
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.request import Request
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.exceptions import PermissionDenied
|
from rest_framework.exceptions import PermissionDenied
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from applications.models import Application
|
||||||
from authentication.signals import post_auth_failed, post_auth_success
|
from authentication.signals import post_auth_failed, post_auth_success
|
||||||
from common.utils import get_logger, random_string
|
from common.utils import get_logger, random_string
|
||||||
from common.drf.api import SerializerMixin
|
from common.mixins.api import SerializerMixin
|
||||||
from common.permissions import IsSuperUserOrAppUser, IsValidUser, IsSuperUser
|
from common.permissions import IsSuperUserOrAppUser, IsValidUser, IsSuperUser
|
||||||
|
from common.utils.common import get_file_by_arch
|
||||||
from orgs.mixins.api import RootOrgViewMixin
|
from orgs.mixins.api import RootOrgViewMixin
|
||||||
|
from common.http import is_true
|
||||||
|
from perms.utils.asset.permission import get_asset_system_user_ids_with_actions_by_user
|
||||||
|
from perms.models.asset_permission import Action
|
||||||
|
|
||||||
from ..serializers import (
|
from ..serializers import (
|
||||||
ConnectionTokenSerializer, ConnectionTokenSecretSerializer,
|
ConnectionTokenSerializer, ConnectionTokenSecretSerializer,
|
||||||
RDPFileSerializer
|
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
__all__ = ['UserConnectionTokenViewSet']
|
__all__ = ['UserConnectionTokenViewSet']
|
||||||
|
|
||||||
|
|
||||||
class UserConnectionTokenViewSet(RootOrgViewMixin, SerializerMixin, GenericViewSet):
|
class ClientProtocolMixin:
|
||||||
permission_classes = (IsSuperUserOrAppUser,)
|
request: Request
|
||||||
serializer_classes = {
|
get_serializer: Callable
|
||||||
'default': ConnectionTokenSerializer,
|
create_token: Callable
|
||||||
'get_secret_detail': ConnectionTokenSecretSerializer,
|
|
||||||
'get_rdp_file': RDPFileSerializer
|
|
||||||
}
|
|
||||||
CACHE_KEY_PREFIX = 'CONNECTION_TOKEN_{}'
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def check_resource_permission(user, asset, application, system_user):
|
|
||||||
from perms.utils.asset import has_asset_system_permission
|
|
||||||
from perms.utils.application import has_application_system_permission
|
|
||||||
if asset and not has_asset_system_permission(user, asset, system_user):
|
|
||||||
error = f'User not has this asset and system user permission: ' \
|
|
||||||
f'user={user.id} system_user={system_user.id} asset={asset.id}'
|
|
||||||
raise PermissionDenied(error)
|
|
||||||
if application and not has_application_system_permission(user, application, system_user):
|
|
||||||
error = f'User not has this application and system user permission: ' \
|
|
||||||
f'user={user.id} system_user={system_user.id} application={application.id}'
|
|
||||||
raise PermissionDenied(error)
|
|
||||||
return True
|
|
||||||
|
|
||||||
def create_token(self, user, asset, application, system_user, ttl=5*60):
|
|
||||||
if not self.request.user.is_superuser and user != self.request.user:
|
|
||||||
raise PermissionDenied('Only super user can create user token')
|
|
||||||
self.check_resource_permission(user, asset, application, system_user)
|
|
||||||
token = random_string(36)
|
|
||||||
value = {
|
|
||||||
'user': str(user.id),
|
|
||||||
'username': user.username,
|
|
||||||
'system_user': str(system_user.id),
|
|
||||||
'system_user_name': system_user.name
|
|
||||||
}
|
|
||||||
|
|
||||||
if asset:
|
|
||||||
value.update({
|
|
||||||
'type': 'asset',
|
|
||||||
'asset': str(asset.id),
|
|
||||||
'hostname': asset.hostname,
|
|
||||||
})
|
|
||||||
elif application:
|
|
||||||
value.update({
|
|
||||||
'type': 'application',
|
|
||||||
'application': application.id,
|
|
||||||
'application_name': str(application)
|
|
||||||
})
|
|
||||||
|
|
||||||
key = self.CACHE_KEY_PREFIX.format(token)
|
|
||||||
cache.set(key, value, timeout=ttl)
|
|
||||||
return token
|
|
||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
serializer = self.get_serializer(data=request.data)
|
|
||||||
serializer.is_valid(raise_exception=True)
|
|
||||||
|
|
||||||
|
def get_request_resource(self, serializer):
|
||||||
asset = serializer.validated_data.get('asset')
|
asset = serializer.validated_data.get('asset')
|
||||||
application = serializer.validated_data.get('application')
|
application = serializer.validated_data.get('application')
|
||||||
system_user = serializer.validated_data['system_user']
|
system_user = serializer.validated_data['system_user']
|
||||||
user = serializer.validated_data.get('user')
|
|
||||||
token = self.create_token(user, asset, application, system_user)
|
|
||||||
return Response({"token": token}, status=201)
|
|
||||||
|
|
||||||
@action(methods=['POST', 'GET'], detail=False, url_path='rdp/file', permission_classes=[IsValidUser])
|
user = serializer.validated_data.get('user')
|
||||||
def get_rdp_file(self, request, *args, **kwargs):
|
if not user or not self.request.user.is_superuser:
|
||||||
|
user = self.request.user
|
||||||
|
return asset, application, system_user, user
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def parse_env_bool(env_key, env_default, true_value, false_value):
|
||||||
|
return true_value if is_true(os.getenv(env_key, env_default)) else false_value
|
||||||
|
|
||||||
|
def get_rdp_file_content(self, serializer):
|
||||||
options = {
|
options = {
|
||||||
'full address:s': '',
|
'full address:s': '',
|
||||||
'username:s': '',
|
'username:s': '',
|
||||||
'screen mode id:i': '0',
|
# 'screen mode id:i': '1',
|
||||||
# 'desktopwidth:i': '1280',
|
# 'desktopwidth:i': '1280',
|
||||||
# 'desktopheight:i': '800',
|
# 'desktopheight:i': '800',
|
||||||
'use multimon:i': '1',
|
'use multimon:i': '0',
|
||||||
'session bpp:i': '32',
|
'session bpp:i': '32',
|
||||||
'audiomode:i': '0',
|
'audiomode:i': '0',
|
||||||
'disable wallpaper:i': '0',
|
'disable wallpaper:i': '0',
|
||||||
@@ -120,53 +84,151 @@ class UserConnectionTokenViewSet(RootOrgViewMixin, SerializerMixin, GenericViewS
|
|||||||
'bookmarktype:i': '3',
|
'bookmarktype:i': '3',
|
||||||
'use redirection server name:i': '0',
|
'use redirection server name:i': '0',
|
||||||
'smart sizing:i': '0',
|
'smart sizing:i': '0',
|
||||||
|
#'drivestoredirect:s': '*',
|
||||||
# 'domain:s': ''
|
# 'domain:s': ''
|
||||||
# 'alternate shell:s:': '||MySQLWorkbench',
|
# 'alternate shell:s:': '||MySQLWorkbench',
|
||||||
# 'remoteapplicationname:s': 'Firefox',
|
# 'remoteapplicationname:s': 'Firefox',
|
||||||
# 'remoteapplicationcmdline:s': '',
|
# 'remoteapplicationcmdline:s': '',
|
||||||
}
|
}
|
||||||
if self.request.method == 'GET':
|
|
||||||
data = self.request.query_params
|
|
||||||
else:
|
|
||||||
data = request.data
|
|
||||||
serializer = self.get_serializer(data=data)
|
|
||||||
serializer.is_valid(raise_exception=True)
|
|
||||||
|
|
||||||
asset = serializer.validated_data.get('asset')
|
asset, application, system_user, user = self.get_request_resource(serializer)
|
||||||
application = serializer.validated_data.get('application')
|
height = self.request.query_params.get('height')
|
||||||
system_user = serializer.validated_data['system_user']
|
width = self.request.query_params.get('width')
|
||||||
height = serializer.validated_data.get('height')
|
full_screen = is_true(self.request.query_params.get('full_screen'))
|
||||||
width = serializer.validated_data.get('width')
|
drives_redirect = is_true(self.request.query_params.get('drives_redirect'))
|
||||||
user = request.user
|
|
||||||
token = self.create_token(user, asset, application, system_user)
|
token = self.create_token(user, asset, application, system_user)
|
||||||
|
|
||||||
|
# 设置磁盘挂载
|
||||||
|
if drives_redirect and asset:
|
||||||
|
systemuser_actions_mapper = get_asset_system_user_ids_with_actions_by_user(user, asset)
|
||||||
|
actions = systemuser_actions_mapper.get(system_user.id, 0)
|
||||||
|
if actions & Action.UPDOWNLOAD:
|
||||||
|
options['drivestoredirect:s'] = '*'
|
||||||
|
|
||||||
|
# 全屏
|
||||||
|
options['screen mode id:i'] = '2' if full_screen else '1'
|
||||||
|
|
||||||
|
# RDP Server 地址
|
||||||
address = settings.TERMINAL_RDP_ADDR
|
address = settings.TERMINAL_RDP_ADDR
|
||||||
if not address or address == 'localhost:3389':
|
if not address or address == 'localhost:3389':
|
||||||
address = request.get_host().split(':')[0] + ':3389'
|
address = self.request.get_host().split(':')[0] + ':3389'
|
||||||
options['full address:s'] = address
|
options['full address:s'] = address
|
||||||
|
# 用户名
|
||||||
options['username:s'] = '{}|{}'.format(user.username, token)
|
options['username:s'] = '{}|{}'.format(user.username, token)
|
||||||
if system_user.ad_domain:
|
if system_user.ad_domain:
|
||||||
options['domain:s'] = system_user.ad_domain
|
options['domain:s'] = system_user.ad_domain
|
||||||
|
# 宽高
|
||||||
if width and height:
|
if width and height:
|
||||||
options['desktopwidth:i'] = width
|
options['desktopwidth:i'] = width
|
||||||
options['desktopheight:i'] = height
|
options['desktopheight:i'] = height
|
||||||
else:
|
else:
|
||||||
options['smart sizing:i'] = '1'
|
options['smart sizing:i'] = '1'
|
||||||
data = ''
|
|
||||||
for k, v in options.items():
|
options['session bpp:i'] = os.getenv('JUMPSERVER_COLOR_DEPTH', '32')
|
||||||
data += f'{k}:{v}\n'
|
options['audiomode:i'] = self.parse_env_bool('JUMPSERVER_DISABLE_AUDIO', 'false', '2', '0')
|
||||||
|
|
||||||
if asset:
|
if asset:
|
||||||
name = asset.hostname
|
name = asset.hostname
|
||||||
elif application:
|
elif application:
|
||||||
name = application.name
|
name = application.name
|
||||||
|
application.get_rdp_remote_app_setting()
|
||||||
|
|
||||||
|
app = f'||jmservisor'
|
||||||
|
options['remoteapplicationmode:i'] = '1'
|
||||||
|
options['alternate shell:s'] = app
|
||||||
|
options['remoteapplicationprogram:s'] = app
|
||||||
|
options['remoteapplicationname:s'] = name
|
||||||
|
options['remoteapplicationcmdline:s'] = '- ' + self.get_encrypt_cmdline(application)
|
||||||
else:
|
else:
|
||||||
name = '*'
|
name = '*'
|
||||||
|
|
||||||
|
content = ''
|
||||||
|
for k, v in options.items():
|
||||||
|
content += f'{k}:{v}\n'
|
||||||
|
return name, content
|
||||||
|
|
||||||
|
def get_encrypt_cmdline(self, app: Application):
|
||||||
|
|
||||||
|
parameters = app.get_rdp_remote_app_setting()['parameters']
|
||||||
|
parameters = parameters.encode('ascii')
|
||||||
|
|
||||||
|
lib_path = get_file_by_arch('xpack/libs', 'librailencrypt.so')
|
||||||
|
lib = ctypes.CDLL(lib_path)
|
||||||
|
lib.encrypt.argtypes = [ctypes.c_char_p, ctypes.c_int]
|
||||||
|
lib.encrypt.restype = ctypes.c_char_p
|
||||||
|
|
||||||
|
rst = lib.encrypt(parameters, len(parameters))
|
||||||
|
rst = rst.decode('ascii')
|
||||||
|
return rst
|
||||||
|
|
||||||
|
@action(methods=['POST', 'GET'], detail=False, url_path='rdp/file', permission_classes=[IsValidUser])
|
||||||
|
def get_rdp_file(self, request, *args, **kwargs):
|
||||||
|
if self.request.method == 'GET':
|
||||||
|
data = self.request.query_params
|
||||||
|
else:
|
||||||
|
data = self.request.data
|
||||||
|
serializer = self.get_serializer(data=data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
name, data = self.get_rdp_file_content(serializer)
|
||||||
response = HttpResponse(data, content_type='application/octet-stream')
|
response = HttpResponse(data, content_type='application/octet-stream')
|
||||||
filename = "{}-{}-jumpserver.rdp".format(user.username, name)
|
filename = "{}-{}-jumpserver.rdp".format(self.request.user.username, name)
|
||||||
filename = urllib.parse.quote(filename)
|
filename = urllib.parse.quote(filename)
|
||||||
response['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'%s' % filename
|
response['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'%s' % filename
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
def get_valid_serializer(self):
|
||||||
|
if self.request.method == 'GET':
|
||||||
|
data = self.request.query_params
|
||||||
|
else:
|
||||||
|
data = self.request.data
|
||||||
|
serializer = self.get_serializer(data=data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
return serializer
|
||||||
|
|
||||||
|
def get_client_protocol_data(self, serializer):
|
||||||
|
asset, application, system_user, user = self.get_request_resource(serializer)
|
||||||
|
protocol = system_user.protocol
|
||||||
|
username = user.username
|
||||||
|
|
||||||
|
if protocol == 'rdp':
|
||||||
|
name, config = self.get_rdp_file_content(serializer)
|
||||||
|
elif protocol == 'ssh':
|
||||||
|
# Todo:
|
||||||
|
name = ''
|
||||||
|
config = 'ssh://system_user@asset@user@jumpserver-ssh'
|
||||||
|
else:
|
||||||
|
raise ValueError('Protocol not support: {}'.format(protocol))
|
||||||
|
|
||||||
|
filename = "{}-{}-jumpserver".format(username, name)
|
||||||
|
data = {
|
||||||
|
"filename": filename,
|
||||||
|
"protocol": system_user.protocol,
|
||||||
|
"username": username,
|
||||||
|
"config": config
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
|
||||||
|
@action(methods=['POST', 'GET'], detail=False, url_path='client-url', permission_classes=[IsValidUser])
|
||||||
|
def get_client_protocol_url(self, request, *args, **kwargs):
|
||||||
|
serializer = self.get_valid_serializer()
|
||||||
|
try:
|
||||||
|
protocol_data = self.get_client_protocol_data(serializer)
|
||||||
|
except ValueError as e:
|
||||||
|
return Response({'error': str(e)}, status=401)
|
||||||
|
|
||||||
|
protocol_data = json.dumps(protocol_data).encode()
|
||||||
|
protocol_data = base64.b64encode(protocol_data).decode()
|
||||||
|
data = {
|
||||||
|
'url': 'jms://{}'.format(protocol_data),
|
||||||
|
}
|
||||||
|
return Response(data=data)
|
||||||
|
|
||||||
|
|
||||||
|
class SecretDetailMixin:
|
||||||
|
valid_token: Callable
|
||||||
|
request: Request
|
||||||
|
get_serializer: Callable
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _get_application_secret_detail(application):
|
def _get_application_secret_detail(application):
|
||||||
from perms.models import Action
|
from perms.models import Action
|
||||||
@@ -212,41 +274,6 @@ class UserConnectionTokenViewSet(RootOrgViewMixin, SerializerMixin, GenericViewS
|
|||||||
'actions': actions,
|
'actions': actions,
|
||||||
}
|
}
|
||||||
|
|
||||||
def valid_token(self, token):
|
|
||||||
from users.models import User
|
|
||||||
from assets.models import SystemUser, Asset
|
|
||||||
from applications.models import Application
|
|
||||||
from perms.utils.asset.permission import validate_permission as asset_validate_permission
|
|
||||||
from perms.utils.application.permission import validate_permission as app_validate_permission
|
|
||||||
|
|
||||||
key = self.CACHE_KEY_PREFIX.format(token)
|
|
||||||
value = cache.get(key, None)
|
|
||||||
if not value:
|
|
||||||
raise serializers.ValidationError('Token not found')
|
|
||||||
|
|
||||||
user = get_object_or_404(User, id=value.get('user'))
|
|
||||||
if not user.is_valid:
|
|
||||||
raise serializers.ValidationError("User not valid, disabled or expired")
|
|
||||||
|
|
||||||
system_user = get_object_or_404(SystemUser, id=value.get('system_user'))
|
|
||||||
|
|
||||||
asset = None
|
|
||||||
app = None
|
|
||||||
if value.get('type') == 'asset':
|
|
||||||
asset = get_object_or_404(Asset, id=value.get('asset'))
|
|
||||||
if not asset.is_active:
|
|
||||||
raise serializers.ValidationError("Asset disabled")
|
|
||||||
|
|
||||||
has_perm, expired_at = asset_validate_permission(user, asset, system_user, 'connect')
|
|
||||||
else:
|
|
||||||
app = get_object_or_404(Application, id=value.get('application'))
|
|
||||||
has_perm, expired_at = app_validate_permission(user, app, system_user)
|
|
||||||
|
|
||||||
if not has_perm:
|
|
||||||
raise serializers.ValidationError('Permission expired or invalid')
|
|
||||||
|
|
||||||
return value, user, system_user, asset, app, expired_at
|
|
||||||
|
|
||||||
@action(methods=['POST'], detail=False, permission_classes=[IsSuperUserOrAppUser], url_path='secret-info/detail')
|
@action(methods=['POST'], detail=False, permission_classes=[IsSuperUserOrAppUser], url_path='secret-info/detail')
|
||||||
def get_secret_detail(self, request, *args, **kwargs):
|
def get_secret_detail(self, request, *args, **kwargs):
|
||||||
token = request.data.get('token', '')
|
token = request.data.get('token', '')
|
||||||
@@ -267,7 +294,7 @@ class UserConnectionTokenViewSet(RootOrgViewMixin, SerializerMixin, GenericViewS
|
|||||||
data.update(asset_detail)
|
data.update(asset_detail)
|
||||||
else:
|
else:
|
||||||
app_detail = self._get_application_secret_detail(app)
|
app_detail = self._get_application_secret_detail(app)
|
||||||
system_user.load_app_more_auth(app.id, user.id)
|
system_user.load_app_more_auth(app.id, user.username, user.id)
|
||||||
data['type'] = 'application'
|
data['type'] = 'application'
|
||||||
data.update(app_detail)
|
data.update(app_detail)
|
||||||
|
|
||||||
@@ -277,6 +304,102 @@ class UserConnectionTokenViewSet(RootOrgViewMixin, SerializerMixin, GenericViewS
|
|||||||
serializer = self.get_serializer(data)
|
serializer = self.get_serializer(data)
|
||||||
return Response(data=serializer.data, status=200)
|
return Response(data=serializer.data, status=200)
|
||||||
|
|
||||||
|
|
||||||
|
class UserConnectionTokenViewSet(
|
||||||
|
RootOrgViewMixin, SerializerMixin, ClientProtocolMixin,
|
||||||
|
SecretDetailMixin, GenericViewSet
|
||||||
|
):
|
||||||
|
permission_classes = (IsSuperUserOrAppUser,)
|
||||||
|
serializer_classes = {
|
||||||
|
'default': ConnectionTokenSerializer,
|
||||||
|
'get_secret_detail': ConnectionTokenSecretSerializer,
|
||||||
|
}
|
||||||
|
CACHE_KEY_PREFIX = 'CONNECTION_TOKEN_{}'
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def check_resource_permission(user, asset, application, system_user):
|
||||||
|
from perms.utils.asset import has_asset_system_permission
|
||||||
|
from perms.utils.application import has_application_system_permission
|
||||||
|
|
||||||
|
if asset and not has_asset_system_permission(user, asset, system_user):
|
||||||
|
error = f'User not has this asset and system user permission: ' \
|
||||||
|
f'user={user.id} system_user={system_user.id} asset={asset.id}'
|
||||||
|
raise PermissionDenied(error)
|
||||||
|
if application and not has_application_system_permission(user, application, system_user):
|
||||||
|
error = f'User not has this application and system user permission: ' \
|
||||||
|
f'user={user.id} system_user={system_user.id} application={application.id}'
|
||||||
|
raise PermissionDenied(error)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def create_token(self, user, asset, application, system_user, ttl=5 * 60):
|
||||||
|
if not self.request.user.is_superuser and user != self.request.user:
|
||||||
|
raise PermissionDenied('Only super user can create user token')
|
||||||
|
self.check_resource_permission(user, asset, application, system_user)
|
||||||
|
token = random_string(36)
|
||||||
|
value = {
|
||||||
|
'user': str(user.id),
|
||||||
|
'username': user.username,
|
||||||
|
'system_user': str(system_user.id),
|
||||||
|
'system_user_name': system_user.name
|
||||||
|
}
|
||||||
|
|
||||||
|
if asset:
|
||||||
|
value.update({
|
||||||
|
'type': 'asset',
|
||||||
|
'asset': str(asset.id),
|
||||||
|
'hostname': asset.hostname,
|
||||||
|
})
|
||||||
|
elif application:
|
||||||
|
value.update({
|
||||||
|
'type': 'application',
|
||||||
|
'application': application.id,
|
||||||
|
'application_name': str(application)
|
||||||
|
})
|
||||||
|
|
||||||
|
key = self.CACHE_KEY_PREFIX.format(token)
|
||||||
|
cache.set(key, value, timeout=ttl)
|
||||||
|
return token
|
||||||
|
|
||||||
|
def create(self, request, *args, **kwargs):
|
||||||
|
serializer = self.get_serializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
|
||||||
|
asset, application, system_user, user = self.get_request_resource(serializer)
|
||||||
|
token = self.create_token(user, asset, application, system_user)
|
||||||
|
return Response({"token": token}, status=201)
|
||||||
|
|
||||||
|
def valid_token(self, token):
|
||||||
|
from users.models import User
|
||||||
|
from assets.models import SystemUser, Asset
|
||||||
|
from applications.models import Application
|
||||||
|
from perms.utils.asset.permission import validate_permission as asset_validate_permission
|
||||||
|
from perms.utils.application.permission import validate_permission as app_validate_permission
|
||||||
|
|
||||||
|
key = self.CACHE_KEY_PREFIX.format(token)
|
||||||
|
value = cache.get(key, None)
|
||||||
|
if not value:
|
||||||
|
raise serializers.ValidationError('Token not found')
|
||||||
|
|
||||||
|
user = get_object_or_404(User, id=value.get('user'))
|
||||||
|
if not user.is_valid:
|
||||||
|
raise serializers.ValidationError("User not valid, disabled or expired")
|
||||||
|
|
||||||
|
system_user = get_object_or_404(SystemUser, id=value.get('system_user'))
|
||||||
|
asset = None
|
||||||
|
app = None
|
||||||
|
if value.get('type') == 'asset':
|
||||||
|
asset = get_object_or_404(Asset, id=value.get('asset'))
|
||||||
|
if not asset.is_active:
|
||||||
|
raise serializers.ValidationError("Asset disabled")
|
||||||
|
has_perm, expired_at = asset_validate_permission(user, asset, system_user, 'connect')
|
||||||
|
else:
|
||||||
|
app = get_object_or_404(Application, id=value.get('application'))
|
||||||
|
has_perm, expired_at = app_validate_permission(user, app, system_user)
|
||||||
|
|
||||||
|
if not has_perm:
|
||||||
|
raise serializers.ValidationError('Permission expired or invalid')
|
||||||
|
return value, user, system_user, asset, app, expired_at
|
||||||
|
|
||||||
def get_permissions(self):
|
def get_permissions(self):
|
||||||
if self.action in ["create", "get_rdp_file"]:
|
if self.action in ["create", "get_rdp_file"]:
|
||||||
if self.request.data.get('user', None):
|
if self.request.data.get('user', None):
|
||||||
|
|||||||
45
apps/authentication/api/feishu.py
Normal file
45
apps/authentication/api/feishu.py
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
from rest_framework.views import APIView
|
||||||
|
from rest_framework.request import Request
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
from users.permissions import IsAuthPasswdTimeValid
|
||||||
|
from users.models import User
|
||||||
|
from common.utils import get_logger
|
||||||
|
from common.permissions import IsOrgAdmin
|
||||||
|
from common.mixins.api import RoleUserMixin, RoleAdminMixin
|
||||||
|
from authentication import errors
|
||||||
|
|
||||||
|
logger = get_logger(__file__)
|
||||||
|
|
||||||
|
|
||||||
|
class FeiShuQRUnBindBase(APIView):
|
||||||
|
user: User
|
||||||
|
|
||||||
|
def post(self, request: Request, **kwargs):
|
||||||
|
user = self.user
|
||||||
|
|
||||||
|
if not user.feishu_id:
|
||||||
|
raise errors.FeiShuNotBound
|
||||||
|
|
||||||
|
user.feishu_id = None
|
||||||
|
user.save()
|
||||||
|
return Response()
|
||||||
|
|
||||||
|
|
||||||
|
class FeiShuQRUnBindForUserApi(RoleUserMixin, FeiShuQRUnBindBase):
|
||||||
|
permission_classes = (IsAuthPasswdTimeValid,)
|
||||||
|
|
||||||
|
|
||||||
|
class FeiShuQRUnBindForAdminApi(RoleAdminMixin, FeiShuQRUnBindBase):
|
||||||
|
user_id_url_kwarg = 'user_id'
|
||||||
|
permission_classes = (IsOrgAdmin,)
|
||||||
|
|
||||||
|
|
||||||
|
class FeiShuEventSubscriptionCallback(APIView):
|
||||||
|
"""
|
||||||
|
# https://open.feishu.cn/document/ukTMukTMukTM/uUTNz4SN1MjL1UzM
|
||||||
|
"""
|
||||||
|
permission_classes = ()
|
||||||
|
|
||||||
|
def post(self, request: Request, *args, **kwargs):
|
||||||
|
return Response(data=request.data)
|
||||||
@@ -8,29 +8,12 @@ from django.shortcuts import get_object_or_404
|
|||||||
|
|
||||||
from common.utils import get_logger
|
from common.utils import get_logger
|
||||||
from common.permissions import IsOrgAdmin
|
from common.permissions import IsOrgAdmin
|
||||||
from ..models import LoginConfirmSetting
|
|
||||||
from ..serializers import LoginConfirmSettingSerializer
|
|
||||||
from .. import errors, mixins
|
from .. import errors, mixins
|
||||||
|
|
||||||
__all__ = ['LoginConfirmSettingUpdateApi', 'TicketStatusApi']
|
__all__ = ['TicketStatusApi']
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class LoginConfirmSettingUpdateApi(UpdateAPIView):
|
|
||||||
permission_classes = (IsOrgAdmin,)
|
|
||||||
serializer_class = LoginConfirmSettingSerializer
|
|
||||||
|
|
||||||
def get_object(self):
|
|
||||||
from users.models import User
|
|
||||||
user_id = self.kwargs.get('user_id')
|
|
||||||
user = get_object_or_404(User, pk=user_id)
|
|
||||||
defaults = {'user': user}
|
|
||||||
s, created = LoginConfirmSetting.objects.get_or_create(
|
|
||||||
defaults, user=user,
|
|
||||||
)
|
|
||||||
return s
|
|
||||||
|
|
||||||
|
|
||||||
class TicketStatusApi(mixins.AuthMixin, APIView):
|
class TicketStatusApi(mixins.AuthMixin, APIView):
|
||||||
permission_classes = (AllowAny,)
|
permission_classes = (AllowAny,)
|
||||||
|
|
||||||
@@ -45,5 +28,5 @@ class TicketStatusApi(mixins.AuthMixin, APIView):
|
|||||||
ticket = self.get_ticket()
|
ticket = self.get_ticket()
|
||||||
if ticket:
|
if ticket:
|
||||||
request.session.pop('auth_ticket_id', '')
|
request.session.pop('auth_ticket_id', '')
|
||||||
ticket.close(processor=request.user)
|
ticket.close(processor=self.get_user_from_session())
|
||||||
return Response('', status=200)
|
return Response('', status=200)
|
||||||
|
|||||||
@@ -1,49 +1,86 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
#
|
#
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from django.utils.translation import ugettext as _
|
from django.utils.translation import ugettext as _
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
from django.shortcuts import get_object_or_404
|
||||||
from rest_framework.permissions import AllowAny
|
from rest_framework.permissions import AllowAny
|
||||||
from rest_framework.generics import CreateAPIView
|
from rest_framework.generics import CreateAPIView
|
||||||
from rest_framework.serializers import ValidationError
|
from rest_framework.serializers import ValidationError
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
|
||||||
from common.permissions import IsValidUser, NeedMFAVerify
|
from common.permissions import IsValidUser, NeedMFAVerify
|
||||||
|
from common.utils import get_logger
|
||||||
|
from users.models.user import User
|
||||||
from ..serializers import OtpVerifySerializer
|
from ..serializers import OtpVerifySerializer
|
||||||
from .. import serializers
|
from .. import serializers
|
||||||
from .. import errors
|
from .. import errors
|
||||||
|
from ..mfa.otp import MFAOtp
|
||||||
from ..mixins import AuthMixin
|
from ..mixins import AuthMixin
|
||||||
|
|
||||||
|
|
||||||
__all__ = ['MFAChallengeApi', 'UserOtpVerifyApi']
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
'MFAChallengeVerifyApi', 'UserOtpVerifyApi',
|
||||||
|
'MFASendCodeApi'
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class MFAChallengeApi(AuthMixin, CreateAPIView):
|
# MFASelectAPi 原来的名字
|
||||||
|
class MFASendCodeApi(AuthMixin, CreateAPIView):
|
||||||
|
"""
|
||||||
|
选择 MFA 后对应操作 api,koko 目前在用
|
||||||
|
"""
|
||||||
|
permission_classes = (AllowAny,)
|
||||||
|
serializer_class = serializers.MFASelectTypeSerializer
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
username = serializer.validated_data.get('username', '')
|
||||||
|
mfa_type = serializer.validated_data['type']
|
||||||
|
if not username:
|
||||||
|
user = self.get_user_from_session()
|
||||||
|
else:
|
||||||
|
user = get_object_or_404(User, username=username)
|
||||||
|
|
||||||
|
mfa_backend = user.get_active_mfa_backend_by_type(mfa_type)
|
||||||
|
if not mfa_backend or not mfa_backend.challenge_required:
|
||||||
|
raise ValidationError('MFA type not support: {} {}'.format(mfa_type, mfa_backend))
|
||||||
|
mfa_backend.send_challenge()
|
||||||
|
|
||||||
|
def create(self, request, *args, **kwargs):
|
||||||
|
serializer = self.get_serializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.perform_create(serializer)
|
||||||
|
return Response(serializer.data, status=201)
|
||||||
|
except Exception as e:
|
||||||
|
logger.exception(e)
|
||||||
|
return Response({'error': str(e)}, status=400)
|
||||||
|
|
||||||
|
|
||||||
|
class MFAChallengeVerifyApi(AuthMixin, CreateAPIView):
|
||||||
permission_classes = (AllowAny,)
|
permission_classes = (AllowAny,)
|
||||||
serializer_class = serializers.MFAChallengeSerializer
|
serializer_class = serializers.MFAChallengeSerializer
|
||||||
|
|
||||||
def perform_create(self, serializer):
|
def perform_create(self, serializer):
|
||||||
try:
|
|
||||||
user = self.get_user_from_session()
|
user = self.get_user_from_session()
|
||||||
code = serializer.validated_data.get('code')
|
code = serializer.validated_data.get('code')
|
||||||
valid = user.check_mfa(code)
|
mfa_type = serializer.validated_data.get('type', '')
|
||||||
if not valid:
|
self._do_check_user_mfa(code, mfa_type, user)
|
||||||
self.request.session['auth_mfa'] = ''
|
|
||||||
raise errors.MFAFailedError(
|
def create(self, request, *args, **kwargs):
|
||||||
username=user.username, request=self.request, ip=self.get_request_ip()
|
try:
|
||||||
)
|
super().create(request, *args, **kwargs)
|
||||||
else:
|
return Response({'msg': 'ok'})
|
||||||
self.request.session['auth_mfa'] = '1'
|
|
||||||
except errors.AuthFailedError as e:
|
except errors.AuthFailedError as e:
|
||||||
data = {"error": e.error, "msg": e.msg}
|
data = {"error": e.error, "msg": e.msg}
|
||||||
raise ValidationError(data)
|
raise ValidationError(data)
|
||||||
except errors.NeedMoreInfoError as e:
|
except errors.NeedMoreInfoError as e:
|
||||||
return Response(e.as_data(), status=200)
|
return Response(e.as_data(), status=200)
|
||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
super().create(request, *args, **kwargs)
|
|
||||||
return Response({'msg': 'ok'})
|
|
||||||
|
|
||||||
|
|
||||||
class UserOtpVerifyApi(CreateAPIView):
|
class UserOtpVerifyApi(CreateAPIView):
|
||||||
permission_classes = (IsValidUser,)
|
permission_classes = (IsValidUser,)
|
||||||
@@ -56,14 +93,17 @@ class UserOtpVerifyApi(CreateAPIView):
|
|||||||
serializer = self.get_serializer(data=request.data)
|
serializer = self.get_serializer(data=request.data)
|
||||||
serializer.is_valid(raise_exception=True)
|
serializer.is_valid(raise_exception=True)
|
||||||
code = serializer.validated_data["code"]
|
code = serializer.validated_data["code"]
|
||||||
|
otp = MFAOtp(request.user)
|
||||||
|
|
||||||
if request.user.check_mfa(code):
|
ok, error = otp.check_code(code)
|
||||||
|
if ok:
|
||||||
request.session["MFA_VERIFY_TIME"] = int(time.time())
|
request.session["MFA_VERIFY_TIME"] = int(time.time())
|
||||||
return Response({"ok": "1"})
|
return Response({"ok": "1"})
|
||||||
else:
|
else:
|
||||||
return Response({"error": _("Code is invalid")}, status=400)
|
return Response({"error": _("Code is invalid, {}").format(error)}, status=400)
|
||||||
|
|
||||||
def get_permissions(self):
|
def get_permissions(self):
|
||||||
if self.request.method.lower() == 'get' and settings.SECURITY_VIEW_AUTH_NEED_MFA:
|
if self.request.method.lower() == 'get' \
|
||||||
|
and settings.SECURITY_VIEW_AUTH_NEED_MFA:
|
||||||
self.permission_classes = [NeedMFAVerify]
|
self.permission_classes = [NeedMFAVerify]
|
||||||
return super().get_permissions()
|
return super().get_permissions()
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from rest_framework.response import Response
|
|||||||
from authentication.serializers import PasswordVerifySerializer
|
from authentication.serializers import PasswordVerifySerializer
|
||||||
from common.permissions import IsValidUser
|
from common.permissions import IsValidUser
|
||||||
from authentication.mixins import authenticate
|
from authentication.mixins import authenticate
|
||||||
from authentication.errors import PasswdInvalid
|
from authentication.errors import PasswordInvalid
|
||||||
from authentication.mixins import AuthMixin
|
from authentication.mixins import AuthMixin
|
||||||
|
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ class UserPasswordVerifyApi(AuthMixin, CreateAPIView):
|
|||||||
|
|
||||||
user = authenticate(request=request, username=user.username, password=password)
|
user = authenticate(request=request, username=user.username, password=password)
|
||||||
if not user:
|
if not user:
|
||||||
raise PasswdInvalid
|
raise PasswordInvalid
|
||||||
|
|
||||||
self.set_passwd_verify_on_session(user)
|
self.mark_password_ok(user)
|
||||||
return Response()
|
return Response()
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ from rest_framework.response import Response
|
|||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.permissions import AllowAny
|
from rest_framework.permissions import AllowAny
|
||||||
|
|
||||||
from common.utils.timezone import utcnow
|
from common.utils.timezone import utc_now
|
||||||
from common.const.http import POST, GET
|
from common.const.http import POST, GET
|
||||||
from common.drf.api import JmsGenericViewSet
|
from common.drf.api import JMSGenericViewSet
|
||||||
from common.drf.serializers import EmptySerializer
|
from common.drf.serializers import EmptySerializer
|
||||||
from common.permissions import IsSuperUser
|
from common.permissions import IsSuperUser
|
||||||
from common.utils import reverse
|
from common.utils import reverse
|
||||||
@@ -26,7 +26,7 @@ NEXT_URL = 'next'
|
|||||||
AUTH_KEY = 'authkey'
|
AUTH_KEY = 'authkey'
|
||||||
|
|
||||||
|
|
||||||
class SSOViewSet(AuthMixin, JmsGenericViewSet):
|
class SSOViewSet(AuthMixin, JMSGenericViewSet):
|
||||||
queryset = SSOToken.objects.all()
|
queryset = SSOToken.objects.all()
|
||||||
serializer_classes = {
|
serializer_classes = {
|
||||||
'login_url': SSOTokenSerializer,
|
'login_url': SSOTokenSerializer,
|
||||||
@@ -79,7 +79,7 @@ class SSOViewSet(AuthMixin, JmsGenericViewSet):
|
|||||||
return HttpResponseRedirect(next_url)
|
return HttpResponseRedirect(next_url)
|
||||||
|
|
||||||
# 判断是否过期
|
# 判断是否过期
|
||||||
if (utcnow().timestamp() - token.date_created.timestamp()) > settings.AUTH_SSO_AUTHKEY_TTL:
|
if (utc_now().timestamp() - token.date_created.timestamp()) > settings.AUTH_SSO_AUTHKEY_TTL:
|
||||||
self.send_auth_signal(success=False, reason='authkey_timeout')
|
self.send_auth_signal(success=False, reason='authkey_timeout')
|
||||||
return HttpResponseRedirect(next_url)
|
return HttpResponseRedirect(next_url)
|
||||||
|
|
||||||
|
|||||||
@@ -33,12 +33,14 @@ class TokenCreateApi(AuthMixin, CreateAPIView):
|
|||||||
self.check_user_mfa_if_need(user)
|
self.check_user_mfa_if_need(user)
|
||||||
self.check_user_login_confirm_if_need(user)
|
self.check_user_login_confirm_if_need(user)
|
||||||
self.send_auth_signal(success=True, user=user)
|
self.send_auth_signal(success=True, user=user)
|
||||||
self.clear_auth_mark()
|
|
||||||
resp = super().create(request, *args, **kwargs)
|
resp = super().create(request, *args, **kwargs)
|
||||||
|
self.clear_auth_mark()
|
||||||
return resp
|
return resp
|
||||||
except errors.AuthFailedError as e:
|
except errors.AuthFailedError as e:
|
||||||
return Response(e.as_data(), status=400)
|
return Response(e.as_data(), status=400)
|
||||||
except errors.NeedMoreInfoError as e:
|
except errors.NeedMoreInfoError as e:
|
||||||
return Response(e.as_data(), status=200)
|
return Response(e.as_data(), status=200)
|
||||||
except errors.PasswdTooSimple as e:
|
except errors.MFAUnsetError:
|
||||||
return redirect(e.url)
|
return Response({'error': 'MFA unset, please set first'}, status=400)
|
||||||
|
except Exception as e:
|
||||||
|
return Response({"error": str(e)}, status=400)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user