> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 認可

> Laravel for Go のポリシーによる認可（アビリティの定義、チェック、フロントエンドとの共有）の使い方を解説します。

## はじめに

[認証](https://kawax.biz/jp/go/authentication.md)は、現在のユーザーが誰であるかを識別しますが、認可は、それらが実行を許可されるアクションを決定します。たとえば、ブログアプリケーションでは、任意のユーザーは、公開された投稿を読むことがありますが、その著者だけが、それを編集したり削除したりできます。

Laravel は、認可ルールを、ポリシーに組織化します。ポリシーは、関数のセットであり、各アビリティについて1つ（たとえば、投稿を更新したり削除したりする）、各関数は、与えられたユーザーについて決定する `auth.Ability` を返します。アビリティをチェックする場合に、そのポリシー関数自体を呼ぶため、間違った名前や、間違った型のレコードは、アプリケーションがコンパイルする場合に捕まえられます。

```go theme={null}
if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {
	return web.Fail(err)
}
```

## ポリシーを書く

ポリシーを、`policies` パッケージに置き、各モデルに、自身のファイルを与えます。各関数は、その決定がを必要とするレコードを取り、`auth.Ability` を返します。そのアビリティは、そのコンテキストと、ログインしたユーザーを受け取り、そのアクションを許可するには `nil` を返すか、それを拒否するには拒否を返す関数です。

たとえば、各 `Post` モデルが、その著者の `UserID` を保存するとします。`policies/post.go` のこのポリシーは、その著者だけが、投稿を更新したり削除したりすることを許可します。

```go theme={null}
package policies

import (
	"context"

	"go.laravel.com/auth"

	"app/models"
)

func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(user.ID == post.UserID)
	}
}

func DeletePost(post *models.Post) auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(user.ID == post.UserID)
	}
}
```

`auth.Allow` は、その引数が真である場合は `nil` を返し、そうでなければ拒否を返します。登録するものは何もありません。アビリティをチェックする場所ならどこでも、その `policies` パッケージをインポートします。

各関数に、それが許可するアクションと、それがについてのモデルにちなんで名前を付けます。通常の名前は、`ViewAnyPost`、`ViewPost`、`CreatePost`、`UpdatePost`、`DeletePost`、`RestorePost`、`ForceDeletePost` ですが、アプリケーションがを必要とする任意のアビリティを追加できます。

ポリシーは、通常の関数のセットであるため、同じチェックをするアビリティは、同じファイルの、エクスポートされていないヘルパーを共有できます。

```go theme={null}
func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(ownsPost(user, post))
	}
}

func DeletePost(post *models.Post) auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(ownsPost(user, post))
	}
}

func ownsPost(user *models.User, post *models.Post) bool {
	return user.ID == post.UserID
}
```

### ポリシーの応答

`auth.Allow` が、アクションを拒否する場合は、そのユーザーは、`403` ステータスと、デフォルトのメッセージ "This action is unauthorized." を取得します。代わりに、カスタムの拒否メッセージを返すには、そのメッセージで `auth.Deny` を返すか、そのアクションを許可するには `nil` を返します。

```go theme={null}
func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		if user.ID != post.UserID {
			return auth.Deny("You do not own this post.")
		}

		return nil
	}
}
```

レコードが存在するかどうかを、認可されていないユーザーから隠したい場合は（別のチームのプライベートプロジェクトのような）、`auth.DenyAsNotFound()` を返します。それは、`403` の代わりに、`404` ステータスで応答します。

```go theme={null}
func ViewProject(project *models.Project) auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		if user.TeamID != project.TeamID {
			return auth.DenyAsNotFound()
		}

		return nil
	}
}
```

まったく異なる HTTP ステータスコードを必要とする場合は、`auth.DenyWithStatus` を呼びます。それは、そのステータスコードと、その標準のテキスト（`401` については "Unauthorized" のような）で応答します。

```go theme={null}
return auth.DenyWithStatus(401)
```

### レコードなしのアビリティ

一部のアビリティは、まだレコードを含みません。投稿を作成するような。それらの関数は、引数を取りません。これは、ユーザーが、そのメールアドレスを検証したら、投稿を作成することを可能にします。

```go theme={null}
func CreatePost() auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(user.EmailVerifiedAt != nil)
	}
}
```

特定のモデルを含まないアビリティは、管理ダッシュボードを表示するような、自身のファイルへ行きます（たとえば、`policies/admin.go`）。たとえば、ユーザーが、`IsAdmin` フィールドを持つとします。

```go theme={null}
package policies

import (
	"context"

	"go.laravel.com/auth"

	"app/models"
)

func ViewAdminDashboard() auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(user.IsAdmin)
	}
}
```

### ゲスト

デフォルトで、Laravel は、それを実行することなく、ゲストに `auth.Ability` を拒否するため、そのアビリティは、常に、ユーザーを受け取ります。ゲストについて自身で決定するには、代わりに、`auth.GuestAbility` を返します。それは、ログインしていない訪問者について nil を受け取ります。たとえば、投稿が、`Published` フィールドを持つため、誰もが、公開された投稿を表示することがあり、その著者だけが、下書きを表示することがあるとします。

```go theme={null}
func ViewPost(post *models.Post) auth.GuestAbility[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(post.Published || user != nil && user.ID == post.UserID)
	}
}
```

### 管理者にすべてを許可する

時々、そのポリシーがカバーするすべてのアクションを実行を許可される管理者を持つことがあります。すべてのアビリティで `IsAdmin` をチェックするのではなく、同じファイルに、そのチェックでアビリティを包む関数を書き、管理者が常に行うことがある各アビリティを包みます。

```go theme={null}
func orAdmin(ability auth.Ability[models.User]) auth.Ability[models.User] {
	return func(ctx context.Context, user *models.User) error {
		if user.IsAdmin {
			return nil
		}

		return ability(ctx, user)
	}
}

func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return orAdmin(func(_ context.Context, user *models.User) error {
		return auth.Allow(user.ID == post.UserID)
	})
}
```

そのラッパーは、それが包むアビリティの前に実行され、3つの方法のうちの1つで決定します。

* `nil` を返すことは、包まれたアビリティを実行することなく、直ちに許可を与えます。
* 拒否を返すこと（停止されたユーザーについての `auth.Deny("Your account is suspended.")` のような）は、直ちに許可を拒否します。
* 包まれたアビリティを呼ぶことは、それが自身で決定することを可能にします。

Laravel は、`auth.Ability` が実行される前に、ゲストを拒否するため、`orAdmin` は、nil のユーザーを決して受け取りません。`auth.GuestAbility` は、まず nil をチェックする、自身のラッパーを必要とします。

管理者が、数個のアクションを除くすべてを行うことがある場合は、投稿を永久に削除するような、それらのアビリティから `orAdmin` を外します。

```go theme={null}
func ForceDeletePost(post *models.Post) auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(user.ID == post.UserID)
	}
}
```

### データベースをクエリするアビリティ

すべてのアビリティは、そのリクエストの `context.Context` を受け取るため、ポリシーは、そのコンストラクタのシグネチャを変更することなく、データベースをクエリしたり、時計を読んだり、アプリケーションのサービスを呼んだりできます。たとえば、このポリシーは、著者が、投稿にコメントがない間だけ、それを削除することを許可します。

```go theme={null}
package policies

import (
	"context"

	"go.laravel.com/auth"
	"go.laravel.com/model"

	"app/models"
)

func DeletePost(post *models.Post) auth.Ability[models.User] {
	return func(ctx context.Context, user *models.User) error {
		if user.ID != post.UserID {
			return auth.Deny("You do not own this post.")
		}

		commented, err := model.Query[models.Comment]().Where("post_id", "=", post.ID).Exists(ctx)
		if err != nil {
			return err
		}

		if commented {
			return auth.Deny("You can't delete a post with comments.")
		}

		return nil
	}
}
```

呼び出し元は、それを、その他のポリシーと同じ方法でチェックします。`auth.Authorize(r, policies.DeletePost(&post))` で。そのアビリティが、拒否でないエラーを返す場合は（失敗したデータベースクエリのような）、Laravel は、そのリクエストを、それを認可の拒否として扱うのではなく、`500` サーバーエラーで失敗させます。

## アビリティをチェックする

ポリシーが書かれたら、そのハンドラーで、そのアビリティを、`auth.Authorize` や `auth.Can` でチェックし、そのリクエストと、そのポリシー関数が返すアビリティを渡します。

この例では、そのハンドラーは、その投稿を、[`model.FromRoute`](https://kawax.biz/jp/go/models#ルートからモデルを探す)で探します。その投稿を更新できるユーザーだけが、その編集ページを見て、その投稿のページは、そのフロントエンドに、**Delete** ボタンを表示するかどうかを伝えます。

```go theme={null}
package posts

import (
	"go.laravel.com/auth"
	"go.laravel.com/inertia"
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
	"app/policies"
)

func Edit(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Edit", inertia.Props{"post": post})
}

func Show(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	canDelete, err := auth.Can(r, policies.DeletePost(&post))
	if err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Show", inertia.Props{"post": post, "canDelete": canDelete})
}
```

`auth.Authorize` は、そのユーザーが行動できる場合は `nil` を返し、そうでなければ、その拒否を返すため、そのエラーを、`web.Fail` へ渡すことは、その拒否のステータスとメッセージで応答します。`auth.Can` は、`bool` を返すため、それで自身で分岐でき、予期しない失敗についてだけエラーを返します（失敗したクエリのような）。拒否については決してありません。

レコードを取らないアビリティについては、`CreatePost` のような、そのポリシー関数を、引数なしで呼びます。

```go theme={null}
func Create(r *web.Request) *web.Response {
	if err := auth.Authorize(r, policies.CreatePost()); err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Create")
}
```

両方の関数は、そのユーザーを、そのコンテキストから読みます。[`auth.User`](https://kawax.biz/jp/go/authentication#ログインしたユーザーを取得する)がそうするように。そのため、それらは、ゲストが訪問することがあるルートでも同じように動きます。ゲストは、そのアビリティが `GuestAbility` でない限り、`auth.Authorize` から `403` を取得し、`auth.Can` から `false` を取得します。ハンドラーが呼ぶ関数も、それが受け取る `ctx` で、アビリティをチェックできます。`auth.Authorize(ctx, policies.UpdatePost(&post))`。

### より多くの引数を渡す

ポリシー関数は、その決定がを必要とするだけ多くのレコードを取ることがあります。たとえば、著者は、そのカテゴリがロックされていない場合にだけ、投稿を、`Category` へ移動できるとします。

```go theme={null}
func MovePost(post *models.Post, category *models.Category) auth.Ability[models.User] {
	return func(_ context.Context, user *models.User) error {
		return auth.Allow(user.ID == post.UserID && !category.Locked)
	}
}
```

そのアビリティをチェックする場合は、そのレコードを、その関数の順序で渡します。

```go theme={null}
if err := auth.Authorize(r, policies.MovePost(&post, &category)); err != nil {
	return web.Fail(err)
}
```

### フォームを認可する

[フォーム型](https://kawax.biz/jp/go/validation.md#リクエストの認可)は、入ってくるリクエストを自身で認可できるため、そのフォームを検証するすべてのハンドラーは、同じアビリティをチェックし、`auth.Authorize` を呼ぶ必要はありません。そのフォーム型に、`Authorize` メソッドを与えます。そのアビリティが、モデルを必要とする場合は（`/posts/{post}` ルートの投稿のような）、そのモデルを、そのルートから探し、`auth.Authorize` の結果を返します。

```go theme={null}
package posts

import (
	"go.laravel.com/auth"
	"go.laravel.com/model"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"

	"app/models"
	"app/policies"
)

type UpdatePost struct {
	Title string `json:"title"`
}

func (UpdatePost) Authorize(r *web.Request) error {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return err
	}

	return auth.Authorize(r, policies.UpdatePost(&post))
}

func (f *UpdatePost) Rules() validation.Rules {
	return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)))
}

func Update(r *web.Request) *web.Response {
	form, err := r.Validate[UpdatePost]()
	if err != nil {
		return web.Fail(err)
	}

	// Only users who may update the post get here, with a valid form.Title...

	return web.Redirect("/posts/" + r.PathValue("post"))
}
```

`r.Validate` は、その入力を検証する前に、現在のユーザーについて `Authorize` を呼びます。その投稿を更新できないユーザーは、検証エラーではなく、その拒否の応答を取得します。

### ユーザー以外の型をチェックする

アビリティは、ユーザー以外の型について決定することがあります。その計画が、それが持つプロジェクトの数を制限するチームのような。そのアビリティを、そのユーザーの代わりに、その型で書きます。

```go theme={null}
func CreateProject() auth.Ability[models.Team] {
	return func(_ context.Context, team *models.Team) error {
		return auth.Allow(team.ProjectsCount < team.ProjectLimit)
	}
}
```

`auth.Authorize` と `auth.Can` は、ログインしたユーザーだけをチェックするため、そのチームをチェックするには、それを、`auth.AuthorizeFor` へ渡します。それは、そのアビリティの拒否を返し、それは、`403` とそのメッセージで応答し、nil の対象を、ゲストとして扱います。これは、ルート `/teams/{team}/projects` についてのハンドラーです。

```go theme={null}
func Store(r *web.Request) *web.Response {
	team, err := model.FromRoute[models.Team](r, "team")
	if err != nil {
		return web.Fail(err)
	}

	if err := auth.AuthorizeFor(r, &team, policies.CreateProject()); err != nil {
		return web.Fail(err)
	}

	// ...
}
```

代わりに `bool` を取得することを好む場合は、`auth.Allows(r, &team, policies.CreateProject())` を呼びます。両方は、ログインしたユーザー以外のユーザーもチェックします。たとえば、チームの各メンバー。

ハンドラーの外のコードも、それが引数として受け取るユーザーを、`auth.AuthorizeFor` でチェックします。そのチェックは、その後、ハンドラーと同様に、ジョブやコマンドでも動きます。

```go theme={null}
func Publish(ctx context.Context, author *models.User, post *models.Post) error {
	if err := auth.AuthorizeFor(ctx, author, policies.UpdatePost(post)); err != nil {
		return err
	}

	return model.Update(ctx, post, db.Values{"published_at": date.Now(ctx)})
}
```

## アビリティをフロントエンドと共有する

ページは、しばしば、そのユーザーが何をできるかを知る必要があります。そのため、編集できない人から、**Edit** ボタンを隠すことができます。そのアビリティを、そのサーバーでチェックし、その結果を、ビューや Inertia ページへ渡します。

### ビューで

サーバーレンダリングされた[ビュー](https://kawax.biz/jp/go/views.md)では、そのアビリティを、そのボタンがある場所の `can` 関数へ渡します。`cannot` は、その逆をします。ビューは、与える関数だけを呼ぶことができるため、ポリシー関数を、`bootstrap/app.go` の `ViewFuncs` へ追加します。テンプレートガイドの[ユーザーとアビリティ](https://kawax.biz/jp/go/templates.md#ユーザーとアビリティ)についてのセクションが示すように。その後、そのアビリティで、テンプレートで分岐します。

```html theme={null}
{{if can (updatePost .Post)}}
    <a href="{{route "posts.edit" "post" .Post.ID}}">Edit</a>
{{end}}
```

### Inertia で

[Inertia](https://kawax.biz/jp/go/inertia.md)では、そのアビリティを、ハンドラーでチェックし、その結果を、props として渡します。

```go theme={null}
func Show(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	canUpdate, err := auth.Can(r, policies.UpdatePost(&post))
	if err != nil {
		return web.Fail(err)
	}

	canDelete, err := auth.Can(r, policies.DeletePost(&post))
	if err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Show", inertia.Props{
		"post": post,
		"can":  map[string]bool{"update": canUpdate, "delete": canDelete},
	})
}
```

すべてのページがを必要とするアビリティについては、ユーザーが、投稿を作成できるかどうかのような、Inertia ミドルウェアの [`share`](https://kawax.biz/jp/go/inertia#共有データ)関数から、それらを返します。`bootstrap/app.go` で。ドットを持つキーは、共有の `auth` prop へ、`auth.user` の隣に追加します。

```go theme={null}
func share(r *web.Request) (inertia.Props, error) {
	canCreatePosts, err := auth.Can(r, policies.CreatePost())
	if err != nil {
		return nil, err
	}

	return inertia.Props{
		"name":                         config.From(r).App.Name,
		"auth.user":                    models.CurrentUser(r),
		"auth.permissions.post.create": canCreatePosts,
	}, nil
}
```

隠されたボタンは、エンドポイントを保護しないため、そのアクションについてのハンドラーは、なお、`auth.Authorize` を呼ばなければなりません。

## テスト

ハンドラーの認可をテストするには、異なるユーザーとして、[`ActingAs`](https://kawax.biz/jp/go/authentication#テスト)でリクエストを送り、各応答をチェックします。このテストは、[ポリシーの応答](https://kawax.biz/jp/go/authorization.md#ポリシーの応答)の `UpdatePost` アビリティを期待します。

```go theme={null}
package feature_test

import (
	"strconv"
	"testing"

	"go.laravel.com/model"

	"app/database/factories"
	"app/models"
	"app/tests"
)

func TestOnlyTheAuthorMayUpdateAPost(t *testing.T) {
	client := tests.New(t)
	author := client.Create(factories.User)
	other := client.Create(factories.User)

	post := models.Post{UserID: author.ID, Title: "Hello", Published: true}
	if err := model.Create(client.Context(), &post); err != nil {
		t.Fatal(err)
	}

	path := "/posts/" + strconv.FormatInt(post.ID, 10)

	client.ActingAs(&other).PutJSON(path, map[string]string{"title": "Goodbye"}).
		AssertForbidden().
		AssertJSONPath("message", "You do not own this post.")

	client.ActingAs(&author).PutJSON(path, map[string]string{"title": "Goodbye"}).
		AssertRedirect(path)
}
```

アビリティは、通常の関数であるため、ユニットテストも、それを、テストで構築するレコードで直接呼ぶことがあります（`policies.UpdatePost(&post)(t.Context(), &user)`）。`orAdmin` のようなラッパーも、直接の呼び出しで実行されます。


## Related topics

- [認可](https://kawax.biz/jp/rust/authorization.md)
- [認可(ゲートとポリシー)](https://kawax.biz/jp/authorization.md)
- [パッケージの認可ポリシー登録と上書き](https://kawax.biz/jp/advanced/package-authorization.md)
- [パッケージのブロードキャストチャンネル認可と上書き](https://kawax.biz/jp/advanced/package-broadcasting.md)
- [Laravel MCP](https://kawax.biz/jp/mcp.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.