-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchange_users_to_single_space_guests_on_confluence-cloud.py
executable file
·213 lines (155 loc) · 6.8 KB
/
change_users_to_single_space_guests_on_confluence-cloud.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python
import sys
import requests
from requests.auth import HTTPBasicAuth
import json
import yaml
import pdb
from pprint import pprint
from Confluence_apis import Confluence_cloud_api
import logging
# configure logging
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s\t[%(name)s.%(funcName)s:%(lineno)d] %(message)s",
datefmt="%d/%b/%Y %H:%M:%S",
stream=sys.stdout)
# user help message
usage = f"Usage: python3 {sys.argv[0]} <atlassian config yaml file> [<groups to convert, comma separated>]"
# get the arguments
try:
logging.debug("Fetching config filename.")
atlassian_config_filename = sys.argv[1]
except IndexError:
print(f"{usage}\n\nERROR: Atlassian config file argument missing")
sys.exit()
try:
logging.debug("Fetching group filter list")
group_filter_list = sys.argv[2].split(',')
except IndexError:
group_filter_list = []
# read the atlassian config file
logging.debug("Reading config file.")
with open(atlassian_config_filename, 'r') as file:
try:
config = yaml.safe_load(file)
except yaml.YAMLError as exc:
print(exc)
# create confluence api instance
logging.debug("Creating confluence api object")
confluence = Confluence_cloud_api(config)
# request a list of all spaces
logging.info("Fetching spaces.")
#spaces = confluence.get_spaces(expand="permissions", paginate=False)
spaces = confluence.get_spaces(expand="permissions")
#spaces = []
# init
user_permissions = {}
group_permissions = {}
## Get all user-space and group-space memberships
# go through all spaces
logging.info("Parsing permissions.")
for space in spaces:
#continue
logging.debug(f"Space: {space['name']}")
# go through all permissions
for permission in space['permissions']:
# skip empty permissions
if 'subjects' not in permission.keys():
continue
# if it is a user permission
if permission['subjects'].get('user'):
# for all users with permission
for user in permission['subjects']['user']['results']:
# save the user and space info
try:
logging.debug(f"User: {user['accountId']}")
user_permissions[user['accountId']]['spaces'][space['key']] = space
except KeyError:
# if it is the first time seeing this user
user_permissions[user['accountId']] = {}
user_permissions[user['accountId']]['spaces'] = {space['key']:space}
user_permissions[user['accountId']]['user'] = user
# if it is a user permission
elif permission['subjects'].get('group'):
# for all groups with permission
for group in permission['subjects']['group']['results']:
# save the user and space info
try:
logging.debug(f"Group: {group['id']}")
group_permissions[group['id']]['spaces'][space['key']] = space
except KeyError:
# if it is the first time seeing this group
group_permissions[group['id']] = {}
group_permissions[group['id']]['spaces'] = {space['key']:space}
group_permissions[group['id']]['group'] = group
logging.debug("Parsing permissions finished.")
## get a complete list of all users
logging.info("Fetching all users from API.")
#users = confluence.get_users(paginate=False)
users = confluence.get_users()
#pdb.set_trace()
# add all users to user_permissions dict
for user in users:
# find missing users
if user['user']['accountId'] not in user_permissions:
# initiate entry
user_permissions[user['user']['accountId']] = {'spaces':{}, 'user':user['user']}
# get all groups
logging.info(f"Fetching groups.")
groups = confluence.get_groups()
# for each groups, get members
for group in groups:
# fetch group members
logging.info(f"Fetching group memebers from {group['name']}")
members = confluence.get_group_members(group_id=group['id'])
# initiate entry if group is missing in group_permissions
if group['id'] not in group_permissions:
group_permissions[group['id']] = {'spaces':{}, 'group':group}
# skip groups with no permissions
# for each member, add the groups spaces to the users spaces list
for member in members:
# initiate entry if member is missing in member_permissions
if member['accountId'] not in user_permissions:
# initiate entry
user_permissions[member['accountId']] = {'spaces':{}, 'user':member}
# add group spaces to user spaces
user_permissions[member['accountId']]['spaces'].update(group_permissions[group['id']]['spaces'])
logging.info("Getting guest group id.")
# get guest group name
guest_group_id = ""
for group in groups:
if group['name'].startswith("confluence-guests-"):
guest_group_id = group['id']
if guest_group_id == "":
print("Guest group id not found.")
pdb.set_trace()
# make a lookup table for space keys to space names for easy access
key_to_name = { space['key']:space['name'] for space in spaces}
logging.info("Findinig users with only 1 space.")
c=0
# find users with access to only 1 space
for user_id,up in user_permissions.items():
if len(user_permissions[user_id]['spaces']) <= 1:
# count number of 1 space users
c += 1
# get user's group memberships
#user_group_memberships = confluence.get_user_group_memberships(user_id)
#user_group_memberships_names = [group['name'] for group in user_group_memberships]
# debug
user_group_memberships_names = []
#pdb.set_trace()
# if the users should be filtered on group memberships
if group_filter_list:
# only convert users who are members of any of the specified group(s)
if not any(group_name in group_filter_list for group_name in user_group_memberships_names):
# skip user if they are not in the correct group(s)
continue
# get the name of the space a user has access to
guest_space_name = "no space at all"
if len(user_permissions[user_id]['spaces']) > 0:
guest_space_name = key_to_name[list(user_permissions[user_id]['spaces'].keys())[0]]
logging.info(f"Converting {user_permissions[user_id]['user']['displayName']} to guest user with access to {guest_space_name}")
# convert user to guest user
#confluence.convert_to_guest_user(user_id, guest_group_id)
logging.info(f"Finished converting {c} users to guest users, out of {len(user_permissions)} total users.")