Skip to main content

Masonite Permission

GitHub Workflow Status PyPI issues Python Version GitHub release (latest by date including pre-releases) License star downloads Code style: black

Introduction

Associate users with roles and permissions to control access to your application.

Getting Started

Install the package using pip:

pip install masonite-permission

Add PermissionProvider to your project in config/providers.py:

# config/providers.py
# ...
from masonite_permission import PermissionProvider

# ...
PROVIDERS = [
    # ...
    # Third Party Providers
    PermissionProvider,
    # ...
]

Publish the package configuration files.

python craft package:publish masonite-permission

This will add migrations and other masonite-permission related configuration to your project. Run your migrations to create the related database tables.

python craft migrate

Now, extend User model class with HasRoles mixin.

from masoniteorm.models import Model
from masoniteorm.scopes import SoftDeletesMixin
from masonite.authentication import Authenticates
from src.masonite_permission.mixins import (HasPermissions, HasRoles)

class User(Model, SoftDeletesMixin, Authenticates, HasRoles, HasPermissions):
    """User Model."""

    __fillable__ = ["name", "email", "password"]
    __hidden__ = ["password"]
    __auth__ = "email"

Usage

Working with Role

Creating Roles

""" Creating Role
    Arguments:
        name: The name of the role
        slug: The slug of the role, must be unique
"""
from masonite_permission.models import Role

role = Role.create({
    "name": "Admin",
    "slug": "admin"
})

Add permissions into roles

""" Add permissions into roles
    Available Methods:
        1. sync_permissions: Syncs the permissions with the role
            arguments: Takes a list/tuple of permission slugs
        2. attach_permission: Adds a permission to a role
            arguments: Takes permission model object or permission slug
        3. detach_permission: Removes a permission from the role
            arguments: Takes permission model object or permission slug
"""
""" Syncing permissions with role, adds provided permissions and removes all other permissions
    Arguments:
        permissions: Takes a list/tuple of permission slugs
"""
role.sync_permissions(["create-post", "read-post", "update-post", "delete-post"])
# or
role.sync_permissions("create-post", "read-post", "update-post", "delete-post")
# or
role.sync_permissions([]) # clears all permissions from role
""" Attach permission, this will add new permission into role if already not added
    Arguments:
        permission: Takes permission model object or permission slug
"""
role.attach_permission("create-post")
# or
role.attach_permission(Permission.first())
""" Detach permission, this will remove permission from role if already added
    Arguments:
        permission: Takes permission model object or permission slug
"""

role.detach_permission("create-post")
# or
role.detach_permission(Permission.first())

Working with Permission

Creating Permission

""" Creating Permission
    Arguments:
        name: The name of the permission
        slug: The slug of the permission, must be unique
"""
from masonite_permission.models import Permission
permission = Permission.create({
  "name": "Create Post",
  "slug": "create-post" # must be unique
})

Add permissions into roles

""" Add permissions into roles
    Available Methods:
        1. sync_roles: Syncs the roles with the permission
            arguments: Takes a list/tuple of role slugs
        2. attach_role: Adds a permission to a role
            arguments: Takes role model object or role slug
        3. detach_role: Removes a permission from a role
            arguments: Takes role model object or role slug
"""
""" Syncing permissions with role, adds provided roles and removes all other roles
    Arguments:
        roles: Takes a list of role ids or role collection
"""
permission.sync_roles(['admin', 'editor'])
# or
permission.sync_roles('admin', 'editor')
# or
permission.sync_roles([]) # clears all role from permission
""" Attach role, this will add new permission into role if already not added
    Arguments:
        role: Takes role model object or role slug
"""
role = Role.first()

permission.attach_role(role)
# or
permission.attach_role('admin')
""" Detach role, this will remove permission from role if already added
    Arguments:
        role: Takes role model object or role id
"""
role = Role.first()

permission.detach_role(role)
# or
permission.detach_role('admin')

Working with User

user = User.first()

Adding/Removing single role

# Add/Remove single role
role = Role.first()

user.assign_role(role) # or you can pass role id
user.revoke_role(role) # or you can pass role id

Adding/Removing multiple roles

# add/remove multiple roles
roles = Role.all()

user.sync_roles(roles) # or you can also pass list of ids...
user.sync_roles([]) # clears all roles from user

Checking if user has roles

# check if user has role
user.has_role_of("admin") # returns boolean

# check if user has any of the roles
user.has_any_role(["admin", "editor"]) # returns boolean
# or
user.has_any_role("admin", "editor")

# check if user has all of the roles
user.has_all_roles(["admin", "editor"]) # returns boolean
# or
user.has_all_roles("admin", "editor")

Adding/Removing single direct permission

# Add/Remove single permission
user.give_permission_to("read-post", "edit-post") # this can be a tuple or a list
# or
user.give_permission_to(["read-post", "edit-post"])

user.revoke_permission_to("read-post", "edit-post") # this can be a tuple or a list
# or
user.revoke_permission_to(["read-post", "edit-post"])

Adding/Removing multiple direct permissions

# add/remove multiple direct permissions
permissions = Permission.all().pluck("slug")

user.sync_permissions(permissions) # tuples or list of permission slug
user.sync_permissions([]) # clears all permissions from user

Checking if user has permissions

# check if user has permission (for single permission)
user.has_permission_to("read-post") # returns boolean

# check if user has any of the permissions
user.has_any_permission(["read-post", "edit-post"]) # returns boolean
# or
user.has_any_permission("read-post", "edit-post")

# check if user has all of the permissions
user.has_all_permissions(["read-post", "edit-post"]) # returns boolean
# or
user.has_all_permissions("read-post", "edit-post") # returns boolean

Using in Template

In case of Roles Checking if user has role.

{% if user.is_("admin") %}
    <p>You are an admin</p>
{% endif %}

Checking if user has any of the roles

{% if user.is_("admin|editor|truck-driver") %}
    <p>You can be either admin, editor, truck driver or all of those</p>
{% endif %}

Checking if user has all of the roles

{% if user.is_("admin,editor,truck-driver") %}
    <p>You are an admin, editor and also truck-driver</p>
{% endif %}

In case of Permissions Checking if user can do {permission}.

{% if user.can_("edit-post") %}
    <p>You can edit post</p>
{% endif %}

Checking if user can do any one or more of the {permissions}

{% if user.can_("edit-post|delete-post") %}
    <p>You can either edit-post, delete-post or both.</p>
{% endif %}

Checking if user can do all of the {permissions}

{% if user.can_("edit-post,delete-post") %}
    <p>You can edit post and also delete post.</p>
{% endif %}

License

Masonite Permission is open-sourced software licensed under the MIT license.

Metadata

Release files for masonite-permission 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for masonite-permission 1.0.0
File Size Uploaded Provenance Actions
masonite-permission-1.0.0.tar.gz 12.7 kB Without provenance Details for masonite-permission-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for masonite-permission 1.0.0
File Interpreter ABI Platform Actions
masonite_permission-1.0.0-py3-none-any.whl Python 3 none any Details for masonite_permission-1.0.0-py3-none-any.whl

Total release size: 25.6 kB

Release files / masonite-permission-1.0.0.tar.gz

Download URL masonite-permission-1.0.0.tar.gz
Size 12.7 kB
Tags Source
SHA-256 checksum
How to use checksums
55f730dc06aca5202df1327a88d5d33a739654e1e27c14c7f9f843181a547a3c
BLAKE2b-256 checksum
How to use checksums
936fcd286fb6fc3a458404e5b9179f6c9eea1611e4a30589eb3410fd9d1163c7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.10.12

Release files / masonite_permission-1.0.0-py3-none-any.whl

Download URL masonite_permission-1.0.0-py3-none-any.whl
Size 12.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8a4921a9cd934093447a5b68102c6ca311fba89a415679a599ad81605a39c40b
BLAKE2b-256 checksum
How to use checksums
f69b2067a500ddfe080f9cfd5ba5024d1b97ad95f5febbdad733b917caddb294
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.10.12

Security for masonite-permission 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page