Package: authoriz
AuthorizThe python module to allow rules-based authorization. Rules for allowing and disallowing actions can
come from different sources.FeaturesEasy rules parsers customization. Rules could be parsed from any source.Specify required actions to your DRF ViewSet actions.Action namespace definition with action params listing.Fast authorization after setup is done.Easy parameters getters definition.Flexible configuration.InstallationTo install project with pip use:pip install authorizTo install it to your Django project add it to your installed apps:INSTALLED_APPS=[...'authoriz',...]UsageThe main workflow of the usage are the following:Specify action namespace enum classes.You should predefine namespaces with actions to parse and use it.Specify parsers for the rules.There are default parsers,
but it's possible (and recommended in many cases) to define
your own with required source.Specify permissions to retrieve parameters.Views could have specific parameters for the action.
So you should specify getters of those in permission class.Install authorization to your view.After all the above steps are complete,
you can finally install authorization to specific view. It includes defining of
actions required by the view, adding mixin to the view and adding permission classes
to fetch required parameters.1. Specify action namespace enum classesThe enum class the following structure as the example below:fromdjango.dbimportmodelsfromauthoriz.namespaces.baseimportActionsNamespaceclassEntityPermissions(ActionsNamespace):name='entity'classActions(models.TextChoices):ENTITY_CREATE='entity:EntityCreate','Create entity'ENTITY_LIST='entity:EntityList','List entities'ENTITY_RETRIEVE='entity:EntityRetrieve','Retrieve entity'ENTITY_UPDATE='entity:EntityUpdate','Update entity'ENTITY_DESTROY='entity:EntityDestroy','Delete entity'params={Actions.ENTITY_CREATE.value:[],Actions.ENTITY_LIST.value:[],Actions.ENTITY_RETRIEVE.value:['entity_id'],Actions.ENTITY_UPDATE.value:['entity_id'],Actions.ENTITY_DESTROY.value:['entity_id'],}Parameters:name- name of the namespace.Actions- enum class with actions contained by the given namespace.params- specification of the params allowed by specific actions.
If the action is not presented in dict, the empty list
is used as a default.2. Specify parsers for the rulesThe parser class has the following structure as the example below:frompath.toimportget_rules_from_some_sourcefromauthoriz.parsing.baseimportPermissionsRule,PermissionsParserclassRulesFromSomeSourceParser(PermissionsParser):defget_rules(self)->List[PermissionsRule]:rules=get_rules_from_some_source()returnrulesSo the main method isget_rules(). It is used to specify the routine to get / parse rules list from
any source (database, file, API call, etc.).After you defined your required parser classes you should specify them insettings.pyof your Django project.AUTHORIZ_RULES_PARSERS=[{'parser':'path.to.RulesFromSomeSourceParser','args':[],'kwargs':{},}]The parsers should be listed in the correct order. The rules parsed with last parsers could
override the rules of the first ones.Rule structure@dataclassclassPermissionsRule:name:streffect:stractions:List[ParsedAction]target:strid:int# generatedParameters:name- name of the rule.'Some rule #1'effect- what exactly does the rule mean.'allow''deny'actions- list of actions on which the rule has effect.target- who is the rule apply on.'132342'- user ID'role:admin'- user roleid- ID of the rule. Used to sort rules before composing final allow/deny tree.Generated automatically.123Action structure@dataclassclassParsedAction:namespace:straction_name:strparams:dict# {} by defaultParameters:namespace- namespace of the action.'project''entity''user'action_name- exact name of the action in the given namespace.'CreateProject''UpdateUser''DeleteEntity'params- some additional data for the given action. Allowed params are specified by namespace enum class.{project_id: 12, entity_id: 32}3. Specify permissions to retrieve parametersThe permission class has the following structure:fromauthoriz.permissions.baseimportBaseServicePermissionclassEntityKwargsHasPermission(BaseServicePermission):defget_entity_id(self,request,view):returnrequest.parser_context['kwargs']['entity_id']Getters are all the methods that starts withget_prefix.
Everything that goes afterget_is considered as parameter name.
So if we make a request to the route/entities/<entity_id>such as:GET http://<host>:<port>/entities/1232it will pass paramentity_idwith value1232to the permission check and find
out whether your rules set allows the action with the following params or not.4. Install authorization to your viewAfter all the previous steps are done we can apply in of the view:fromrest_frameworkimportpermissions,viewsets,mixinsfromauthoriz.mixinsimportAPIViewPermissionsMixinfrompath.toimportEntityKwargsHasPermissionfrompath.toimportEntityPermissionsclassEntityViewSet(APIViewPermissionsMixin,mixins.ListModelMixin,mixins.RetrieveModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,viewsets.GenericViewSet):permission_classes=[permissions.IsAuthenticated,EntityKwargsHasPermission,]actions_permissions={'create':[EntityPermissions.Actions.ENTITY_CREATE],'list':[EntityPermissions.Actions.ENTITY_LIST],'retrieve':[EntityPermissions.Actions.ENTITY_RETRIEVE,],'update':[EntityPermissions.Actions.ENTITY_UPDATE,],'destroy':[EntityPermissions.Actions.ENTITY_DESTROY,],}To apply follow the following steps:AddAPIViewPermissionsMixinas your first base class.AddEntityKwargsHasPermissiontopermission_classes.Specify required actions to DRF ViewSet actions inactions_permissions.LicenseThe project is licensed under the BSD license.