# 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


[authentication](/ja/rust/docs/authentication) が現在のユーザーを識別するのに対し、認可はユーザーに許可する操作を決めます。たとえばブログでは誰でも公開済みの記事を読めますが、編集や削除は投稿者だけに許可できます。


Laravel は認可ルールをポリシーにまとめます。各ポリシーは、特定のモデルやリソースの権限（`update` や `delete` など）をメソッドで定義する構造体です。権限の確認時にはポリシーメソッド自体を渡すため、名前の誤記やモデル型の不一致はコンパイル時に検出されます。

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

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

## Writing policies


`impl` ブロックに `#[policy]` を付けてポリシーを定義します。通常はモデルにちなんだ名前のユニット構造体に定義します。各メソッドは最初にユーザー、該当する場合は続いてモデルを受け取り、操作を許可するかを返します。


各 `Post` モデルが投稿者の `user_id` を保存しているとします。次のポリシーは `src/policies/post.rs`、またはモデルと同じ `src/models/post.rs` に置き、投稿者だけに記事の更新と削除を許可します。

```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
    }
}
```


`src/models/post.rs` でモデルとともに定義したポリシーは、`src/models/mod.rs` から再エクスポートしてください。

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

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


ポリシーを専用の `src/policies` ディレクトリに置く場合は、[adding your own modules](/ja/rust/docs/structure#adding-your-own-modules) の説明に従って `src/lib.rs` に `policies` モジュールを宣言し、`src/policies/mod.rs` から各ポリシーを再エクスポートしてください。

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

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

pub use post::PostPolicy;
```


メソッドには許可する操作に合った名前を付けます。一般的には `view_any`、`view`、`create`、`update`、`delete`、`restore`、`force_delete` を使いますが、アプリケーションに必要な権限を追加できます。


`#[policy]` はブロック内のすべての関数を権限として扱うため、共通のヘルパー関数は `#[policy]` のない別の `impl` ブロックに置きます。

```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


ポリシーメソッドが `false` を返すと、`403` ステータスと既定のメッセージ "This action is unauthorized." で操作を拒否します。独自の拒否メッセージを返すには、`Access::allow()` と `Access::deny(..)` による `Access` レスポンスを返します。

```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.")
        }
    }
}
```


別のチームの非公開プロジェクトなど、権限のないユーザーにレコードの存在を隠すには `Access::deny_as_not_found()` を返します。`403` の代わりに `404` ステータスで応答します。

```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()
        }
    }
}
```


ほかの HTTP ステータスコードが必要なら、`Access::deny_with_status(..)` を呼び出します。指定したステータスコードと標準の理由フレーズで応答します。

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

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

### Abilities without a record


記事の作成など、まだレコードがない権限もあります。このようなメソッドはユーザーだけを受け取ります。次の例は、メール認証を済ませたユーザーに記事の作成を許可します。

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

    // ...
}
```


管理者ダッシュボードの表示など、特定のモデルに関係しない権限は専用のポリシーに置きます。たとえばユーザーに `is_admin` カラムがあるとします。

```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


既定では、`&User` を受け取るポリシーメソッドはゲストに対して実行せず、自動的に拒否します。ゲストを明示的に評価するには `Option<&User>` を受け取り、未認証の訪問者には `None` が渡されます。次は記事に `published` カラムがあり、公開済みの記事は誰でも、下書きは投稿者だけが閲覧できる例です。

```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


ポリシーのすべての操作を許可する管理者がいる場合があります。各メソッドで `is_admin` を確認する代わりに、`before` メソッドを追加してください。ユーザーを受け取り `Option<bool>` を返します。

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

    // ...
}
```


`before` メソッドは、ポリシーのほかのすべてのメソッドより先に自動実行されます。


- `Some(true)` を返すと、要求された権限メソッドを実行せず、直ちに許可します。
- `Some(false)` を返すと、直ちに拒否します。
- `None` を返すと、`update` や `delete` などの要求された権限メソッドに処理が移り、そのメソッドが判断します。


`before` は `&User` を受け取るため、未認証のゲストでは省略されます。そのため `Option<&User>` を受け取るゲスト向けメソッドが、ゲストを直接評価できます。


管理者に記事の完全削除以外を許可する場合など、`before` が評価対象の権限を知る必要がある場合は、メソッド名を 2 番目の `&str` パラメーターとして受け取ります。

```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


認可の確認でデータベースを問い合わせる必要があれば、ポリシーメソッドを `async` にして `laravel::Result` を返します。次のポリシーは、コメントのない記事だけ投稿者に削除を許可します。

```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())
    }

    // ...
}
```


非同期ポリシーメソッドがデータベースクエリの失敗などで `Err` を返すと、Laravel は認可拒否ではなく `500` サーバーエラーとしてリクエストを失敗させます。

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

## Checking abilities


ポリシーを定義したら、ハンドラーでユーザー型の `authorize` または `can` に、ポリシーメソッドと追加の引数を順に渡して権限を確認します。


ハンドラーでは `Authenticated<User>` でログインユーザーを抽出し、[route model binding](/ja/rust/docs/models#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` は拒否時にエラーを返すため、`?` によって [configured status and message](#denying-with-a-message) でハンドラーが中断されます。`can` は `bool` を返すので、自分で処理を分岐できます。


両メソッドは [prelude](/ja/rust/docs/prelude) がインポートする `Authorizable` トレイトのもので、すべての `Authenticatable` モデルに自動実装されます。


`PostPolicy::create` など、ユーザー以外のモデルや追加引数を受け取らない権限には、2 番目の引数として `()` を渡します。

```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


ゲストもログインユーザーもアクセスできるルートでは、`Auth<User>` または `Request` の `can` や `authorize` を呼び出します。

```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?;

    // ...
}
```


ポリシーメソッドが [`Option<&User>`](#guests) を受け取らない限り、ゲストには `authorize` が `403`、`can` が `false` を返します。

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

### Passing more arguments


判断が複数のモデルに依存する場合、ポリシーメソッドはユーザーの後に最大 3 つの追加引数を受け取れます。たとえば、投稿者が記事を `Category` に移動できるのは、そのカテゴリーがロックされていない場合だけだとします。

```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
    }

    // ...
}
```


2 つまたは 3 つの引数は、メソッドと同じ順序のタプルとして渡します。

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

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

### Authorizing a form


[form type](/ja/rust/docs/validation#authorizing-the-request) は `#[validate(authorize(..))]` で受信リクエストを自動認可できるので、ハンドラー自身が `authorize` を呼ぶ必要はありません。`/posts/{post}` の `Post` など、ポリシーメソッドがモデルを要求する場合は `route("post")` を渡し、そのルートパラメーターを解決してモデルをポリシーに渡します。

```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>` は入力のバリデーション前に、現在のユーザーに対して `PostPolicy::update` を確認します。記事を更新できないユーザーには、バリデーションエラーではなく拒否のレスポンスが返されます。


レコードを伴わない権限では、`#[validate(authorize(PostPolicy::create))]` のように引数を省略します。複数のレコードは `authorize(PostPolicy::move_to, route("post"), route("category"))` のようにメソッドの順序で列挙します。

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

### Checking types other than users


プランによってプロジェクト数が制限されるチームなど、ユーザー以外の型にもポリシーで権限を決められます。その型に空の `impl` で `Authorizable` を実装し、ポリシーの最初の引数にその型を使います。

```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
    }
}
```


続いて、`/teams/{team}/projects` のハンドラーなどで、ユーザーと同様にチームを確認します。

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

    // ...
}
```


1 つのポリシー内では、すべてのメソッドが最初に同じ型を受け取ります。ユーザーとチームの両方を確認するには、それぞれのポリシーを作成してください。

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

## Sharing abilities with the frontend


ページでは、編集できないユーザーに **Edit** ボタンを表示しないなど、ユーザーに許可された操作を知る必要がよくあります。サーバーで権限を確認して、ビューや Inertia ページに結果を渡してください。

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

### In views


サーバーで描画する [views](/ja/rust/docs/views) では、ハンドラーで権限を評価し、`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 }))
}
```


続いてテンプレートでその真偽値を使って分岐します。

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


すべてのテンプレートで必要な権限は、ミドルウェア内の [`laravel::view::share`](/ja/rust/docs/views#sharing-data-with-all-views) を使って現在のリクエストで共有します。

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

### With Inertia


[Inertia](/ja/rust/docs/inertia) では、確認した権限を 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 }))
}
```


ユーザーが記事を作成できるかなど、全ページで必要な権限は、`src/http/middleware` にある Inertia ミドルウェアの [`share`](/ja/rust/docs/inertia#shared-data) メソッドから返します。

```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? },
                },
            }),
        })
    }
}
```


ボタンを隠してもエンドポイントは保護されないため、その操作のハンドラーで必ず `authorize` を呼び出してください。

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

## Testing


ハンドラーの認可をテストするには、[`acting_as`](/ja/rust/docs/authentication#testing) を使って異なるユーザーとしてリクエストを送信し、それぞれのレスポンスを確認します。

```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(())
}
```


ポリシーメソッドは通常の関数なので、単体テスト内で作ったレコードを使って `PostPolicy::update(&user, &post)` のように直接呼び出せます。直接呼び出した場合も `before` は実行されます。