Package: balrog
Balrog is a Python library that helps you to build an authorization system in your projects:You shall not pass!Balrog is good for systems with statically defined roles that enable certain workflows.
Every identity can have only one role on the certain context. This approach allows covering
your system with functional tests according to the roles and flows these roles perform.
Formal requirements can be applied to the workflows in the system which will define roles.These roles are statically defined in the code and this way properly versioned and covered
with testing. It is possible to do a composition of certain permission groups and share them
between roles, but semantically there’s no way for one identity to have 2 contradicting
roles when one role forbids actions and the other allows them. Instead a proper role
can be extracted with the permissions it allows.InstallationpipinstallbalrogUsagePermission is needed to access a resource or to perform an action. Permissions are grouped in the roles
and roles are grouped in the policies.The entry point where a permission is being checked is the Policy. Define an instance of the Policy
and specify the list of roles it works with.Project can contain multiple policies that serve different purposes.Permission declaration:importbalrogfromflaskimportrequestdefget_identity(*args,**kwargs):"""Get current user."""# Flask request wrapper implements the ``user`` propertyreturnrequest.userdefget_role(identity,*args,**kwargs):"""Get current identity role."""# User.role is a property of the ORM User modelreturnidentity.roleread=balrog.Permissions(name="article.read")post=balrog.Permissions(name="article.post")comment=balrog.Permissions(name="article.comment")anonymous=balrog.Role(name="anonymous",permissions=[read],)"""Anonymous visitors can read articles."""user=balrog.Role(name="user",permissions=[read,comment],)"""User accounts can read and comment articles."""author=balrog.Role(name="author",permissions=[read,post,comment],)"""Author accounts can read, create and comment articles."""policy=balrog.Policy(roles=[anonymous,user,author],get_identity=get_identity,get_role=get_role,permissions=[read,post,comment])Permission checking:# ...policy=balrog.Policy(roles=[anonymous,user,author],get_identity=get_identity,get_role=get_role)policy.check("article.comment")Filtering collections:articles=session.query(Article)my_articles=policy.filter("article.view",objects=articles)Every role is a collection of permissions. Besides being included in the role permissions can
implement even more detailed checking and filtering logic.PermissionPermissions have unique names (within the role) which reflect the resource and the action you
want to take with this resource.importbalrogeat=balrog.Permission(name="cucumber.eat")happy=balrog.Permission(name="be-happy")Name is just a string identifier that you are using in order to ask a policy for a permission.
The name formatting convention can be decided per project.Permissions have 2 methods:checkandfilter. By default thecheckmethod implementsTrueand thefiltermethod is simply bypassing the objects. These methods are an additional opportunities
to control the access to certain context, instances of your resources, check whitelists, filter out objects
from collections that can not be seen by currently authenticated identity, etc.RoleRoles have unique names within the policy. Role name is determined by the authenticated identity
and used in the policy permission check implicitly.Roles are collections of permissions that define the role and enable certain workflows in your
system.When a system is large and has a lot of specific permissions declared sometimes it is easier to
subclass the Role class instead of granting all permissions to the role:importbalrogclassAdmin(balrog.Role):defcheck(self,identity,permission,*args,**kwargs):returnTruePolicyPolicy is used as an entry point of permission checking in your project. It incapsulates the roles
that define your workflows. There could be multiple policy instances in the project.Besides roles policy requires some configuration and backend implementation:get_identityA callback that returns currenlty authenticated identity. Projects have to implement this backend
and restore the identity instance (e.g. User object) for example from the Flask Request object.fromflaskimportrequestdefget_identity(*args,**kwargs):"""Get current user."""# Flask request wrapper implements the ``user`` propertyreturnrequest.userget_roleA callback that returns which role current identity has on the context. In the simple case the role is associated
to the user in the database.defget_role(identity,*args,**kwargs):"""Get current identity role."""# User.role is a property of the ORM User modelreturnidentity.rolecheckThe permission check. All arguments that you pass to this function are passed along in Role.check and finally
to Permission.check.ifnotpolicy.check("article.read",article=a):flask.abort("You can't access the article `{0}`".format(a.id))filterThe function that is filtering out items of the given objects if the identity has no permission to access them.articles=session.query(Article).filter_by(is_published=True)my_articles=policy.filter("article.read",objects=articles)Implementing your own filtering:importbalrogclassViewArticle(balrog.Permission);deffilter(self,identity,objects,*args,**kwargs):"""Filter out articles of the other users.

        :param identity: User object.
        :param objects: SQLAlchemy query.

        :returns: SQLAlchemy query with applied filtering.
        """returnobjects.filter_by(user_id=identity.id)Filter function can raise an exception in the case when there’s no such permission
in the role of the identity. In this case the library doesn’t know for sure what type to
return that represents an empty collection of objects. Some projects would expect
an empty list, some - falsy ORM query, etc. Instead the exception should be handled:try:my_articles=policy.filter("article.read",objects=articles)exceptbalrog.PermissionNotFound:my_articles=[]contextEverything that you pass extra to the check or filter function is passed along to the regarding
Role and Permission methods.
You can pass certain instance of an object you control your access using whitelists.policy.check("message.send",ip=ip_addr)Policy.check method can compare if ip address is in a whitelist.ContactIf you have questions, bug reports, suggestions, etc. please create an issue on
theGitHub project page.LicenseThis software is licensed under theMIT licenseSeeLicenseChangelog
=========1.1.0Policy will keep track of all the permissions and raise PermissionNotFound when called with unknown permission (hvdklauw)1.0.1Pass the context to the get_identity (olegpidsadnyi)1.0.0Initial public release