Python flask_principal.RoleNeed() Examples

The following are 26 code examples of flask_principal.RoleNeed(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_principal , or try the search function .
Example #1
Source File: permissions.py    From gitmark with GNU General Public License v2.0 8 votes vote down vote up
def on_identity_loaded(sender, identity):
    # Set the identity user object
    identity.user = current_user

    # Add the UserNeed to the identity
    if hasattr(current_user, 'username'):
        identity.provides.add(UserNeed(current_user.username))

    # Assuming the User model has a list of roles, update the
    # identity with the roles that the user provides
    if hasattr(current_user, 'role'):
        # for role in current_user.roles:
        identity.provides.add(RoleNeed(current_user.role))
    
    # if current_user.is_superuser:
    if hasattr(current_user, 'is_superuser') and current_user.is_superuser:
        identity.provides.add(su_need)
        # return current_user.role

    identity.allow_su = su_permission.allows(identity)
    identity.allow_admin = admin_permission.allows(identity)
    identity.allow_edit = editor_permission.allows(identity)
    identity.allow_general = general_permission.allows(identity) 
Example #2
Source File: test_record_permissions.py    From invenio-app-ils with MIT License 6 votes vote down vote up
def test_record_patron_create(client, db, users, with_role_creator):
    """Test patron create."""

    tests = [
        ({"foo": "bar"}, "create", True),
        ({"foo": "bar"}, "update", False),
        ({"foo": "bar"}, "delete", False),
    ]

    @identity_loaded.connect
    def add_roles_to_identity(sender, identity):
        """Provide additional role to the user."""
        roles = [RoleNeed("records-creators")]
        identity.provides |= set(roles)

    for access, action, is_allowed in tests:
        # create role to be able to create records
        user_login(client, "patron1", users)

        id = uuid.uuid4()
        record = Record.create(access, id_=id)
        factory = RecordPermission(record, action)

        assert factory.can() if is_allowed else not factory.can() 
Example #3
Source File: permissions.py    From training with MIT License 5 votes vote down vote up
def owner_manager_permission_factory(record=None):
    """Returns permission for managers group."""
    return Permission(UserNeed(record["owner"]), RoleNeed('managers')) 
Example #4
Source File: view_admin.py    From flicket with MIT License 5 votes vote down vote up
def on_identity_loaded(sender, identity):
    # set the identity user object
    identity.user = current_user
    # Add the UserNeed to the identity
    if hasattr(current_user, 'id'):
        identity.provides.add(UserNeed(current_user.id))

    # Assuming the User model has a list of groups, update the
    # identity with the groups that the user provides
    if hasattr(current_user, 'flicket_groups'):
        the_user = FlicketUser.query.filter_by(id=current_user.id).first()
        for g in the_user.flicket_groups:
            identity.provides.add(RoleNeed('{}'.format(g.group_name))) 
Example #5
Source File: decorators.py    From flask-react-spa with MIT License 5 votes vote down vote up
def roles_accepted(*roles):
    """Decorator which specifies that a user must have at least one of the
    specified roles.

    Aborts with HTTP: 403 if the user doesn't have at least one of the roles

    Example::

        @app.route('/create_post')
        @roles_accepted('ROLE_ADMIN', 'ROLE_EDITOR')
        def create_post():
            return 'Create Post'

    The current user must have either the `ROLE_ADMIN` role or `ROLE_EDITOR`
    role in order to view the page.

    :param args: The possible roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perm = Permission(*[RoleNeed(role) for role in roles])
            if not perm.can():
                abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper 
Example #6
Source File: decorators.py    From flask-react-spa with MIT License 5 votes vote down vote up
def roles_required(*roles):
    """Decorator which specifies that a user must have all the specified roles.

    Aborts with HTTP 403: Forbidden if the user doesn't have the required roles

    Example::

        @app.route('/dashboard')
        @roles_required('ROLE_ADMIN', 'ROLE_EDITOR')
        def dashboard():
            return 'Dashboard'

    The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles
    in order to view the page.

    :param args: The required roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perms = [Permission(RoleNeed(role)) for role in roles]
            for perm in perms:
                if not perm.can():
                    abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper 
Example #7
Source File: extension.py    From flask-react-spa with MIT License 5 votes vote down vote up
def on_identity_loaded(sender, identity):
    role_names = set()
    for role in getattr(current_user, 'roles', []):
        role_names = role_names.union(set(_get_role_hierarchy(role.name)))
    for role_name in role_names:
        identity.provides.add(RoleNeed(role_name)) 
Example #8
Source File: main.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def on_identity_loaded(sender, identity):
    """Helper for flask-principal."""
    # Set the identity user object
    identity.user = current_user

    # Add the UserNeed to the identity
    if hasattr(current_user, "id"):
        identity.provides.add(UserNeed(current_user.id))

    try:
        if current_user.is_admin:
            identity.provides.add(RoleNeed("admin"))
    except AttributeError:
        pass  # Definitely not an admin 
Example #9
Source File: app.py    From maple-bbs with GNU General Public License v3.0 5 votes vote down vote up
def init_app(app):
    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        '''基础权限'''
        identity.user = current_user

        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))

        if hasattr(current_user, 'is_superuser'):
            if current_user.is_superuser:
                identity.provides.add(RoleNeed('super'))

        if hasattr(current_user, 'is_confirmed'):
            if current_user.is_confirmed:
                identity.provides.add(RoleNeed('confirmed'))

        if hasattr(current_user, 'is_authenticated'):
            if current_user.is_authenticated:
                identity.provides.add(RoleNeed('auth'))
            else:
                identity.provides.add(RoleNeed('guest'))

        if hasattr(current_user, 'topics'):
            for topic in current_user.topics:
                identity.provides.add(TopicNeed(topic.id))

        if hasattr(current_user, 'replies'):
            for reply in current_user.replies:
                identity.provides.add(ReplyNeed(reply.id))

        if hasattr(current_user, 'collects'):
            for collect in current_user.collects:
                identity.provides.add(CollectNeed(collect.id)) 
Example #10
Source File: security.py    From flask-unchained with MIT License 5 votes vote down vote up
def _on_identity_loaded(self, sender, identity: Identity) -> None:
        """
        Callback that runs whenever a new identity has been loaded.
        """
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))

        for role in getattr(current_user, 'roles', []):
            identity.provides.add(RoleNeed(role.name))

        identity.user = current_user 
Example #11
Source File: roles_required.py    From flask-unchained with MIT License 5 votes vote down vote up
def roles_required(*roles):
    """
    Decorator which specifies that a user must have all the specified roles.

    Aborts with HTTP 403: Forbidden if the user doesn't have the required roles.

    Example::

        @app.route('/dashboard')
        @roles_required('ROLE_ADMIN', 'ROLE_EDITOR')
        def dashboard():
            return 'Dashboard'

    The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles
    in order to view the page.

    :param roles: The required roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perms = [Permission(RoleNeed(role)) for role in roles]
            for perm in perms:
                if not perm.can():
                    abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper 
Example #12
Source File: roles_accepted.py    From flask-unchained with MIT License 5 votes vote down vote up
def roles_accepted(*roles):
    """
    Decorator which specifies that a user must have at least one of the
    specified roles.

    Aborts with HTTP: 403 if the user doesn't have at least one of the roles.

    Example::

        @app.route('/create_post')
        @roles_accepted('ROLE_ADMIN', 'ROLE_EDITOR')
        def create_post():
            return 'Create Post'

    The current user must have either the `ROLE_ADMIN` role or `ROLE_EDITOR`
    role in order to view the page.

    :param roles: The possible roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perm = Permission(*[RoleNeed(role) for role in roles])
            if not perm.can():
                abort(HTTPStatus.FORBIDDEN)
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper 
Example #13
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def on_identity_loaded(sender, identity):
	user = load_user(identity.id)
	if user is None:
		return

	identity.provides.add(UserNeed(user.get_name()))
	if user.is_user():
		identity.provides.add(RoleNeed("user"))
	if user.is_admin():
		identity.provides.add(RoleNeed("admin")) 
Example #14
Source File: permissions.py    From lemur with Apache License 2.0 5 votes vote down vote up
def __init__(self, authority_id, roles):
        needs = [RoleNeed("admin"), AuthorityCreatorNeed(str(authority_id))]
        for r in roles:
            needs.append(AuthorityOwnerNeed(str(r)))

        super(AuthorityPermission, self).__init__(*needs) 
Example #15
Source File: permissions.py    From lemur with Apache License 2.0 5 votes vote down vote up
def __init__(self, role_id):
        needs = [RoleNeed("admin"), RoleMemberNeed(role_id)]
        super(RoleMemberPermission, self).__init__(*needs) 
Example #16
Source File: permissions.py    From lemur with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(ApiKeyCreatorPermission, self).__init__(RoleNeed("admin")) 
Example #17
Source File: permissions.py    From lemur with Apache License 2.0 5 votes vote down vote up
def __init__(self, owner, roles):
        needs = [RoleNeed("admin"), RoleNeed(owner), RoleNeed("creator")]
        for r in roles:
            needs.append(CertificateOwnerNeed(str(r)))
            # Backwards compatibility with mixed-case role names
            if str(r) != str(r).lower():
                needs.append(CertificateOwnerNeed(str(r).lower()))

        super(CertificatePermission, self).__init__(*needs) 
Example #18
Source File: permissions.py    From lemur with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        needs = [RoleNeed("admin")]
        sensitive_domain_roles = current_app.config.get("SENSITIVE_DOMAIN_ROLES", [])

        if sensitive_domain_roles:
            for role in sensitive_domain_roles:
                needs.append(RoleNeed(role))

        super(SensitiveDomainPermission, self).__init__(*needs) 
Example #19
Source File: engine.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def blogger_permission(self):
        if self._blogger_permission is None:
            if self.config.get("BLOGGING_PERMISSIONS", False):
                self._blogger_permission = Permission(RoleNeed(
                    self.config.get("BLOGGING_PERMISSIONNAME", "blogger")))
            else:
                self._blogger_permission = Permission()
        return self._blogger_permission 
Example #20
Source File: __init__.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *needs):
        '''Let administrator bypass all permissions'''
        super(Permission, self).__init__(RoleNeed('admin'), *needs) 
Example #21
Source File: core.py    From flask-security with MIT License 5 votes vote down vote up
def _on_identity_loaded(sender, identity):
    if hasattr(current_user, "fs_uniquifier"):
        identity.provides.add(UserNeed(current_user.fs_uniquifier))

    for role in getattr(current_user, "roles", []):
        identity.provides.add(RoleNeed(role.name))
        for fsperm in role.get_permissions():
            identity.provides.add(FsPermNeed(fsperm))

    identity.user = current_user 
Example #22
Source File: decorators.py    From flask-security with MIT License 5 votes vote down vote up
def roles_accepted(*roles):
    """Decorator which specifies that a user must have at least one of the
    specified roles. Example::

        @app.route('/create_post')
        @roles_accepted('editor', 'author')
        def create_post():
            return 'Create Post'

    The current user must have either the `editor` role or `author` role in
    order to view the page.

    :param roles: The possible roles.
    """

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perm = Permission(*[RoleNeed(role) for role in roles])
            if perm.can():
                return fn(*args, **kwargs)
            if _security._unauthorized_callback:
                # Backwards compat - deprecated
                return _security._unauthorized_callback()
            return _security._unauthz_handler(roles_accepted, list(roles))

        return decorated_view

    return wrapper 
Example #23
Source File: decorators.py    From flask-security with MIT License 5 votes vote down vote up
def roles_required(*roles):
    """Decorator which specifies that a user must have all the specified roles.
    Example::

        @app.route('/dashboard')
        @roles_required('admin', 'editor')
        def dashboard():
            return 'Dashboard'

    The current user must have both the `admin` role and `editor` role in order
    to view the page.

    :param roles: The required roles.
    """

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perms = [Permission(RoleNeed(role)) for role in roles]
            for perm in perms:
                if not perm.can():
                    if _security._unauthorized_callback:
                        # Backwards compat - deprecated
                        return _security._unauthorized_callback()
                    return _security._unauthz_handler(roles_required, list(roles))
            return fn(*args, **kwargs)

        return decorated_view

    return wrapper 
Example #24
Source File: permissions.py    From invenio-app-ils with MIT License 5 votes vote down vote up
def record_needs(self):
        """Create needs of the record."""
        needs = []
        for access_entity in self.record_explicit_restrictions():
            try:
                if isinstance(access_entity, string_types):
                    needs.append(UserNeed(int(access_entity)))
                elif isinstance(access_entity, int):
                    needs.append(UserNeed(access_entity))
            except ValueError:
                needs.append(RoleNeed(access_entity.lower()))
        return needs 
Example #25
Source File: __init__.py    From incepiton-mysql with MIT License 4 votes vote down vote up
def create_app(config_name):
    """
    application initialization
    :param config_name:
    :return:
    """

    app = Flask(__name__)
    app.config.from_object(config[config_name])

    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    ldap.init_app(app)

    # flask_principal
    principals.init_app(app)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        identity.user = current_user

        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))

        if hasattr(current_user, 'role'):
            identity.provides.add(RoleNeed(current_user.role))

    # celery
    celery.init_app(app)

    # register blue_print
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint)

    from .audit import audit as audit_blueprint
    app.register_blueprint(audit_blueprint)

    from .dev import dev as dev_blueprint
    app.register_blueprint(dev_blueprint)

    return app 
Example #26
Source File: test_record_permissions.py    From invenio-app-ils with MIT License 4 votes vote down vote up
def test_record_generic_access(client, db, users, with_access):
    """Test access control for records."""

    tests = [
        ({"foo": "bar"}, "read", True),
        ({"foo": "bar"}, "update", False),
        ({"_access": {"read": [1]}}, "read", True),
        ({"_access": {"read": [2]}}, "read", False),
        ({"_access": {"read": ["records-readers"]}}, "read", True),
        # permission for specific user to create
        ({"_access": {"update": [1]}}, "update", True),
        # checks if the access works for different actions
        ({"_access": {"update": [1]}}, "create", False),
        ({"_access": {"delete": [1]}}, "update", False),
        # delete access for user and librarian
        ({"_access": {"delete": [1, "librarian"]}}, "delete", True),
    ]

    @identity_loaded.connect
    def add_roles_to_identity(sender, identity):
        """Provide additional role to the user."""
        roles = [RoleNeed("records-readers")]
        identity.provides |= set(roles)

    def login_and_test(username):
        user = user_login(client, username, users)
        # Create record
        id = uuid.uuid4()
        record = Record.create(access, id_=id)
        factory = RecordPermission(record, action)
        if user.has_role("admin"):
            # super user can do EVERYTHING
            assert factory.can()
        elif user.has_role("librarian") and action != "delete":
            # librarian should be able to update, create, and read everything
            assert factory.can()
        else:
            assert factory.can() if is_allowed else not factory.can()

    for access, action, is_allowed in tests:
        # Test standard user
        login_and_test("patron1")
        # Test librarian access
        login_and_test("librarian")
        # Test superuser access
        login_and_test("admin")