コード例 #1
0
def on_identity_loaded(sender, identity):

    if identity.id is not None:
        from zou.app.services import persons_service

        try:
            identity.user = persons_service.get_person(identity.id)

            if hasattr(identity.user, "id"):
                identity.provides.add(UserNeed(identity.user["id"]))

            if identity.user is None:
                raise PersonNotFoundException

            if identity.user["role"] == "admin":
                identity.provides.add(RoleNeed("admin"))
                identity.provides.add(RoleNeed("manager"))

            if identity.user["role"] == "manager":
                identity.provides.add(RoleNeed("manager"))

            if identity.user["role"] == "client":
                identity.provides.add(RoleNeed("client"))

            if not identity.user["active"]:
                current_app.logger.error("Current user is not active anymore")
                logout()
                return wrong_auth_handler(identity.user)

            return identity
        except PersonNotFoundException:
            return wrong_auth_handler()
        except TimeoutError:
            current_app.logger.error("Identity loading timed out")
            return wrong_auth_handler()
        except Exception as exception:
            current_app.logger.error(exception, exc_info=1)
            if hasattr(exception, "message"):
                current_app.logger.error(exception.message)
            return wrong_auth_handler()
コード例 #2
0
ファイル: __init__.py プロジェクト: pbatthala/bearing_project
def on_identity_loaded(sender, identity):
    """
    视图层模块的权限控制
    :param sender:
    :param identity:
    :return:
    """
    # Set the identity user object
    identity.user = current_user

    if not (hasattr(current_user, 'id') and hasattr(current_user, 'role_id')):
        return

    # Add the UserNeed to the identity
    identity.provides.add(UserNeed(current_user.id))

    # 角色 - 系统
    if current_user.role_id == TYPE_ROLE_SYSTEM:
        identity_role_administrator.setup(identity)

    # 角色 - 销售
    if current_user.role_id == TYPE_ROLE_SALES:
        identity_role_sales.setup(identity)

    # 角色 - 采购
    if current_user.role_id == TYPE_ROLE_PURCHASER:
        identity_role_purchaser.setup(identity)

    # 角色 - 经理
    if current_user.role_id == TYPE_ROLE_MANAGER:
        identity_role_manager.setup(identity)

    # 角色 - 库管
    if current_user.role_id == TYPE_ROLE_STOREKEEPER:
        identity_role_stock_keeper.setup(identity)

    # 角色 - 财务
    if current_user.role_id == TYPE_ROLE_ACCOUNTANT:
        identity_role_accountant.setup(identity)
コード例 #3
0
def on_identity_loaded(sender, identity):
        # 设置当前用户身份为login登录对象
        identity.user = current_user

        # 添加UserNeed到identity user对象
        if hasattr(current_user, 'id'):
            identity.provides.add(UserNeed(current_user.id))

        # 将Role添加到identity user对象
        if hasattr(current_user, 'role'):
            identity.provides.add(RoleNeed(current_user.role))

        if hasattr(current_user, 'is_su_user') and current_user.is_su_user:
            identity.provides.add(RoleNeed('su'))


        # 把身份添加到权限里面
        identity.allow_su = su_permission.allows(identity)
        identity.allow_admin = admin_permission.allows(identity)
        identity.allow_edit = editor_permission.allows(identity)
        identity.allow_write = writer_permission.allows(identity)
        identity.allow_read = reader_permission.allows(identity)
コード例 #4
0
def on_identity_loaded(sender, identity):


    # Set the identity user object
    identity.user = current_user
    #user has the permission of edit himself

    identity.provides.add(EditUserPermission(current_user.id))

    # Add the UserNeed to the identity
    if hasattr(current_user, 'id'):
        identity.provides.add(UserNeed(current_user.id))
        for role in current_user.roles:
            identity.provides.add(RoleNeed(role.roleName))
        
    # Assuming the User model has a list of nodes, update the
    # identity with the nodes that the user provides
    if hasattr(current_user,"roles"):
        for role in current_user.roles:
            for node in role.nodes:
                if (node.status==1) and (current_user.status==1) and (role.status==1):
                    identity.provides.add(ActionNeed(node.nodeName))
コード例 #5
0
def edit_post(id):
    #  if not g.current_user:
    #  return redirect(url_for('main.login'))

    post = Post.query.get_or_404(id)
    permission = Permission(UserNeed(post.user.id))

    # 同时希望管理员可以修改任何文章
    if permission.can() or admin_permission.can():
        form = PostForm()

        if form.validate_on_submit():
            title = form.title.data
            text = form.text.data
            post.change(title, text)

            return redirect(url_for('.post', post_id=post.id))

        form.text.data = post.text
        return render_template('blog/edit.html', form=form, post=post)

    abort(403)
コード例 #6
0
ファイル: views.py プロジェクト: zhchnchn/flask-repo
def edit_post(post_id):
    post = Post.query.get_or_404(post_id)

    permission = Permission(UserNeed(post.user_id))
    # 除了文章作者,我们希望管理员也可以修改任何文章
    if permission.can() or admin_permission.can():
        form = PostForm()
        if form.validate_on_submit():
            post.title = form.title.data
            post.text = form.text.data
            post.publish_date = datetime.datetime.utcnow()

            db.session.add(post)
            db.session.commit()
            flash('The post has been updated.', category='success')
            return redirect(url_for('.post', post_id=post.id))

        form.text.data = post.text
        return render_template('edit_post.html', form=form, post=post)

    # 如果没有权限,直接返回403错误
    abort(403)
コード例 #7
0
def on_identity_loaded(sender, identity):
    if identity.id is not None:
        from zou.app.services import persons_service
        try:
            identity.user = persons_service.get_person(identity.id)

            if hasattr(identity.user, "id"):
                identity.provides.add(UserNeed(identity.user["id"]))

            if identity.user["role"] == "admin":
                identity.provides.add(RoleNeed("admin"))
                identity.provides.add(RoleNeed("manager"))

            if identity.user["role"] == "manager":
                identity.provides.add(RoleNeed("manager"))

            return identity
        except PersonNotFoundException:
            return None
        except Exception as exception:
            current_app.logger.error(exception.message)
            return None
コード例 #8
0
def install_default_user_permissions(identity):
    '''
    Add permisisons that the current user should be able to perform
    regardless of whatever other roles they possess.
    '''
    identity.provides.add(UserNeed(identity.user.id))

    # TODO(vedant) - This should not be hardcoded.
    # Always allow the user to view their profile
    identity.provides.add(ItemNeed('view_resource', identity.user.id, 'user'))

    # HACK(vedant) - Fixed as part of a short term solution for T2113
    # The long term solution is to define default permissions or a default user group that all new
    # users should be added to.
    identity.provides.add(ItemNeed('create_resource', None, 'dashboard'))

    # Continuation of Work for T2148 but now allowing RO-access to all Potion APIs
    identity.provides.add(ItemNeed('view_resource', None, 'user'))
    identity.provides.add(ItemNeed('view_resource', None, 'group'))
    identity.provides.add(ItemNeed('view_resource', None, 'role'))
    identity.provides.add(ItemNeed('view_resource', None, 'resource'))
    identity.provides.add(ItemNeed('view_resource', None, 'configuration'))
コード例 #9
0
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_edit = editor_permission.allows(identity)
    identity.allow_admin = admin_permission.allows(identity)
    identity.allow_write = writer_permission.allows(identity)
コード例 #10
0
def test_owner_permissions(app, db, community, authenticated_user):
    """Test owner system role permissions."""
    login_user(authenticated_user)
    assert len(g.identity.provides) == 4
    assert community_record_owner in g.identity.provides

    permissions = require_any(
        # Approval is granted either by user role
        Permission(ParameterizedActionNeed(COMMUNITY_REQUEST_APPROVAL, community[0])),
        require_all(
            # Or user id must match and record owners must be granted the action
            Permission(UserNeed(authenticated_user.id)),
            Permission(ParameterizedActionNeed(f'owner-{COMMUNITY_REQUEST_APPROVAL}', community[0]))
        )
    )

    assert not permissions().can()

    db.session.add(
        ActionSystemRoles(action=f'owner-{COMMUNITY_REQUEST_APPROVAL}', role_name=community_record_owner.value,
                          argument=community[0]))

    assert permissions().can()
コード例 #11
0
def update_password():
    """Update current logged user password
    """
    user = current_user
    form = PasswordForm(request.form)

    perm = Permission(UserNeed(user.id), RoleNeed('admin'))
    perm.test()

    if form.validate_on_submit():
        to_check = user.password_hash
        if not custom_app_context.verify(form.current.data, to_check):
            flash("Bad password provided", "alert-danger")
            return render_template("user/pwd_update.html", form=form)

        new_hash = custom_app_context.hash(form.password.data)
        user.password_hash = new_hash
        db.session.commit()

        flash("Password updated", "alert-info")
        return redirect(url_for('dashboard.index'))

    return render_template("user/pwd_update.html", form=form)
コード例 #12
0
def test_record_access(db):
    """Test access control for search."""
    mock_provides([UserNeed('*****@*****.**'), RoleNeed('groupX')])

    def check_record(json, allowed=True):
        # Create uuid
        id = uuid.uuid4()

        # Create record
        rec = type('obj', (object, ), {'id': id})
        Record.create(json, id_=id)

        # Check permission factory
        factory = cern_read_factory(rec)
        assert factory.can() if allowed else not factory.can()

    # Check test records
    check_record({'foo': 'bar'})
    check_record({'_access': {'read': ['*****@*****.**', 'groupA', 'groupB']}})
    check_record({'_access': {'read': ['*****@*****.**', 'groupC']}}, False)
    check_record({'_access': {'read': ['groupX']}})
    check_record({'_access': {'read': ['*****@*****.**', 'groupA', 'groupB']}})
    check_record({'_access': {'read': []}})
コード例 #13
0
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, 'roles'):
        for role in current_user.roles:
            identity.provides.add(RoleNeed(role.name))

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

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

    if hasattr(current_user, 'collects'):
        for collect in current_user.collects:
            identity.provides.add(GetCollect(collect.id))
            identity.provides.add(PostCollect(collect.id))
コード例 #14
0
def edit_post(id):
    post = Post.query.get_or_404(id)
    permission = Permission(UserNeed(post.user.id))

    # We want admins to be able to edit any post
    if permission.can() or admin_permission.can():
        form = PostForm()

        if form.validate_on_submit():
            post.title = form.title.data
            post.text = form.text.data
            post.publish_date = datetime.datetime.now()

            db.session.add(post)
            db.session.commit()

            return redirect(url_for('.post', post_id=post.id))

        form.text.data = post.text

        return render_template('edit.html', form=form, post=post)

    abort(403)
コード例 #15
0
ファイル: views.py プロジェクト: yenib/destinations-catalog
def editItem(item_id):
    item = Item.query.get_or_404(item_id)

    # Check if the logged user is the one that created the destination about to
    # edit.
    permission = Permission(UserNeed(item.user_id))
    if permission.can():
        # Create the form object using data from different sources.
        form = ItemForm(CombinedMultiDict((request.files, request.form)),
                        obj=item)
        form.category.choices = getChoicesOfCategorySelect()
        form.image.default = item.image
        if request.method == 'GET':
            form.category.default = item.category_id
            # Makes effective the default selection set above.
            form.category.process([])
        elif form.validate():
            # Manages images updates.
            if isinstance(form.image.data, FileStorage) and form.image.data:
                filename = secure_filename(form.image.data.filename)
                removeFile(item.image)
                saveFile(form.image.data, filename)
                item.image = filename

            item.name = form.name.data
            item.category_id = form.category.data
            item.coutry = form.country.data
            item.description = form.description.data
            item.location = form.location.data
            item.image_alt = form.image_alt.data
            db.session.add(item)
            db.session.commit()
            flash('The destination was successfully updated.', "success")
            return redirect(url_for('showItem', item_id=item.id))
        return render_template('editItem.html', form=form, item=item)
    else:
        abort(403)
コード例 #16
0
ファイル: blog.py プロジェクト: Jerry-zhuang/Jerry-s-Blog
def edit_post(id):
    """编辑博客"""

    post = Post.query.get_or_404(id)
    searchform = SearchForm()

    if not current_user:
        return redirect(url_for('main.login'))

    if current_user != post.users:
        return redirect(url_for('blog.post',post_id=id))

    permission = Permission(UserNeed(post.users.id))

    if permission.can() or admin_permission.can():
        postform = PostForm()

        if postform.validate_on_submit():
            data1 = str(postform.text).replace("required>","&")
            data2 = str(data1).replace("</textarea>"," ")
            mes = data2.find("&")
            data = data2[mes+1:]

            post.title = postform.title.data
            post.text = postform.text.data
            post.publish_date = datetime.now()

            db.session.add(post)
            db.session.commit()
            return redirect(url_for('blog.post',post_id=post.id))
    else:
        return redirect(url_for('blog.home',page=1))


    postform.title.data  = post.title
    postform.text.data = post.text
    return render_template('edit_post.html',postform=postform,post=post,searchform=searchform)
コード例 #17
0
ファイル: blog.py プロジェクト: leozhuang196/flask-blog
def edit_post(id):
    """View function for edit_post."""

    post = Post.query.get_or_404(id)
    form = PostForm()

    # Ensure the user logged in.
    if not current_user:
        return redirect(url_for('main.login'))

    # Only the post onwer can be edit this post.
    if current_user != post.users:
        return redirect(url_for('blog.post', post_id=id))

    # 当 user 是 poster 或者 admin 时, 才能够编辑文章
    # Admin can be edit the post.
    permission = Permission(UserNeed(post.users.id))
    if permission.can() or admin_permission.can():

        # if current_user != post.users:
        #    abort(403)

        if form.validate_on_submit():
            post.title = form.title.data
            post.text = form.text.data
            post.publish_date = datetime.now()

            # Update the post
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('blog.post', post_id=post.id))
    else:
        return redirect(url_for('blog.post', post_id=id))

    form.title.data = post.title
    form.text.data = post.text
    return render_template('edit_post.html', form=form, post=post)
コード例 #18
0
def populate_identity_roles(identity, user=None):
    identity.user = user

    if user is None or user.is_anonymous:
        if current_app.config['POLICY_ANONYMOUS_VIEW_INDEX']:
            identity.provides.add(roles.index_view)
        if current_app.config['POLICY_ANONYMOUS_VIEW_POST']:
            identity.provides.add(roles.post_view)
        if current_app.config['POLICY_ANONYMOUS_VIEW_STATS']:
            identity.provides.add(roles.stats_view)

    else:
        identity.provides.add(UserNeed(user.identifier))
        identity.provides.add(roles.index_view)
        identity.provides.add(roles.post_comment)
        identity.provides.add(roles.post_view)
        identity.provides.add(roles.post_download)
        identity.provides.add(roles.post_edit)
        identity.provides.add(roles.stats_view)

        # TODO: Populate group permissions, and port existing group admin
        # code to roles.

    return identity
コード例 #19
0
        def test_permissions():
            """Iterates over all users checking its permissions."""
            for i in range(users_number):
                identity = FakeIdentity(UserNeed(users[i].id))

                # Allowed permission
                permission_allowed_both = dynamic_permission(
                    ActionNeed('action{0}'.format((i % actions_users_number) +
                                                  actions_roles_number)),
                    ActionNeed('action{0}'.format(i % actions_roles_number)))
                assert permission_allowed_both.allows(identity)

                # Not allowed action user
                permission_not_allowed_user = dynamic_permission(
                    ActionNeed(
                        'action{0}'.format((i + 1) % actions_users_number +
                                           actions_roles_number)))
                assert not permission_not_allowed_user.allows(identity)

                # Not allowed action role
                permission_not_allowed_role = dynamic_permission(
                    ActionNeed('action{0}'.format(
                        (i + 1) % actions_roles_number)))
                assert not permission_not_allowed_role.allows(identity)
コード例 #20
0
ファイル: view.py プロジェクト: Arianxx/LoniceraBlog
def post_edit(postid):
    """Edit a exits article."""
    post = Post.query.get_or_404(postid)
    if Permission(UserNeed(post.user.id)).can() or current_user.can("admin"):
        form = PostForm()
        if form.validate_on_submit():
            post.title = form.title.data
            post.body = form.body.data
            db.session.add(post)
            db.session.commit()

            tags = list(set(form.tags.data.split()))
            post.tags = []
            for tagname in tags:
                tag = Tag.query.filter_by(name=tagname).first()
                if tag:
                    post.tags.append(tag)
                else:
                    tag = Tag(name=tagname)
                    post.tags.append(tag)

            db.session.add(post)
            db.session.commit()

            flash("You have successfully updated a article.")
            return redirect(url_for("main.post", postid=post.id))

        form.title.data = post.title
        form.body.data = post.body
        form.tags.data = " ".join([tag.name for tag in post.tags])
        return render_template("/main/editpost.html",
                               form=form,
                               postid=post.id)

    else:
        abort(403)
コード例 #21
0
def _on_identity_loaded(sender, identity):
    """ flask_principal used to load user"""
    if hasattr(current_user, 'id'):
        identity.provides.add(UserNeed(current_user.id))

    if hasattr(current_user, 'roles'):
        for role in current_user.roles:
            identity.provides.add(RoleNeed(role.name))

    # provide vip need
    if hasattr(current_user, 'vips'):
        from youjiao.user.models import User, VIP
        from youjiao.extensions import db
        e = VIP.query.filter(VIP.user_id == current_user.id,
                             VIP.end > date.today()).exists()
        if db.session.query(e).scalar():
            identity.provides.add(RoleNeed('vip'))
    if hasattr(current_user, 'roles'):
        if ('admin'
                in current_user.roles_name) or ('editor'
                                                in current_user.roles_name):
            identity.provides.add(RoleNeed('vip'))

    identity.user = current_user
コード例 #22
0
 def on_identity_loaded(sender, identity):
     identity.user = current_user
     if hasattr(current_user, "id"):
         identity.provides.add(UserNeed(current_user.id))
     identity.provides.add(RoleNeed(role_name))
コード例 #23
0
 def need(self):
     """Return UserNeed instance."""
     return UserNeed(self.user_id)
コード例 #24
0
def load_needs(sender, identity: Identity):
    identity.user = current_user

    if getattr(current_user, 'id', None):
        identity.provides.add(UserNeed(current_user.id))
        identity.provides.add(RoleNeed(USER_ROLE))
コード例 #25
0
def test_invenio_access_permission_cache_users_updates(app):
    """Testing ActionUsers cache with inserts/updates/deletes."""
    cache = SimpleCache()
    InvenioAccess(app, cache=cache)
    with app.test_request_context():
        # Creation of some data to test.
        user_1 = User(email='*****@*****.**')
        user_2 = User(email='*****@*****.**')
        user_3 = User(email='*****@*****.**')
        user_4 = User(email='*****@*****.**')
        user_5 = User(email='*****@*****.**')
        user_6 = User(email='*****@*****.**')

        db.session.add(user_1)
        db.session.add(user_2)
        db.session.add(user_3)
        db.session.add(user_4)
        db.session.add(user_5)
        db.session.add(user_6)

        db.session.add(ActionUsers(action='open', user=user_1))
        db.session.add(ActionUsers(action='write', user=user_4))

        db.session.flush()

        # Creation identities to test.
        identity_user_1 = FakeIdentity(UserNeed(user_1.id))
        identity_user_2 = FakeIdentity(UserNeed(user_2.id))
        identity_user_3 = FakeIdentity(UserNeed(user_3.id))
        identity_user_4 = FakeIdentity(UserNeed(user_4.id))
        identity_user_5 = FakeIdentity(UserNeed(user_5.id))
        identity_user_6 = FakeIdentity(UserNeed(user_6.id))

        # Test if user 1 can open. In this case, the cache should store only
        # this object.
        permission_open = DynamicPermission(ActionNeed('open'))
        assert permission_open.allows(identity_user_1)
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1)]),
            set([])
        )

        # Test if user 4 can write. In this case, the cache should have this
        # new object and the previous one (Open is allowed to user_1)
        permission_write = DynamicPermission(ActionNeed('write'))
        assert permission_write.allows(identity_user_4)
        assert current_access.get_action_cache('write') == (
            set([Need(method='id', value=4)]),
            set([])
        )
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1)]),
            set([])
        )

        # If we add a new user to the action open, the open action in cache
        # should be removed but it should still containing the write entry.
        db.session.add(ActionUsers(action='open', user=user_2))
        db.session.flush()
        assert current_access.get_action_cache('open') is None
        permission_open = DynamicPermission(ActionNeed('open'))
        assert permission_open.allows(identity_user_2)
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2)]),
            set([])
        )
        assert current_access.get_action_cache('write') == (
            set([Need(method='id', value=4)]),
            set([])
        )

        # Test if the new user is added to the action 'open'
        permission_write = DynamicPermission(ActionNeed('write'))
        assert permission_write.allows(identity_user_4)
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2)]),
            set([])
        )
        assert current_access.get_action_cache('write') == (
            set([Need(method='id', value=4)]),
            set([])
        )

        # If we update an action swapping a user, the cache containing the
        # action, should be removed.
        user_4_action_write = ActionUsers.query.filter(
            ActionUsers.action == 'write' and
            ActionUsers.user == user_4).first()
        user_4_action_write.user = user_3
        db.session.flush()
        assert current_access.get_action_cache('write') is None
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2)]),
            set([])
        )

        # Test if the user_3 can now write.
        permission_write = DynamicPermission(ActionNeed('write'))
        assert not permission_write.allows(identity_user_4)
        permission_write = DynamicPermission(ActionNeed('write'))
        assert permission_write.allows(identity_user_3)
        assert current_access.get_action_cache('write') == (
            set([Need(method='id', value=3)]),
            set([])
        )
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2)]),
            set([])
        )

        # If we remove a user from an action, the cache should clear the
        # action item.
        user_3_action_write = ActionUsers.query.filter(
            ActionUsers.action == 'write' and
            ActionUsers.user == user_3).first()
        db.session.delete(user_3_action_write)
        db.session.flush()
        assert current_access.get_action_cache('write') is None
        # If no one is allowed to perform an action then everybody is allowed.
        permission_write = DynamicPermission(ActionNeed('write'))
        assert permission_write.allows(identity_user_3)
        assert current_access.get_action_cache('write') == (
            set([]),
            set([])
        )
        db.session.add(ActionUsers(action='write', user=user_5))
        db.session.flush()
        permission_write = DynamicPermission(ActionNeed('write'))
        assert permission_write.allows(identity_user_5)
        permission_write = DynamicPermission(ActionNeed('write'))
        assert not permission_write.allows(identity_user_3)
        assert current_access.get_action_cache('write') == (
            set([Need(method='id', value=5)]),
            set([])
        )
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2)]),
            set([])
        )

        # If you update the name of an existing action, the previous action
        # and the new action should be remove from cache.
        permission_write = DynamicPermission(ActionNeed('write'))
        assert permission_write.allows(identity_user_5)
        assert current_access.get_action_cache('write') == (
            set([Need(method='id', value=5)]),
            set([])
        )
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2)]),
            set([])
        )
        user_5_action_write = ActionUsers.query.filter(
            ActionUsers.action == 'write' and
            ActionUsers.user == user_5).first()
        user_5_action_write.action = 'open'
        db.session.flush()
        assert current_access.get_action_cache('write') is None
        assert current_access.get_action_cache('open') is None
        permission_open = DynamicPermission(ActionNeed('open'))
        assert permission_open.allows(identity_user_1)
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2),
                 Need(method='id', value=5)]),
            set([])
        )
        db.session.add(ActionUsers(action='write', user=user_4))
        permission_write = DynamicPermission(ActionNeed('write'))
        assert not permission_write.allows(identity_user_5)
        assert current_access.get_action_cache('write') == (
            set([Need(method='id', value=4)]),
            set([])
        )

        db.session.add(ActionUsers(action='open', argument='1', user=user_6))
        db.session.flush()
        permission_open_1 = DynamicPermission(
            ParameterizedActionNeed('open', '1'))
        assert not permission_open.allows(identity_user_6)
        assert permission_open_1.allows(identity_user_6)
        assert current_access.get_action_cache('open::1') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2),
                 Need(method='id', value=5),
                 Need(method='id', value=6)]),
            set([])
        )
        user_6_action_open_1 = ActionUsers.query.filter_by(
            action='open', argument='1', user_id=user_6.id).first()
        user_6_action_open_1.argument = '2'
        db.session.flush()
        assert current_access.get_action_cache('open::1') is None
        assert current_access.get_action_cache('open::2') is None
        permission_open_2 = DynamicPermission(
            ParameterizedActionNeed('open', '2'))
        assert permission_open_2.allows(identity_user_6)
        assert current_access.get_action_cache('open::2') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2),
                 Need(method='id', value=5),
                 Need(method='id', value=6)]),
            set([])
        )
        # open action cache should remain as before
        assert current_access.get_action_cache('open') == (
            set([Need(method='id', value=1),
                 Need(method='id', value=2),
                 Need(method='id', value=5)]),
            set([])
        )
コード例 #26
0
 def custom_views_permissions_factory(action):
     if action == "circulation-loan-force-checkout":
         # fake permission for a specific user
         return Permission(UserNeed(librarian2.id))
     else:
         return default_factory(action)
コード例 #27
0
 def __call__(self, item):
     if self.method == 'id':
         return UserNeed(self.resource.item_get_id(item))
     return ItemNeed(self.method,
                     get_value(item, self.resource.meta.id_attribute, None),
                     self.type)
コード例 #28
0
def identity_simple():
    """Simple identity fixture."""
    i = Identity(1)
    i.provides.add(UserNeed(1))
    i.provides.add(Need(method="system_role", value="any_user"))
    return i
コード例 #29
0
 def needs(self, record=None, **kwargs):
     """Enabling Needs."""
     return [UserNeed(owner) for owner in record.get('owners', [])]
コード例 #30
0
from flask_principal import Principal, Permission, RoleNeed, identity_loaded,UserNeed
from config import config
from flask_login import current_user

import flask_whooshalchemyplus

from flask_admin import Admin

db = SQLAlchemy()
principals = Principal()

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'main.login'
admin_permission = Permission(RoleNeed('admin'))
user_permission = Permission(UserNeed('id'))


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    Principal(app)
    db.init_app(app)
    db.app = app
    with app.app_context():
        db.create_all()
    login_manager.init_app(app)
    from .models import User, Post, UserRole, Comment, Tag, posts_tags, Role
    from .modelview import MyAdminIndexView, MyViewAll, MyView, MyViewpost
    flask_whooshalchemyplus.init_app(app)