Debian Codegraph @

src/calibre/srv/manage_users_cli.py

raw
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
3
4 import sys
5
6 from calibre import prints
7 from calibre.constants import iswindows, preferred_encoding
8 from calibre.utils.config import OptionParser
9 from calibre.utils.localization import _, ngettext
10
11
12 def create_subcommand_parser(name, usage):
13 usage = f'%prog --manage-users -- {name} ' + usage
14 parser = OptionParser(usage)
15 return parser
16
17
18 def add(user_manager, args):
19 p = create_subcommand_parser(
20 'add',
21 _('username [password]')
22 + '\n\n'
23 + '''\
24 Create a new user account with the specified name and password. If the password
25 is not specified on the command line, it will be read from STDIN.
26 ''',
27 )
28 p.add_option('--readonly', action='store_true', default=False, help=_('Give this user only read access'))
29 opts, args = p.parse_args(['calibre-server'] + list(args))
30 if len(args) < 2:
31 p.print_help()
32 raise SystemExit(_('username is required'))
33 username = args[1]
34 if len(args) > 2:
35 pw = args[2]
36 else:
37 pw = sys.stdin.read()
38 user_manager.add_user(username, pw, readonly=opts.readonly)
39
40
41 def remove(user_manager, args):
42 p = create_subcommand_parser(
43 'remove',
44 _('username')
45 + '\n\n'
46 + '''\
47 Remove the user account with the specified username.
48 ''',
49 )
50 opts, args = p.parse_args(['calibre-server'] + list(args))
51 if len(args) < 2:
52 p.print_help()
53 raise SystemExit(_('username is required'))
54 username = args[1]
55 user_manager.remove_user(username)
56
57
58 def list_users(user_manager, args):
59 p = create_subcommand_parser(
60 'list',
61 '\n\n'
62 + '''\
63 List all usernames.
64 ''',
65 )
66 opts, args = p.parse_args(['calibre-server'] + list(args))
67 for name in user_manager.all_user_names:
68 print(name)
69
70
71 def change_set_password(user_manager, args):
72 p = create_subcommand_parser(
73 'change_set_password',
74 _('username set|reset|toggle|show')
75 + '\n\n'
76 + '''\
77 Restrict the specified user account to prevent it from changing its own password via the web interface. \
78 The value of set allows the account to change its own password, reset prevents it from changing its \
79 own password, toggle flips the value and show prints out the current value. \
80 ''',
81 )
82 opts, args = p.parse_args(['calibre-server'] + list(args))
83 if len(args) < 3:
84 p.print_help()
85 raise SystemExit(_('username and operation are required'))
86 username, op = args[1], args[2]
87 if op == 'toggle':
88 val = not user_manager.is_allowed_to_change_password_via_http(username)
89 elif op == 'set':
90 val = True
91 elif op == 'reset':
92 val = False
93 elif op == 'show':
94 print('set' if user_manager.is_allowed_to_change_password_via_http(username) else 'reset', end='')
95 return
96 else:
97 raise SystemExit(f'{op} is an unknown operation')
98 user_manager.set_allowed_to_change_password_via_http(username, val)
99
100
101 def change_readonly(user_manager, args):
102 p = create_subcommand_parser(
103 'readonly',
104 _('username set|reset|toggle|show')
105 + '\n\n'
106 + '''\
107 Restrict the specified user account to prevent it from making changes. \
108 The value of set makes the account readonly, reset allows it to make \
109 changes, toggle flips the value and show prints out the current value. \
110 ''',
111 )
112 opts, args = p.parse_args(['calibre-server'] + list(args))
113 if len(args) < 3:
114 p.print_help()
115 raise SystemExit(_('username and operation are required'))
116 username, op = args[1], args[2]
117 if op == 'toggle':
118 val = not user_manager.is_readonly(username)
119 elif op == 'set':
120 val = True
121 elif op == 'reset':
122 val = False
123 elif op == 'show':
124 print('set' if user_manager.is_readonly(username) else 'reset', end='')
125 return
126 else:
127 raise SystemExit(f'{op} is an unknown operation')
128 user_manager.set_readonly(username, val)
129
130
131 def change_libraries(user_manager, args):
132 p = create_subcommand_parser(
133 'libraries',
134 _('[options] username [library_name ...]')
135 + '\n\n'
136 + '''\
137 Manage the libraries the specified user account is restricted to.
138 ''',
139 )
140 p.add_option(
141 '--action',
142 type='choice',
143 choices='allow-all allow block per-library show'.split(),
144 default='show',
145 help=_(
146 'Specify the action to perform.'
147 '\nA value of "show" shows the current library restrictions for the specified user.'
148 '\nA value of "allow-all" removes all library restrictions.'
149 '\nA value of "allow" allows access to only the specified libraries.'
150 '\nA value of "block" allows access to all, except the specified libraries.'
151 '\nA value of "per-library" sets per library restrictions. In this case the libraries list'
152 ' is interpreted as a list of library name followed by restriction to apply, followed'
153 ' by next library name and so on. Using a restriction of "=" removes any previous restriction'
154 ' on that library.'
155 ),
156 )
157 opts, args = p.parse_args(['calibre-server'] + list(args))
158 if len(args) < 2:
159 p.print_help()
160 raise SystemExit(_('username is required'))
161 username, libraries = args[1], args[2:]
162 r = user_manager.restrictions(username)
163 if r is None:
164 raise SystemExit(f'The user {username} does not exist')
165
166 if opts.action == 'show':
167 if r['allowed_library_names']:
168 print('Allowed:')
169 for name in r['allowed_library_names']:
170 print('\t' + name)
171 if r['blocked_library_names']:
172 print('Blocked:')
173 for name in r['blocked_library_names']:
174 print('\t' + name)
175 if r['library_restrictions']:
176 print('Per Library:')
177 for name, res in r['library_restrictions'].items():
178 print('\t' + name)
179 print('\t\t' + res)
180 if not r['allowed_library_names'] and not r['blocked_library_names'] and not r['library_restrictions']:
181 print(f'{username} has no library restrictions')
182 elif opts.action == 'allow-all':
183 user_manager.update_user_restrictions(username, {})
184 elif opts.action == 'per-library':
185 if not libraries:
186 p.print_help()
187 raise SystemExit('Must specify at least one library and restriction')
188 if len(libraries) % 2 != 0:
189 p.print_help()
190 raise SystemExit('Must specify a restriction for every library')
191 lres = r['library_restrictions']
192 for i in range(0, len(libraries), 2):
193 name, res = libraries[i : i + 2]
194 if res == '=':
195 lres.pop(name, None)
196 else:
197 lres[name] = res
198 user_manager.update_user_restrictions(username, r)
199 else:
200 if not libraries:
201 p.print_help()
202 raise SystemExit('Must specify at least one library name')
203 k = 'blocked_library_names' if opts.action == 'block' else 'allowed_library_names'
204 r.pop('allowed_library_names', None)
205 r.pop('blocked_library_names', None)
206 r[k] = libraries
207 user_manager.update_user_restrictions(username, r)
208
209
210 def chpass(user_manager, args):
211 p = create_subcommand_parser(
212 'chpass',
213 _('username [password]')
214 + '\n\n'
215 + '''\
216 Change the password of the new user account with the specified username. If the password
217 is not specified on the command line, it will be read from STDIN.
218 ''',
219 )
220 opts, args = p.parse_args(['calibre-server'] + list(args))
221 if len(args) < 2:
222 p.print_help()
223 raise SystemExit(_('username is required'))
224 username = args[1]
225 if len(args) > 2:
226 pw = args[2]
227 else:
228 pw = sys.stdin.read()
229 user_manager.change_password(username, pw)
230
231
232 def main(user_manager, args):
233 q, rest = args[0], args[1:]
234 if q == 'add':
235 return add(user_manager, rest)
236 if q == 'remove':
237 return remove(user_manager, rest)
238 if q == 'chpass':
239 return chpass(user_manager, rest)
240 if q == 'list':
241 return list_users(user_manager, rest)
242 if q == 'readonly':
243 return change_readonly(user_manager, rest)
244 if q == 'change_set_password':
245 return change_set_password(user_manager, rest)
246 if q == 'libraries':
247 return change_libraries(user_manager, rest)
248 if q != 'help':
249 print(_('Unknown command: {}').format(q), file=sys.stderr)
250 print()
251 print(_('Manage the user accounts for calibre-server. Available commands are:'))
252 print('add, remove, chpass, list, readonly, change_set_password')
253 print(_('Use {} for help on individual commands').format('calibre-server --manage-users -- command -h'))
254 raise SystemExit(1)
255
256
257 def manage_users_cli(path=None, args=()):
258 from calibre.srv.users import UserManager
259
260 m = UserManager(path)
261 if args:
262 main(m, args)
263 return
264 enc = getattr(sys.stdin, 'encoding', preferred_encoding) or preferred_encoding
265
266 def get_input(prompt):
267 prints(prompt, end=' ')
268 ans = input()
269 if isinstance(ans, bytes):
270 ans = ans.decode(enc)
271 if iswindows:
272 # https://bugs.python.org/issue11272
273 ans = ans.rstrip('\r')
274 return ans
275
276 def choice(question=_('What do you want to do?'), choices=(), default=None, banner=''):
277 prints(banner)
278 for i, choice in enumerate(choices):
279 prints(f'{i + 1})', choice)
280 print()
281 while True:
282 prompt = question + f' [1-{len(choices)}]:'
283 if default is not None:
284 prompt = question + f" [1-{len(choices)} {_('default')}: {default + 1}]"
285 reply = get_input(prompt)
286 if not reply and default is not None:
287 reply = str(default + 1)
288 if not reply:
289 prints(_('No choice selected, exiting...'))
290 raise SystemExit(0)
291 reply = reply.strip()
292 try:
293 num = int(reply) - 1
294 if not (0 <= num < len(choices)):
295 raise Exception('bad num')
296 return num
297 except Exception:
298 prints(_('%s is not a valid choice, try again') % reply)
299
300 def get_valid(prompt, invalidq=lambda x: None):
301 while True:
302 ans = get_input(prompt + ':').strip()
303 fail_message = invalidq(ans)
304 if fail_message is None:
305 return ans
306 prints(fail_message)
307
308 def get_valid_user():
309 prints(_('Existing user names:'))
310 users = sorted(m.all_user_names)
311 if not users:
312 raise SystemExit(_('There are no users, you must first add an user'))
313 prints(', '.join(users))
314
315 def validate(username):
316 if not m.has_user(username):
317 return _('The username %s does not exist') % username
318
319 return get_valid(_('Enter the username'), validate)
320
321 def get_pass(username):
322 from getpass import getpass
323
324 while True:
325 one = getpass(_('Enter the new password for %s: ') % username)
326 if not one:
327 prints(_('Empty passwords are not allowed'))
328 continue
329 two = getpass(_('Re-enter the new password for %s, to verify: ') % username)
330 if one != two:
331 prints(_('Passwords do not match'))
332 continue
333 msg = m.validate_password(one)
334 if msg is None:
335 return one
336 prints(msg)
337
338 def add_user():
339 username = get_valid(_('Enter the username'), m.validate_username)
340 pw = get_pass(username)
341 m.add_user(username, pw)
342 prints(_('User %s added successfully!') % username)
343
344 def remove_user():
345 un = get_valid_user()
346 if get_input((_('Are you sure you want to remove the user %s?') % un) + ' [y/n]:') != 'y':
347 raise SystemExit(0)
348 m.remove_user(un)
349 prints(_('User %s successfully removed!') % un)
350
351 def change_password(username):
352 pw = get_pass(username)
353 m.change_password(username, pw)
354 prints(_('Password for %s successfully changed!') % username)
355
356 def show_password(username):
357 pw = m.get(username)
358 prints(_('Current password for {0} is: {1}').format(username, pw))
359
360 def change_readonly(username):
361 readonly = m.is_readonly(username)
362 if readonly:
363 q = _('Allow {} to make changes (i.e. grant write access)')
364 else:
365 q = _('Prevent {} from making changes (i.e. remove write access)')
366 if get_input(q.format(username) + '? [y/n]:').lower() == 'y':
367 m.set_readonly(username, not readonly)
368
369 def change_set_password(username):
370 allowed = m.is_allowed_to_change_password_via_http(username)
371 if allowed:
372 q = _('Prevent {} from changing their own password via the web')
373 else:
374 q = _('Allow {} to change their own password via the web')
375 if get_input(q.format(username) + '? [y/n]:').lower() == 'y':
376 m.set_allowed_to_change_password_via_http(username, not allowed)
377
378 def change_restriction(username):
379 r = m.restrictions(username)
380 if r is None:
381 raise SystemExit(f'The user {username} does not exist')
382 if r['allowed_library_names']:
383 libs = r['allowed_library_names']
384 prints(
385 ngettext(
386 '{} is currently only allowed to access the library named: {}',
387 '{} is currently only allowed to access the libraries named: {}',
388 len(libs),
389 ).format(username, ', '.join(libs))
390 )
391 if r['blocked_library_names']:
392 libs = r['blocked_library_names']
393 prints(
394 ngettext(
395 '{} is currently not allowed to access the library named: {}',
396 '{} is currently not allowed to access the libraries named: {}',
397 len(libs),
398 ).format(username, ', '.join(libs))
399 )
400 if r['library_restrictions']:
401 prints(_('{} has the following additional per-library restrictions:').format(username))
402 for k, v in r['library_restrictions'].items():
403 prints(k + ':', v)
404 else:
405 prints(_('{} has no additional per-library restrictions').format(username))
406 c = choice(
407 choices=[
408 _('Allow access to all libraries'),
409 _('Allow access to only specified libraries'),
410 _('Allow access to all, except specified libraries'),
411 _('Change per-library restrictions'),
412 _('Cancel'),
413 ]
414 )
415 if c == 0:
416 m.update_user_restrictions(username, {})
417 elif c == 3:
418 while True:
419 library = get_input(_('Enter the name of the library:'))
420 if not library:
421 break
422 prints(
423 _(
424 'Enter a search expression, access will be granted only to books matching this expression.'
425 ' An empty expression will grant access to all books.'
426 )
427 )
428 plr = get_input(_('Search expression:'))
429 if plr:
430 r['library_restrictions'][library] = plr
431 else:
432 r['library_restrictions'].pop(library, None)
433 m.update_user_restrictions(username, r)
434 if get_input(_('Another restriction?') + ' (y/n):') != 'y':
435 break
436 elif c == 4:
437 pass
438 else:
439 names = get_input(_('Enter a comma separated list of library names:'))
440 names = list(filter(None, [x.strip() for x in names.split(',')]))
441 w = 'allowed_library_names' if c == 1 else 'blocked_library_names'
442 t = _('Allowing access only to libraries: {}') if c == 1 else _('Allowing access to all libraries, except: {}')
443 prints(t.format(', '.join(names)))
444 m.update_user_restrictions(username, {w: names})
445
446 def edit_user(username=None):
447 username = username or get_valid_user()
448 c = choice(
449 choices=[
450 _('Show password for {}').format(username),
451 _('Change password for {}').format(username),
452 _('Change read/write permission for {}').format(username),
453 _('Change the libraries {} is allowed to access').format(username),
454 _('Change if {} is allowed to set their own password').format(username),
455 _('Cancel'),
456 ],
457 banner='\n' + _('{0} has {1} access').format(username, _('readonly') if m.is_readonly(username) else _('read-write')),
458 )
459 print()
460 if c > 4:
461 actions.append(toplevel)
462 return
463 {
464 0: show_password,
465 1: change_password,
466 2: change_readonly,
467 3: change_restriction,
468 4: change_set_password,
469 }[c](username)
470 actions.append(lambda: edit_user(username=username))
471
472 def toplevel():
473 {0: add_user, 1: edit_user, 2: remove_user, 3: lambda: None}[
474 choice(choices=[_('Add a new user'), _('Edit an existing user'), _('Remove a user'), _('Cancel')])
475 ]()
476
477 actions = [toplevel]
478 while actions:
479 actions[0]()
480 del actions[0]