Repository navigation
Expand file tree
/
Copy pathcreateuser.py
More file actions
executable file
·182 lines (157 loc) · 7.05 KB
/
Copy pathcreateuser.py
File metadata and controls
executable file
·182 lines (157 loc) · 7.05 KB
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
#!/usr/bin/python3
# Copyright (C) 2022 OX Software GmbH
# Wolfgang Rosenauer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import argparse
import json
import re
import requests
import settings
import soapclient
def main():
parser = argparse.ArgumentParser(description='Creates an OX Cloud user.')
parser.add_argument("-n", dest="context_name",
help="Context name the user should be created in.")
parser.add_argument(
"-c", "--cid", help="Context ID the user should be created in.", type=int)
parser.add_argument("-e", "--email", required=True,
help="E-Mail address / login name of the user.")
parser.add_argument("-p", "--password", required=True,
help="Password for the user.")
parser.add_argument("-g", "--firstname", required=True,
help="First name of the user.")
parser.add_argument("-s", "--lastname", required=True,
help="Last name of the user.")
parser.add_argument(
"-l", "--language", help="Initial language of the user. (Default: en_US)", default="en_US")
parser.add_argument(
"-t", "--timezone", help="Initial timezone of the user. (Default: Europe/Berlin)", default="Europe/Berlin")
parser.add_argument("-q", "--quota", required=True,
help="Quota of the user in MiB (-1 for unlimited)", type=int)
parser.add_argument("--mailquota", help="Mailquota (if set quota won't be unified; if unset unified quota applies)")
parser.add_argument("-a", "--access-combination", required=True,
help="Access combination name for the user.")
parser.add_argument(
"--cos", help="The Class of Service for that mailbox. If left undefined the access-combination name is used.")
parser.add_argument("--editpassword",
help="Should the user have the ability to change his password.", action="store_true")
parser.add_argument(
"--spamlevel", help="Specify spamlevel to use for the mailbox (no default). Options 'low', 'medium', and 'high'.")
parser.add_argument(
"--config", help="Additional config properties including in format PROPERTY=VALUE")
args = parser.parse_args()
if args.context_name is None and args.cid is None:
parser.error("Context must be specified by either -n or -c !")
ctx = {}
if args.cid is not None:
ctx["id"] = args.cid
else:
ctx["name"] = settings.getCreds()["login"] + "_" + args.context_name
if args.cos is None:
args.cos = args.access_combination
contextService = soapclient.getService("OXResellerContextService")
ctx = contextService.getData(ctx, settings.getCreds())
userService = soapclient.getService("OXResellerUserService")
oxaasService = soapclient.getService("OXaaSService")
# prepare user
user = {
"name": args.email,
"password": args.password,
"display_name": args.firstname + " " + args.lastname,
"sur_name": args.lastname,
"given_name": args.firstname,
"primaryEmail": args.email,
"email1": args.email,
"language": args.language,
"timezone": args.timezone,
"maxQuota": args.quota,
"drive_user_folder_mode": "normal" # can be default, normal or none
}
userConfig = []
if args.config:
config = kv_pairs(args.config)
configAttributes = []
for key in config:
configAttributes.append(
{
"key": key,
"value": config[key]
}
)
userConfig.extend(configAttributes)
# unlimited quota is currently an edge case
# for Drive unlimited means -1
# for Dovecot unlimited means 0
# handle this special case
if args.quota == -1 or args.mailquota is not None:
userConfig.extend(
[{
"key": "com.openexchange.unifiedquota.enabled",
"value": "false"
}]
)
if args.quota == -1:
dcQuota = 0
user["maxQuota"] = 1 # to force creation of userfilestore
else:
dcQuota = args.mailquota
else:
dcQuota = args.quota
userCOS = {
"key": "cloud",
"value": {"entries": {"key": "service", "value": args.cos}}
}
user["userAttributes"] = {"entries": [userCOS]}
if (userConfig):
user["userAttributes"]["entries"].append(
{"key": "config", "value": {"entries": userConfig}})
user = userService.createByModuleAccessName(
ctx, user, args.access_combination, settings.getCreds())
if args.editpassword:
user_access = userService.getModuleAccess(
ctx, user, settings.getCreds())
user_access.editPassword = args.editpassword
userService.changeByModuleAccess(
ctx, user, user_access, settings.getCreds())
if args.quota == -1:
# change maxQuota to -1 finally
user["maxQuota"] = -1
userService.change(ctx, user, settings.getCreds())
oxaasService.setMailQuota(
ctx.id, user.id, dcQuota, settings.getCreds())
print("Created user", user.id, "with password", args.password,
"in context", ctx.id, "and unified quota", args.quota)
# apply spamlevel
if args.spamlevel:
data = json.loads('{"spamlevel": "'+args.spamlevel+'"}')
r = requests.put(settings.getRestHost()+"oxaas/v1/admin/contexts/"+str(
ctx.id)+"/users/"+str(user.id)+"/spamlevel", auth=(settings.getRestCreds()), json=data, verify=settings.getVerifyTls())
print(r.status_code)
if r.status_code == 200:
print("Applied spamlevel ", args.spamlevel,
" for ", user.id, "in context", ctx.id)
else:
print("Failed to set requested spamlevel")
def kv_pairs(text, item_sep=r",", value_sep="="):
split_regex = r"""
(?P<key>[\w\.\-/]+)= # Key consists of only alphanumerics and '-' character
(?P<quote>["']?) # Optional quote character.
(?P<value>[\S\s]*?) # Value is a non greedy match
(?P=quote) # Closing quote equals the first.
($|\s) # Entry ends with comma or end of string
""".replace("=", value_sep).replace(r"|\s)", f"|{item_sep})")
regex = re.compile(split_regex, re.VERBOSE)
return {match.group("key"): match.group("value") for match in regex.finditer(text)}
if __name__ == "__main__":
main()