Debian Codegraph @

flask_security/cli.py

raw
1 """
2 flask_security.cli
3 ~~~~~~~~~~~~~~~~~~
4
5 Command Line Interface for managing accounts and roles.
6
7 :copyright: (c) 2016 by CERN.
8 :copyright: (c) 2019-2025 by J. Christopher Wagner
9 :license: MIT, see LICENSE for more details.
10 """
11
12 import functools
13
14 import click
15 from flask import current_app
16 from werkzeug.local import LocalProxy
17 from .quart_compat import get_quart_status
18
19 from .changeable import admin_change_password
20 from .forms import _build_form
21 from .utils import (
22 lookup_identity,
23 get_identity_attributes,
24 get_identity_attribute,
25 hash_password,
26 )
27
28 if get_quart_status(): # pragma: no cover
29 import quart.cli
30
31 # quart cli doesn't provide the with_appcontext function
32 def with_appcontext(f):
33 """Wraps a callback so that it's guaranteed to be executed with the
34 script's application context. If callbacks are registered directly
35 to the ``app.cli`` object then they are wrapped with this function
36 by default unless it's disabled.
37 """
38
39 @click.pass_context
40 def decorator(__ctx, *args, **kwargs):
41 with __ctx.ensure_object(quart.cli.ScriptInfo).load_app().app_context():
42 return __ctx.invoke(f, *args, **kwargs)
43
44 return functools.update_wrapper(decorator, f)
45
46 else:
47 import flask.cli
48
49 with_appcontext = flask.cli.with_appcontext
50
51
52 _security = LocalProxy(lambda: current_app.extensions["security"])
53 _datastore = LocalProxy(lambda: current_app.extensions["security"].datastore)
54
55
56 def commit(fn):
57 """Decorator to commit changes in datastore."""
58
59 @functools.wraps(fn)
60 def wrapper(*args, **kwargs):
61 fn(*args, **kwargs)
62 _datastore.commit()
63
64 return wrapper
65
66
67 def fix_errors(form_errors):
68 # Form errors might have lazy text which normally would be processed by
69 # render_template
70 errors = {}
71 for k, v in form_errors.items():
72 errors[k] = [str(e) for e in v]
73 return errors
74
75
76 @click.group()
77 def users():
78 """User commands.
79
80 For commands that require a USER - pass in any identity attribute.
81 """
82
83
84 @click.group()
85 def roles():
86 """Role commands."""
87
88
89 @users.command(
90 "create",
91 epilog=(
92 "Example: users create [email protected] --password 'battery staple' --active"
93 "\n"
94 "Example: users create [email protected] --password 'battery staple' --active"
95 " --username mememe us_phone_number:6505551212"
96 ),
97 )
98 @click.argument(
99 "attributes",
100 nargs=-1,
101 )
102 @click.password_option()
103 @click.option(
104 "-a", "--active", default=False, is_flag=True, help="Mark new user as active"
105 )
106 @click.option(
107 "-u",
108 "--username",
109 required=False,
110 default=None,
111 help="Available only if SECURITY_USERNAME_ENABLE is set",
112 )
113 @with_appcontext
114 @commit
115 def users_create(attributes, password, active, username):
116 """Create a user.
117
118 Create a new user with one or more attributes using the syntax:
119 ``attribute:value``. If attr isn't set 'email' is presumed.
120 Identity attribute values will be validated using the configured
121 confirm_register_form;
122 however, any ADDITIONAL attribute:value pairs will be sent directly to
123 datastore.create_user().
124
125 Note that unless the ``--active`` option is set, the new user won't ba able
126 to sign in or perform any other action
127
128 """
129 kwargs = {}
130
131 identity_attributes = get_identity_attributes()
132 for attrarg in attributes:
133 # If given identity is an identity_attribute - do a bit of pre-validating
134 # to provide nicer errors.
135 attr = "email"
136 if ":" in attrarg:
137 attr, attrarg = attrarg.split(":")
138 if attr in identity_attributes:
139 details = get_identity_attribute(attr)
140 idata = details["mapper"](attrarg)
141 if not idata:
142 raise click.UsageError(
143 f"Attr {attr} with value {attrarg} wasn't accepted by"
144 f" ``SECURITY_USER_IDENTITY_ATTRIBUTES``"
145 )
146
147 kwargs[attr] = attrarg
148 kwargs["password"] = password
149 if username:
150 kwargs["username"] = username
151
152 # We always add password_confirm here - if user used the CLI in input mode -
153 # it already asked for confirmation.
154 # if they used inline keywords, there really isn't any reason to make them type
155 # it in twice.
156 if _security.forms["confirm_register_form"].cls:
157 form_name = "confirm_register_form"
158 else:
159 form_name = "register_form"
160 form = _build_form(
161 form_name,
162 meta={"csrf": False},
163 **kwargs,
164 password_confirm=password,
165 )
166
167 if form.validate():
168 # We don't use the form directly to provide values so that this CLI can actually
169 # set any usermodel attribute. We do grab email and password from the form
170 # so that we get any normalization results.
171 kwargs["password"] = hash_password(form.password.data)
172 kwargs["active"] = active
173 # echo normalized email...
174 if "email" in kwargs:
175 kwargs["email"] = form.email.data
176 # Exceptions could be an attribute given that isn't in user store
177 try:
178 _datastore.create_user(**kwargs)
179 except Exception as e:
180 raise click.exceptions.BadParameter(e)
181 click.secho("User created successfully.", fg="green")
182 kwargs["password"] = "****"
183 click.echo(kwargs)
184 else:
185 raise click.UsageError(f"Error creating user. {fix_errors(form.errors)}")
186
187
188 @roles.command("create")
189 @click.argument("name")
190 @click.option("-d", "--description", default=None)
191 @click.option("-p", "--permissions", help="A comma separated list")
192 @with_appcontext
193 @commit
194 def roles_create(**kwargs):
195 """Create a role."""
196
197 # For some reason Click puts arguments in kwargs - even if they weren't specified.
198 if "permissions" in kwargs and not kwargs["permissions"]:
199 del kwargs["permissions"]
200 if "permissions" in kwargs and not hasattr(_datastore.role_model, "permissions"):
201 raise click.UsageError("Role model does not support permissions")
202 _datastore.create_role(**kwargs)
203 click.secho('Role "%(name)s" created successfully.' % kwargs, fg="green")
204
205
206 @roles.command("add")
207 @click.argument("user")
208 @click.argument("role")
209 @with_appcontext
210 @commit
211 def roles_add(user, role):
212 """Add role to user.
213
214 USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
215 """
216 user_obj = lookup_identity(user)
217 if user_obj is None:
218 raise click.UsageError("User not found.")
219
220 role = _datastore._prepare_role_modify_args(role)
221 if role is None:
222 raise click.UsageError("Cannot find role.")
223 if _datastore.add_role_to_user(user_obj, role):
224 click.secho(
225 f'Role "{role.name}" added to user "{user}" successfully.',
226 fg="green",
227 )
228 else:
229 raise click.UsageError("Cannot add role to user.")
230
231
232 @roles.command("remove")
233 @click.argument("user")
234 @click.argument("role")
235 @with_appcontext
236 @commit
237 def roles_remove(user, role):
238 """Remove role from user.
239
240 USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
241 """
242 user_obj = lookup_identity(user)
243 if user_obj is None:
244 raise click.UsageError("User not found.")
245
246 role = _datastore._prepare_role_modify_args(role)
247 if role is None:
248 raise click.UsageError("Cannot find role.")
249 if _datastore.remove_role_from_user(user_obj, role):
250 click.secho(
251 f'Role "{role.name}" removed from user "{user}" successfully.',
252 fg="green",
253 )
254 else:
255 raise click.UsageError("Cannot remove role from user.")
256
257
258 @roles.command("add_permissions")
259 @click.argument("role")
260 @click.argument("permissions")
261 @with_appcontext
262 @commit
263 def roles_add_permissions(role, permissions):
264 """Add permissions to role.
265
266 Role is an existing role name.
267 Permissions are a comma separated list.
268 """
269 role = _datastore._prepare_role_modify_args(role)
270 if role is None:
271 raise click.UsageError("Cannot find role.")
272 permlist = [s.strip() for s in permissions.split(",")]
273 if _datastore.add_permissions_to_role(role, permlist):
274 click.secho(
275 f'Permission(s) "{permissions}" added to role "{role.name}" successfully.',
276 fg="green",
277 )
278 else: # pragma: no cover
279 raise click.UsageError("Cannot add permission(s) to role.")
280
281
282 @roles.command("remove_permissions")
283 @click.argument("role")
284 @click.argument("permissions")
285 @with_appcontext
286 @commit
287 def roles_remove_permissions(role, permissions):
288 """Remove permissions from role.
289
290 Role is an existing role name.
291 Permissions are a comma separated list.
292 """
293 role = _datastore._prepare_role_modify_args(role)
294 if role is None:
295 raise click.UsageError("Cannot find role.")
296 permlist = [s.strip() for s in permissions.split(",")]
297 if _datastore.remove_permissions_from_role(role, permlist):
298 click.secho(
299 f'Permission(s) "{permissions}" removed from role'
300 f' "{role.name}" successfully.',
301 fg="green",
302 )
303 else: # pragma: no cover
304 raise click.UsageError("Cannot remove permission(s) from role.")
305
306
307 @users.command("activate")
308 @click.argument("user")
309 @with_appcontext
310 @commit
311 def users_activate(user):
312 """Activate a user.
313
314 USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
315 """
316 user_obj = lookup_identity(user)
317 if user_obj is None:
318 raise click.UsageError("User not found.")
319 if _datastore.activate_user(user_obj):
320 click.secho(f'User "{user}" has been activated.', fg="green")
321 else:
322 click.secho(f'User "{user}" was already activated.', fg="yellow")
323
324
325 @users.command("deactivate")
326 @click.argument("user")
327 @with_appcontext
328 @commit
329 def users_deactivate(user):
330 """Deactivate a user.
331
332 USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
333 """
334 user_obj = lookup_identity(user)
335 if user_obj is None:
336 raise click.UsageError("User not found.")
337 if _datastore.deactivate_user(user_obj):
338 click.secho(f'User "{user}" has been deactivated.', fg="green")
339 else:
340 click.secho(f'User "{user}" was already deactivated.', fg="yellow")
341
342
343 @users.command("reset_access")
344 @click.argument("user")
345 @with_appcontext
346 @commit
347 def users_reset_access(user):
348 """Reset all authentication credentials for user.
349 This includes sessions, authentication tokens, two-factor
350 and unified sign in secrets. The user's password is not affected.
351
352 USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
353
354 """
355 user_obj = lookup_identity(user)
356 if user_obj is None:
357 raise click.UsageError("User not found.")
358 _datastore.reset_user_access(user_obj)
359 click.secho(
360 f'User "{user}" authentication credentials have been reset.', fg="green"
361 )
362
363
364 @users.command("change_password")
365 @click.argument("user")
366 @click.password_option()
367 @with_appcontext
368 @commit
369 def users_change_password(user, password):
370 """
371 Administratively change a user's password.
372 All the user's sessions will be immediately invalidated.
373 You will have to inform the user via an out of band mechanism
374 what their new password is.
375
376 USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
377
378 """
379 user_obj = lookup_identity(user)
380 if user_obj is None:
381 raise click.UsageError("User not found.")
382
383 kwargs = {"password": password, "password_confirm": password}
384 form = _build_form("reset_password_form", meta={"csrf": False}, **kwargs)
385 form.user = user_obj
386
387 if form.validate():
388 # validation will normalize password
389 admin_change_password(user_obj, form.password.data, notify=False)
390 else:
391 raise click.UsageError(f"Error changing password. {fix_errors(form.errors)}")