Beispiel #1
0
    def get_principals(
        self, role, anonymous=True, users=True, groups=True, object=None, as_list=True
    ):
        """Return all users which are assigned given role."""
        if not isinstance(role, Role):
            role = Role(role)
        assert role
        assert users or groups
        query = RoleAssignment.query.filter_by(role=role)

        if not anonymous:
            query = query.filter(RoleAssignment.anonymous == False)
        if not users:
            query = query.filter(RoleAssignment.user == None)
        elif not groups:
            query = query.filter(RoleAssignment.group == None)

        query = query.filter(RoleAssignment.object == object)
        principals = {(ra.user or ra.group) for ra in query.all()}

        if object is not None and role in (Creator, Owner):
            p = object.creator if role == Creator else object.owner
            if p:
                principals.add(p)

        if not as_list:
            return principals

        return list(principals)
Beispiel #2
0
class GroupAdminForm(Form):
    name = StringField(_l(u'Name'), filters=(strip,), validators=[required()])
    description = StringField(_l(u'Description'), filters=(strip,))

    public = BooleanField(
        _l(u'Public'), widget=widgets.BooleanWidget(on_off_mode=True))

    roles = fields.Select2MultipleField(
        _l(u'Roles'),
        choices=lambda: [(r.name, r.label) for r in Role.assignable_roles()],)
Beispiel #3
0
    def after_populate_obj(self):
        security = get_service('security')
        current_roles = security.get_roles(self.obj, no_group_roles=True)
        current_roles = {r for r in current_roles if r.assignable}
        new_roles = {Role(r) for r in self.form.roles.data}

        for r in (current_roles - new_roles):
            security.ungrant_role(self.obj, r)

        for r in (new_roles - current_roles):
            security.grant_role(self.obj, r)

        return super(GroupEdit, self).after_populate_obj()
Beispiel #4
0
    def after_populate_obj(self):
        security = current_app.services['security']
        current_roles = security.get_roles(self.obj, no_group_roles=True)
        current_roles = set(r for r in current_roles if r.assignable)
        new_roles = {Role(r) for r in self.form.roles.data}

        for r in (current_roles - new_roles):
            security.ungrant_role(self.obj, r)

        for r in (new_roles - current_roles):
            security.grant_role(self.obj, r)

        return super(UserEdit, self).after_populate_obj()
Beispiel #5
0
class BaseUserAdminForm(Form):

    email = StringField(
        _l("Email"),
        description=_l("Users log in with their email address."),
        view_widget=widgets.EmailWidget(),
        filters=(strip,),
        validators=[required()],
    )
    first_name = StringField(
        _l("First Name"),
        description=_l("ex: John"),
        filters=(strip,),
        validators=[required()],
    )
    last_name = StringField(
        _l("Last Name"),
        description=_l("ex: Smith"),
        filters=(strip,),
        validators=[required()],
    )

    can_login = BooleanField(
        _l("Login enabled"),
        description=_l("If unchecked, user will not be able to connect."),
        widget=widgets.BooleanWidget(),
    )

    groups = QuerySelect2Field(
        _l("Groups"),
        validators=(optional(),),
        multiple=True,
        collection_class=set,
        query_factory=lambda: Group.query.order_by(sa.sql.func.lower(Group.name).asc()),
        get_label="name",
    )

    roles = Select2MultipleField(
        _l("Roles"),
        description=_l(
            "Prefer groups to manage access rights. Directly assigning roles "
            "to users is possible but discouraged."
        ),
        choices=lambda: [(r.name, r.label) for r in Role.assignable_roles()],
    )

    password = StringField(
        _l("New Password"),
        description=_l("If empty the current password will not be changed."),
        widget=widgets.PasswordInput(autocomplete="off"),
    )
Beispiel #6
0
    def get_principals(
        self,
        role: Role,
        anonymous: bool = True,
        users: bool = True,
        groups: bool = True,
        object: Optional[Model] = None,
        as_list: bool = True,
    ) -> Collection[Principal]:
        """Return all users which are assigned given role."""
        if not isinstance(role, Role):
            role = Role(role)
        assert role
        assert users or groups
        query = RoleAssignment.query.filter_by(role=role)

        if not anonymous:
            query = query.filter(RoleAssignment.anonymous == False)
        if not users:
            query = query.filter(RoleAssignment.user == None)
        elif not groups:
            query = query.filter(RoleAssignment.group == None)

        query = query.filter(RoleAssignment.object == object)
        principals = {(ra.user or ra.group) for ra in query.all()}

        if object is not None and role in (Creator, Owner):
            # pyre-fixme[16]: `Model` has no attribute `creator`.
            # pyre-fixme[16]: `Model` has no attribute `owner`.
            p = object.creator if role == Creator else object.owner
            if p:
                principals.add(p)

        if not as_list:
            return principals

        return list(principals)
Beispiel #7
0
    def has_permission(self, user, permission, obj=None, inherit=False, roles=None):
        """
        :param obj: target object to check permissions.
        :param inherit: check with permission inheritance. By default, check only
                        local roles.
        :param roles: additional valid role or iterable of roles having
                      `permission`.
        """
        if not isinstance(permission, Permission):
            assert permission in PERMISSIONS
            permission = Permission(permission)
        user = unwrap(user)

        if not self.running:
            return True

        session = None
        if obj is not None:
            session = object_session(obj)

        if session is None:
            session = db.session()

        # root always have any permission
        if isinstance(user, User) and user.id == 0:
            return True

        # valid roles
        # 1: from database
        pa_filter = PermissionAssignment.object == None
        if obj is not None and obj.id is not None:
            pa_filter |= PermissionAssignment.object == obj

        pa_filter &= PermissionAssignment.permission == permission
        valid_roles = session.query(PermissionAssignment.role).filter(pa_filter)
        valid_roles = {res[0] for res in valid_roles.yield_per(1000)}

        # complete with defaults
        valid_roles |= {Admin}  # always have all permissions
        valid_roles |= DEFAULT_PERMISSION_ROLE.get(permission, set())

        # FIXME: obj.__class__ could define default permisssion matrix too

        if roles is not None:
            if isinstance(roles, (Role,) + string_types):
                roles = (roles,)

            for r in roles:
                valid_roles.add(Role(r))

        # FIXME: query permission_role: global and on object

        if AnonymousRole in valid_roles:
            return True

        if Authenticated in valid_roles and not user.is_anonymous:
            return True

        # first test global roles, then object local roles
        checked_objs = [None, obj]
        if inherit and obj is not None:
            while obj.inherit_security and obj.parent is not None:
                obj = obj.parent
                checked_objs.append(obj)

        principals = [user] + list(user.groups)
        self._fill_role_cache_batch(principals)

        return any(
            (
                self.has_role(principal, valid_roles, item)
                for principal in principals
                for item in checked_objs
            )
        )