File: cli.py

package info (click to toggle)
flask-security 5.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,448 kB
  • sloc: python: 23,247; javascript: 204; makefile: 138
file content (387 lines) | stat: -rw-r--r-- 11,804 bytes parent folder | download | duplicates (2)
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
"""
flask_security.cli
~~~~~~~~~~~~~~~~~~

Command Line Interface for managing accounts and roles.

:copyright: (c) 2016 by CERN.
:copyright: (c) 2019-2024 by J. Christopher Wagner
:license: MIT, see LICENSE for more details.
"""

import functools

import click
from flask import current_app
from werkzeug.local import LocalProxy
from .quart_compat import get_quart_status

from .changeable import admin_change_password
from .forms import build_form
from .utils import (
    lookup_identity,
    get_identity_attributes,
    get_identity_attribute,
    hash_password,
)

if get_quart_status():  # pragma: no cover
    import quart.cli

    # quart cli doesn't provide the with_appcontext function
    def with_appcontext(f):
        """Wraps a callback so that it's guaranteed to be executed with the
        script's application context.  If callbacks are registered directly
        to the ``app.cli`` object then they are wrapped with this function
        by default unless it's disabled.
        """

        @click.pass_context
        def decorator(__ctx, *args, **kwargs):
            with __ctx.ensure_object(quart.cli.ScriptInfo).load_app().app_context():
                return __ctx.invoke(f, *args, **kwargs)

        return functools.update_wrapper(decorator, f)

else:
    import flask.cli

    with_appcontext = flask.cli.with_appcontext


_security = LocalProxy(lambda: current_app.extensions["security"])
_datastore = LocalProxy(lambda: current_app.extensions["security"].datastore)


def commit(fn):
    """Decorator to commit changes in datastore."""

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        fn(*args, **kwargs)
        _datastore.commit()

    return wrapper


def fix_errors(form_errors):
    # Form errors might have lazy text which normally would be processed by
    # render_template
    errors = {}
    for k, v in form_errors.items():
        errors[k] = [str(e) for e in v]
    return errors


@click.group()
def users():
    """User commands.

    For commands that require a USER - pass in any identity attribute.
    """


@click.group()
def roles():
    """Role commands."""


@users.command(
    "create",
    epilog=(
        "Example: users create me@me.com --password 'battery staple' --active"
        "\n"
        "Example: users create me2@me.cmo --password 'battery staple' --active"
        "   --username mememe us_phone_number:6505551212"
    ),
)
@click.argument(
    "attributes",
    nargs=-1,
)
@click.password_option()
@click.option(
    "-a", "--active", default=False, is_flag=True, help="Mark new user as active"
)
@click.option(
    "-u",
    "--username",
    required=False,
    default=None,
    help="Available only if SECURITY_USERNAME_ENABLE is set",
)
@with_appcontext
@commit
def users_create(attributes, password, active, username):
    """Create a user.

    Create a new user with one or more attributes using the syntax:
    ``attribute:value``. If attr isn't set 'email' is presumed.
    Identity attribute values will be validated using the configured
    confirm_register_form;
    however, any ADDITIONAL attribute:value pairs will be sent directly to
    datastore.create_user().

    Note that unless the ``--active`` option is set, the new user won't ba able
    to sign in or perform any other action

    """
    kwargs = {}

    identity_attributes = get_identity_attributes()
    for attrarg in attributes:
        # If given identity is an identity_attribute - do a bit of pre-validating
        # to provide nicer errors.
        attr = "email"
        if ":" in attrarg:
            attr, attrarg = attrarg.split(":")
        if attr in identity_attributes:
            details = get_identity_attribute(attr)
            idata = details["mapper"](attrarg)
            if not idata:
                raise click.UsageError(
                    f"Attr {attr} with value {attrarg} wasn't accepted by"
                    f" ``SECURITY_USER_IDENTITY_ATTRIBUTES``"
                )

        kwargs[attr] = attrarg
    kwargs["password"] = password
    if username:
        kwargs["username"] = username

    # We always add password_confirm here - if user used the CLI in input mode -
    # it already asked for confirmation.
    # if they used inline keywords, there really isn't any reason to make them type
    # it in twice.
    form = build_form(
        "confirm_register_form" if _security._use_confirm_form else "register_form",
        meta={"csrf": False},
        **kwargs,
        password_confirm=password,
    )

    if form.validate():
        # We don't use the form directly to provide values so that this CLI can actually
        # set any usermodel attribute. We do grab email and password from the form
        # so that we get any normalization results.
        kwargs["password"] = hash_password(form.password.data)
        kwargs["active"] = active
        # echo normalized email...
        if "email" in kwargs:
            kwargs["email"] = form.email.data
        # Exceptions could be an attribute given that isn't in user store
        try:
            _datastore.create_user(**kwargs)
        except TypeError as e:
            raise click.exceptions.BadParameter(e)
        click.secho("User created successfully.", fg="green")
        kwargs["password"] = "****"
        click.echo(kwargs)
    else:
        raise click.UsageError(f"Error creating user. {fix_errors(form.errors)}")


@roles.command("create")
@click.argument("name")
@click.option("-d", "--description", default=None)
@click.option("-p", "--permissions", help="A comma separated list")
@with_appcontext
@commit
def roles_create(**kwargs):
    """Create a role."""

    # For some reason Click puts arguments in kwargs - even if they weren't specified.
    if "permissions" in kwargs and not kwargs["permissions"]:
        del kwargs["permissions"]
    if "permissions" in kwargs and not hasattr(_datastore.role_model, "permissions"):
        raise click.UsageError("Role model does not support permissions")
    _datastore.create_role(**kwargs)
    click.secho('Role "%(name)s" created successfully.' % kwargs, fg="green")


@roles.command("add")
@click.argument("user")
@click.argument("role")
@with_appcontext
@commit
def roles_add(user, role):
    """Add role to user.

    USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
    """
    user_obj = lookup_identity(user)
    if user_obj is None:
        raise click.UsageError("User not found.")

    role = _datastore._prepare_role_modify_args(role)
    if role is None:
        raise click.UsageError("Cannot find role.")
    if _datastore.add_role_to_user(user_obj, role):
        click.secho(
            f'Role "{role.name}" added to user "{user}" successfully.',
            fg="green",
        )
    else:
        raise click.UsageError("Cannot add role to user.")


@roles.command("remove")
@click.argument("user")
@click.argument("role")
@with_appcontext
@commit
def roles_remove(user, role):
    """Remove role from user.

    USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
    """
    user_obj = lookup_identity(user)
    if user_obj is None:
        raise click.UsageError("User not found.")

    role = _datastore._prepare_role_modify_args(role)
    if role is None:
        raise click.UsageError("Cannot find role.")
    if _datastore.remove_role_from_user(user_obj, role):
        click.secho(
            f'Role "{role.name}" removed from user "{user}" successfully.',
            fg="green",
        )
    else:
        raise click.UsageError("Cannot remove role from user.")


@roles.command("add_permissions")
@click.argument("role")
@click.argument("permissions")
@with_appcontext
@commit
def roles_add_permissions(role, permissions):
    """Add permissions to role.

    Role is an existing role name.
    Permissions are a comma separated list.
    """
    role = _datastore._prepare_role_modify_args(role)
    if role is None:
        raise click.UsageError("Cannot find role.")
    permlist = [s.strip() for s in permissions.split(",")]
    if _datastore.add_permissions_to_role(role, permlist):
        click.secho(
            f'Permission(s) "{permissions}" added to role "{role.name}" successfully.',
            fg="green",
        )
    else:  # pragma: no cover
        raise click.UsageError("Cannot add permission(s) to role.")


@roles.command("remove_permissions")
@click.argument("role")
@click.argument("permissions")
@with_appcontext
@commit
def roles_remove_permissions(role, permissions):
    """Remove permissions from role.

    Role is an existing role name.
    Permissions are a comma separated list.
    """
    role = _datastore._prepare_role_modify_args(role)
    if role is None:
        raise click.UsageError("Cannot find role.")
    permlist = [s.strip() for s in permissions.split(",")]
    if _datastore.remove_permissions_from_role(role, permlist):
        click.secho(
            f'Permission(s) "{permissions}" removed from role'
            f' "{role.name}" successfully.',
            fg="green",
        )
    else:  # pragma: no cover
        raise click.UsageError("Cannot remove permission(s) from role.")


@users.command("activate")
@click.argument("user")
@with_appcontext
@commit
def users_activate(user):
    """Activate a user.

    USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
    """
    user_obj = lookup_identity(user)
    if user_obj is None:
        raise click.UsageError("User not found.")
    if _datastore.activate_user(user_obj):
        click.secho(f'User "{user}" has been activated.', fg="green")
    else:
        click.secho(f'User "{user}" was already activated.', fg="yellow")


@users.command("deactivate")
@click.argument("user")
@with_appcontext
@commit
def users_deactivate(user):
    """Deactivate a user.

    USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.
    """
    user_obj = lookup_identity(user)
    if user_obj is None:
        raise click.UsageError("User not found.")
    if _datastore.deactivate_user(user_obj):
        click.secho(f'User "{user}" has been deactivated.', fg="green")
    else:
        click.secho(f'User "{user}" was already deactivated.', fg="yellow")


@users.command("reset_access")
@click.argument("user")
@with_appcontext
@commit
def users_reset_access(user):
    """Reset all authentication credentials for user.
    This includes sessions, authentication tokens, two-factor
    and unified sign in secrets. The user's password is not affected.

    USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.

    """
    user_obj = lookup_identity(user)
    if user_obj is None:
        raise click.UsageError("User not found.")
    _datastore.reset_user_access(user_obj)
    click.secho(
        f'User "{user}" authentication credentials have been reset.', fg="green"
    )


@users.command("change_password")
@click.argument("user")
@click.password_option()
@with_appcontext
@commit
def users_change_password(user, password):
    """
    Administratively change a user's password.
    All the user's sessions will be immediately invalidated.
    You will have to inform the user via an out of band mechanism
    what their new password is.

    USER is identity as defined by SECURITY_USER_IDENTITY_ATTRIBUTES.

    """
    user_obj = lookup_identity(user)
    if user_obj is None:
        raise click.UsageError("User not found.")

    kwargs = {"password": password, "password_confirm": password}
    form = build_form("reset_password_form", meta={"csrf": False}, **kwargs)
    form.user = user_obj

    if form.validate():
        # validation will normalize password
        admin_change_password(user_obj, form.password.data, notify=False)
    else:
        raise click.UsageError(f"Error changing password. {fix_errors(form.errors)}")