Authorization
Masonite also provides a simple way to authorize user actions against a given resource. This is achieved with two concepts: gates and policies. Gates are as the name suggests an authorization check that you will be able to invoke to verify user access. Policies are a way to groupe authorization logic around a model.

Gates

Gates are simple callable that will define if a user is authorized to perform a given action. A handy Gate facade is available to easily manipulate gates.

Registering Gates

Gates receive a user instance as their first argument and may receive additionals arguments such as a Model instance. You needs to define Gates in boot() method of your service provider.
In the following example we are adding gates to verify if a user can create and update posts. Users can create posts if they are administrators and can update posts they have created only.
1
from masonite.facades import Gate
2
3
class MyAppProvider(Provider):
4
5
def boot(self):
6
Gate.define("create-post", lambda user: user.is_admin)
7
Gate.define("update-post", lambda user, post: post.user_id == user.id)
Copied!
You can then check if a gate exists or has been registed by using has() which is returning a boolean:
1
Gate.has("create-post")
Copied!
If a unknown gate is used a GateDoesNotExist exception will be raised.

Authorizing Actions

Then anywhere (often in a controller) in your code you can use those gates to check if the current authenticated user is authorized to perform the given action defined by the gate.
Gates exposes different methods to perform verification: allows(), denies(), none(), any(), authorize() inspect().
allows(), denies(), none() and any() return a boolean indicating if user is authorized
1
if not Gate.allows("create-post"):
2
return response.redirect("/")
3
4
# ...
5
post = Post.find(request.input("id"))
6
if Gate.denies("update-post", post):
7
return response.redirect("/")
8
9
# ...
10
Gate.any(["delete-post", "update-post"], post)
11
12
# ...
13
Gate.none(["force-delete-post", "restore-post"], post)
Copied!
authorize() does not return a boolean but will raise an AuthorizationException exception instead that will be rendered as an HTTP response with a 403 status code.
1
Gate.authorize("update-post", post)
2
# if we reach this part user is authorized
3
# else an exception has been raised and be rendered as a 403 with content "Action not authorized".
Copied!
Finally for better control over the authorization check you can analyse the response with inspect():
1
response = Gate.inspect("update-post", post)
2
if response.allowed():
3
# do something
4
else:
5
# not authorized and we can access message
6
Session.flash("errors", response.message())
Copied!

Via the User Model

Authorizes class can be added to your User model to allow quick permission checks:
1
from masonite.authentication import Authenticates
2
from masonite.authorization import Authorizes
3
4
class User(Model, Authenticates, Authorizes):
5
#..
Copied!
A fluent authorization api will now be available on User instances:
1
user.can("delete-post", post)
2
user.cannot("access-admin")
3
user.can_any(["delete-post", "force-delete-post"], post)
Copied!
All of those methods receive the gate name as first argument and then some additional arguments if required.

With a given user

You can use the for_user() method on the Gate facade to make the verification against a given user instead of the authenticated user.
1
from masonite.facades import Gate
2
3
user = User.find(1)
4
Gate.for_user(user).allows("create-post")
Copied!

Gate Hooks

During the gate authorization process, before and after hooks can be triggered.
A before hook can be added like this:
1
# here admin users will always be authorized based on the boolean value of this response
2
Gate.before(lambda user, permission : user.role == "admin")
Copied!
The after hook works the same way:
1
Gate.after(lambda user, permission, result : user.role == "admin")
Copied!
If the after callback is returning a value it will take priority over the gate result check.

Policies

Policies are classes that organize authorization logic around a specific model.

Creating Policies

You can run the craft command:
1
$ python craft policy AccessAdmin
Copied!
You can also create a policy with a set of predefined gates by using the --model flag:
1
$ python craft policy Post --model
Copied!
A model policy comes with common actions that we can perform on a model:
1
from masonite.authorization import Policy
2
3
4
class PostPolicy(Policy):
5
def create(self, user):
6
return False
7
8
def view_any(self, user):
9
return False
10
11
def view(self, user, instance):
12
return False
13
14
def update(self, user, instance):
15
return False
16
17
def delete(self, user, instance):
18
return False
19
20
def force_delete(self, user, instance):
21
return False
22
23
def restore(self, user, instance):
24
return False
Copied!
You are free to add any other methods on your policies:
1
from masonite.authorization import Policy
2
3
4
class PostPolicy(Policy):
5
#..
6
7
def publish(self, user):
8
return user.email == "[email protected]"
Copied!

Registering Policies

Then in your service provider (as for defining gates) you should register the policies and bind them with a model:
1
from masonite.facades import Gate
2
from app.models.Post import Post
3
from app.models.User import User
4
5
from app.policies.PostPolicy import PostPolicy
6
from app.policies.UserPolicy import UserPolicy
7
8
class MyAppProvider(Provider):
9
10
#..
11
12
def register(self):
13
Gate.register_policies(
14
[(Post, PostPolicy), (User, UserPolicy)],
15
)
Copied!
An example policy for the Post model may look like this:
1
from masonite.authorization import Policy
2
3
class PostPolicy(Policy):
4
def create(self, user):
5
return user.email == "[email protected]"
6
7
def view(self, user, instance):
8
return True
9
10
def update(self, user, instance):
11
return user.id == instance.user_id
Copied!
If an unknown policy is used then a PolicyDoesNotExist exception will be raised.

Authorizing Actions

You can then use the Gate facade methods to authorize actions defined in your policies. With the previously defined PostPolicy we could make the following calls:
1
from masonite.facades import Gate
2
3
post = Post.find(1)
4
Gate.allows("update", post)
5
Gate.denies("view", post)
6
Gate.allows("force_delete", post)
Copied!
The create() or view_any() methods do not take a model instance, that is why the model class should be provided so that Gate mechanism can infer from which policy those methods are belonging to.
1
Gate.allows("create", Post)
2
Gate.allows("view_any", Post)
Copied!