Пример #1
0
    def verify_user(self, login_id=None, password=None):
        user = self.user_ent.query.filter_by(username=login_id).one_or_none()

        if not user:
            username_key = get_username_key(self.user_ent)
            user = self.user_ent.add(**{username_key: login_id})
        if password and not self.verify_password(user, password):
            raise UserInvalidAuth(user)

        return user
Пример #2
0
    def set_user_password(username):
        auth_manager = keg.current_app.auth_manager
        user_ent = auth_manager.entity_registry.user_cls
        user = user_ent.get_by(**{get_username_key(user_ent): username})

        if user is None:
            click.echo('Unknown user', err=True)
            return

        password_policy = auth_manager.password_policy_cls()
        password = click.prompt('Password',
                                type=PasswordType(password_policy, user),
                                hide_input=True,
                                confirmation_prompt=True)
        user.change_password(user.token_generate(), password)
Пример #3
0
    def check_does_not_contain_username(self, pw: str, user):
        """
        Raises PasswordPolicyError if the password contains the username. This is case insensitive.
        :param pw: password to check
        :param user: user entity
        """
        user_cls = user.__class__
        username_key = get_username_key(user_cls)
        username = getattr(user, username_key)
        username_col = getattr(user_cls, username_key)
        if isinstance(username_col.type, EmailType):
            username = user.username.split('@')[0]

        if username.casefold() in pw.casefold():
            raise PasswordPolicyError(_('Password may not contain username'))
Пример #4
0
def user_form(config=None,
              allow_superuser=False,
              endpoint='',
              fields=['is_enabled', 'disabled_utc']):
    """Returns a form for User CRUD.

    Form is customized depending on the fields and superuser setting passed in."""
    config = config or {}
    user_cls = flask.current_app.auth_manager.entity_registry.user_cls

    # The model can be assumed to have a `username` attribute. However, it may not be settable,
    # depending on whether it is actually a column, or is instead a proxy to another column
    # (e.g. email). So, we will need to grab a key to use for it that matches the data column.
    username_key = get_username_key(
        flask.current_app.auth_manager.entity_registry.user_cls)

    # create a copy of fields for internal use. In python 2, if we use this as a static method,
    #   the kwarg value would get modified in the wrong scope
    _fields = [username_key] + fields[:]
    if allow_superuser and 'is_superuser' not in _fields:
        _fields.append('is_superuser')

    def html_link(obj):
        return link_to(obj.username, flask.url_for(endpoint, objid=obj.id))

    def filter_disabled_utc(date):
        if isinstance(date, dt.date):
            date = arrow.get(date)

        return date

    class User(PermissionsMixin, BundlesMixin, GroupsMixin, ModelForm):
        disabled_utc = DateField('Disable Date', [validators.Optional()],
                                 filters=[filter_disabled_utc],
                                 render_kw={'type': 'date'})

        class Meta:
            model = user_cls
            only = _fields

        class FieldsMeta:
            is_enabled = FieldMeta('Enabled')
            is_superuser = FieldMeta('Superuser')
            __default__ = FieldMeta

        field_order = tuple(_fields +
                            ['group_ids', 'bundle_ids', 'permission_ids'])

        setattr(
            FieldsMeta, username_key,
            FieldMeta(extra_validators=[
                validators.data_required(),
                ValidateUnique(html_link)
            ]))

        if isinstance(
                flask.current_app.auth_manager.entity_registry.user_cls.
                username.type, EmailType):
            getattr(FieldsMeta, username_key).widget = EmailInput()

        if not config.get('KEGAUTH_EMAIL_OPS_ENABLED'):
            reset_password = PasswordField(
                _('New Password'),
                validators=[
                    _ValidatePasswordRequired(),
                    validators.EqualTo('confirm',
                                       message=_('Passwords must match'))
                ])
            confirm = PasswordField(_('Confirm Password'))
            field_order = field_order + ('reset_password', 'confirm')
        else:
            # place a Send Welcome field after the initial set of fields
            send_welcome = BooleanField('Send Welcome Email', default=True)
            field_order = tuple(_fields + ['send_welcome'] +
                                list(field_order[len(_fields):]))

        def get_object_by_field(self, field):
            return user_cls.get_by(username=field.data)

        @property
        def obj(self):
            return self._obj

        def __iter__(self):
            if hasattr(self, 'csrf_token'):
                field_ids = ('csrf_token', ) + self.field_order
            else:
                field_ids = self.field_order
            return (getattr(self, field_id) for field_id in field_ids)

        def after_init(self, args, kwargs):
            if kwargs.get('obj') and hasattr(self, 'send_welcome'):
                self.send_welcome = None
                self.field_order = tuple(
                    filter(lambda v: v != 'send_welcome', self.field_order))

            return super().after_init(args, kwargs)

    return User