laravel-rust 0.1.3

Laravel for Rust: a full-stack Rust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# Authorization

- [Introduction]#introduction
- [Writing policies]#writing-policies
    - [Policy responses]#denying-with-a-message
    - [Abilities without a record]#abilities-without-a-record
    - [Guests]#guests
    - [Allowing administrators everything]#before
    - [Asynchronous checks]#asynchronous-checks
- [Checking abilities]#checking-abilities
    - [Authorizing via Auth or Request]#checking-the-current-user
    - [Passing more arguments]#passing-more-arguments
    - [Authorizing a form]#authorizing-a-form
    - [Checking types other than users]#checking-types-other-than-users
- [Sharing abilities with the frontend]#sharing-abilities-with-the-frontend
    - [In views]#sharing-abilities-in-views
    - [With Inertia]#sharing-abilities-with-inertia
- [Testing]#testing

<a name="introduction"></a>
## Introduction

While [authentication](authentication.md) identifies who the current user is, authorization determines which actions they are permitted to perform. For example, in a blog application, any user may read a published post, while only its author may edit or delete it.

Laravel organizes authorization rules into policies. Each policy is a struct whose methods define abilities (such as `update` or `delete`) for a specific model or resource. Because you pass the policy method itself when checking an ability, misspelled names or mismatched model types are caught at compile time:

```rust
user.authorize(PostPolicy::update, &post).await?;
```

<a name="writing-policies"></a>
## Writing policies

Define a policy by annotating an `impl` block with `#[policy]`, typically on a unit struct named after the model. Each method accepts the user first, followed by the model (if applicable), and returns whether the action is allowed.

For example, suppose each `Post` model stores the author's `user_id`. This policy (placed in `src/policies/post.rs`, or directly alongside the model in `src/models/post.rs`) allows only the author to update or delete a post:

```rust
use laravel::auth::policy;

use crate::models::{Post, User};

pub struct PostPolicy;

#[policy]
impl PostPolicy {
    pub fn update(user: &User, post: &Post) -> bool {
        user.id == post.user_id
    }

    pub fn delete(user: &User, post: &Post) -> bool {
        user.id == post.user_id
    }
}
```

If you define a policy alongside its model in `src/models/post.rs`, re-export it from `src/models/mod.rs`:

```rust
// src/models/mod.rs
mod post;
mod user;

pub use post::{Post, PostFactory, PostPolicy};
pub use user::{User, UserFactory};
```

If you prefer keeping policies in their own `src/policies` directory, declare the `policies` module in `src/lib.rs` (as [adding your own modules](structure.md#adding-your-own-modules) describes) and re-export each policy from `src/policies/mod.rs`:

```rust
// src/lib.rs
pub mod policies;

// src/policies/mod.rs
mod post;

pub use post::PostPolicy;
```

Name each method after the action it allows. The usual names are `view_any`, `view`, `create`, `update`, `delete`, `restore`, and `force_delete`, but you may add any ability your application needs.

Because `#[policy]` treats every function in the block as an ability, place shared helper functions in a separate `impl` block without `#[policy]`:

```rust
#[policy]
impl PostPolicy {
    pub fn update(user: &User, post: &Post) -> bool {
        Self::owns(user, post)
    }

    pub fn delete(user: &User, post: &Post) -> bool {
        Self::owns(user, post)
    }
}

impl PostPolicy {
    fn owns(user: &User, post: &Post) -> bool {
        user.id == post.user_id
    }
}
```

<a name="denying-with-a-message"></a>
### Policy responses

A policy method returning `false` denies the action with a `403` status and the default message "This action is unauthorized." To return a custom denial message instead, return an `Access` response using `Access::allow()` and `Access::deny(..)`:

```rust
use laravel::auth::{Access, policy};

#[policy]
impl PostPolicy {
    pub fn update(user: &User, post: &Post) -> Access {
        if user.id == post.user_id {
            Access::allow()
        } else {
            Access::deny("You do not own this post.")
        }
    }
}
```

When you want to hide whether a record exists from unauthorized users (such as another team's private project), return `Access::deny_as_not_found()`, which responds with a `404` status instead of `403`:

```rust
#[policy]
impl ProjectPolicy {
    pub fn view(user: &User, project: &Project) -> Access {
        if user.team_id == project.team_id {
            Access::allow()
        } else {
            Access::deny_as_not_found()
        }
    }
}
```

If you need a different HTTP status code altogether, call `Access::deny_with_status(..)`, which responds with that status code and its standard reason phrase:

```rust
Access::deny_with_status(401)
```

<a name="abilities-without-a-record"></a>
### Abilities without a record

Some abilities don't involve a record yet, such as creating a post. Their methods take only the user. This one lets users create posts once they've verified their email:

```rust
#[policy]
impl PostPolicy {
    pub fn create(user: &User) -> bool {
        user.email_verified_at.is_some()
    }

    // ...
}
```

Abilities that don't involve a specific model, such as viewing an admin dashboard, go in their own policy. For example, suppose your users have an `is_admin` column:

```rust
use laravel::auth::policy;

use crate::models::User;

pub struct AdminPolicy;

#[policy]
impl AdminPolicy {
    pub fn view_dashboard(user: &User) -> bool {
        user.is_admin
    }
}
```

<a name="guests"></a>
### Guests

By default, a policy method accepting `&User` automatically denies guests without running. To evaluate guests explicitly, accept `Option<&User>`, which receives `None` for unauthenticated visitors. For example, suppose posts have a `published` column so anyone may view published posts while only authors may view drafts:

```rust
#[policy]
impl PostPolicy {
    pub fn view(user: Option<&User>, post: &Post) -> bool {
        post.published || user.is_some_and(|user| user.id == post.user_id)
    }

    // ...
}
```

<a name="before"></a>
### Allowing administrators everything

Sometimes you may have administrators who are permitted to perform every action a policy covers. Rather than check `is_admin` in every method, add a `before` method. It takes the user and returns an `Option<bool>`:

```rust
#[policy]
impl PostPolicy {
    fn before(user: &User) -> Option<bool> {
        user.is_admin.then_some(true)
    }

    // ...
}
```

The `before` method executes automatically before every other method in the policy:

- Returning `Some(true)` immediately grants permission without running the requested ability method.
- Returning `Some(false)` immediately denies permission.
- Returning `None` falls through to the requested ability method (such as `update` or `delete`) so it can decide for itself.

Because `before` receives `&User`, it is skipped for unauthenticated guests, allowing guest-accessible methods that accept `Option<&User>` to evaluate guests directly.

If your `before` check needs to know which ability is being evaluated (for example, allowing administrators everything except permanently deleting posts), accept the method's name as a second `&str` parameter:

```rust
#[policy]
impl PostPolicy {
    fn before(user: &User, ability: &str) -> Option<bool> {
        if ability == "force_delete" {
            return None;
        }

        user.is_admin.then_some(true)
    }

    // ...
}
```

<a name="asynchronous-checks"></a>
### Asynchronous checks

When an authorization check needs to query the database, make the policy method `async` and return `laravel::Result`. For example, this policy allows authors to delete a post only while it has no comments:

```rust
use laravel::auth::{Access, policy};

use crate::models::{Comment, Post, User};

#[policy]
impl PostPolicy {
    pub async fn delete(user: &User, post: &Post) -> laravel::Result<Access> {
        if user.id != post.user_id {
            return Ok(Access::deny("You do not own this post."));
        }

        if Comment::query().filter(Comment::post_id.eq(post.id)).exists().await? {
            return Ok(Access::deny("You can't delete a post with comments."));
        }

        Ok(Access::allow())
    }

    // ...
}
```

If an asynchronous policy method returns an `Err` (such as from a failed database query), Laravel fails the request with a `500` server error rather than treating it as an authorization denial.

<a name="checking-abilities"></a>
## Checking abilities

Once your policy is defined, check abilities in your handlers using `authorize` or `can` on your user type, passing the policy method followed by any additional arguments.

In a handler, extract the signed-in user with `Authenticated<User>` and resolve the target model via [route model binding](models.md#route-model-binding):

```rust
use laravel::inertia::{self, Page, props};
use laravel::prelude::*;

use crate::models::{Post, User};
use crate::policies::post::PostPolicy;

pub async fn edit(
    user: Authenticated<User>,
    post: Post,
) -> laravel::Result<Page> {
    user.authorize(PostPolicy::update, &post).await?;

    Ok(inertia::render("Posts/Edit", props! { "post" => &post }))
}

pub async fn show(
    user: Authenticated<User>,
    post: Post,
) -> laravel::Result<Page> {
    let can_delete = user.can(PostPolicy::delete, &post).await?;

    Ok(inertia::render("Posts/Show", props! { "post" => &post, "canDelete" => can_delete }))
}
```

`authorize` returns an error when denied so `?` aborts the handler with the [configured status and message](#denying-with-a-message), while `can` returns a `bool` so you can branch on it yourself.

Both methods come from the `Authorizable` trait imported by the [prelude](prelude.md) and automatically implemented for every `Authenticatable` model.

For abilities that do not take a model or any additional arguments beyond the user (such as `PostPolicy::create`), pass `()` as the second argument:

```rust
pub async fn create(user: Authenticated<User>) -> laravel::Result<Page> {
    user.authorize(PostPolicy::create, ()).await?;

    Ok(inertia::render("Posts/Create", props! {}))
}
```

<a name="checking-the-current-user"></a>
### Authorizing via Auth or Request

When a route is accessible to guests as well as signed-in users, call `can` or `authorize` on `Auth<User>` or `Request`:

```rust
use laravel::auth::Auth;
use laravel::inertia::Page;
use laravel::prelude::*;

use crate::models::{Post, User};
use crate::policies::post::PostPolicy;

pub async fn show(auth: Auth<User>, post: Post) -> laravel::Result<Page> {
    auth.authorize(PostPolicy::view, &post).await?;

    // ...
}

pub async fn create(request: Request) -> laravel::Result<Page> {
    request.authorize(PostPolicy::create, ()).await?;

    // ...
}
```

Guests receive a `403` from `authorize` and `false` from `can` unless the policy method accepts [`Option<&User>`](#guests).

<a name="passing-more-arguments"></a>
### Passing more arguments

A policy method may accept up to three additional arguments after the user when a decision depends on multiple models. For example, suppose an author may move a post into a `Category` only if that category is unlocked:

```rust
use laravel::auth::policy;

use crate::models::{Category, Post, User};

#[policy]
impl PostPolicy {
    pub fn move_to(user: &User, post: &Post, category: &Category) -> bool {
        user.id == post.user_id && !category.locked
    }

    // ...
}
```

Pass two or three arguments as a tuple, in the method's order:

```rust
user.authorize(PostPolicy::move_to, (&post, &category)).await?;
```

<a name="authorizing-a-form"></a>
### Authorizing a form

A [form type](validation.md#authorizing-the-request) can authorize the incoming request automatically using `#[validate(authorize(..))]`, so your handler does not need to call `authorize` itself. When the policy method expects a model (such as `Post` on a `/posts/{post}` route), pass `route("post")` to resolve that route parameter and pass the model to the policy:

```rust
use laravel::prelude::*;

use crate::models::Post;
use crate::policies::post::PostPolicy;

#[laravel::input]
#[validate(authorize(PostPolicy::update, route("post")))]
pub struct UpdatePost {
    #[validate(required, max_length(255))]
    title: String,
}

pub async fn update(post: Post, Valid(input): Valid<UpdatePost>) -> laravel::Result<Redirect> {
    // Only users who may update the post get here, with a valid title...

    Ok(Redirect::back())
}
```

`Valid<UpdatePost>` checks `PostPolicy::update` for the current user before it validates the input. A user who may not update the post gets the denial's response, not validation errors.

For an ability without a record, leave out the arguments, as in `#[validate(authorize(PostPolicy::create))]`. List several records in the method's order, as in `authorize(PostPolicy::move_to, route("post"), route("category"))`.

<a name="checking-types-other-than-users"></a>
### Checking types other than users

A policy may decide abilities for a type other than your user, such as a team whose plan limits how many projects it has. Implement `Authorizable` for the type with an empty `impl`, and write the policy with the type first:

```rust
use laravel::auth::{Authorizable, policy};

use crate::models::Team;

impl Authorizable for Team {}

pub struct ProjectPolicy;

#[policy]
impl ProjectPolicy {
    pub fn create(team: &Team) -> bool {
        team.projects_count < team.project_limit
    }
}
```

Then check the team as you would a user, such as in a handler for the route `/teams/{team}/projects`:

```rust
pub async fn store(team: Team) -> laravel::Result<Redirect> {
    team.authorize(ProjectPolicy::create, ()).await?;

    // ...
}
```

Every method of a policy takes the same type first. To check abilities for both users and teams, write a policy for each.

<a name="sharing-abilities-with-the-frontend"></a>
## Sharing abilities with the frontend

Your pages often need to know what the user may do, so they can hide an **Edit** button from someone who cannot edit. Check the abilities on the server and pass the results to your views or Inertia pages.

<a name="sharing-abilities-in-views"></a>
### In views

For server-rendered [views](views.md), evaluate the abilities in your handler and pass them through `data!`:

```rust
use laravel::prelude::*;
use laravel::view::View;

use crate::models::{Post, User};
use crate::policies::post::PostPolicy;

pub async fn show(user: Authenticated<User>, post: Post) -> laravel::Result<View> {
    let can = data! {
        update => user.can(PostPolicy::update, &post).await?,
        delete => user.can(PostPolicy::delete, &post).await?,
    };

    Ok(view("posts.show", data! { post, can }))
}
```

Then branch on those booleans in your template:

```html
{% if can.update %}
    <a href="/posts/{{ post.id }}/edit">Edit</a>
{% endif %}
```

For abilities that every template needs, share them for the current request with [`laravel::view::share`](views.md#sharing-data-with-all-views) inside a middleware.

<a name="sharing-abilities-with-inertia"></a>
### With Inertia

With [Inertia](inertia.md), pass the checked abilities as props:

```rust
use laravel::inertia::{self, Page, props};
use laravel::prelude::*;
use serde_json::json;

use crate::models::{Post, User};
use crate::policies::post::PostPolicy;

pub async fn show(
    user: Authenticated<User>,
    post: Post,
) -> laravel::Result<Page> {
    let can = json!({
        "update": user.can(PostPolicy::update, &post).await?,
        "delete": user.can(PostPolicy::delete, &post).await?,
    });

    Ok(inertia::render("Posts/Show", props! { "post" => &post, "can" => can }))
}
```

For abilities that every page needs, such as whether the user may create posts, return them from your Inertia middleware's [`share`](inertia.md#shared-data) method, in `src/http/middleware`:

```rust
use laravel::http::Request;
use laravel::inertia::{self, Props, props};
use serde_json::json;

use crate::models::User;
use crate::policies::post::PostPolicy;

impl inertia::Middleware for HandleInertiaRequests {
    async fn share(&self, request: &Request) -> laravel::Result<Props> {
        let user: Option<User> = request.user().await?;

        Ok(props! {
            auth => json!({
                "user": user,
                "permissions": {
                    "post": { "create": request.can(PostPolicy::create, ()).await? },
                },
            }),
        })
    }
}
```

A hidden button does not protect an endpoint, so the handler for the action must still call `authorize`.

<a name="testing"></a>
## Testing

To test a handler's authorization, send requests as different users with [`acting_as`](authentication.md#testing), and check each response:

```rust
use laravel::model::create;
use laravel::testing::prelude::*;

#[laravel::test]
async fn only_the_author_may_update_a_post(app: Application) -> laravel::Result<()> {
    let author = create!(User {
        name: "Taylor",
        email: "taylor@laravel.com",
        password: "password",
    })
    .await?;

    let other = create!(User {
        name: "Abigail",
        email: "abigail@laravel.com",
        password: "password",
    })
    .await?;

    let post = create!(Post { user_id: author.id, title: "Hello", published: true }).await?;

    app.put(format!("/posts/{}", post.id))
        .acting_as(&other)
        .json(json!({ "title": "Goodbye" }))
        .await
        .assert_forbidden()
        .assert_json_path("message", "You do not own this post.");

    app.put(format!("/posts/{}", post.id))
        .acting_as(&author)
        .json(json!({ "title": "Goodbye" }))
        .await
        .assert_redirect();

    Ok(())
}
```

A policy method is an ordinary function, so a unit test may also call it directly with records you build in the test, as in `PostPolicy::update(&user, &post)`. `before` runs in a direct call too.