# 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](#allowing-administrators-everything)
    - [Abilities that query the database](#abilities-that-query-the-database)
- [Checking abilities](#checking-abilities)
    - [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/go/docs/authentication) がユーザーを識別し、認可は許される操作を決定します。ブログなら誰でも公開済み投稿を読めますが、編集・削除は著者だけに許可します。


Laravel は認可規則をポリシーにまとめます。投稿更新・削除など能力ごとの関数の集合で、各関数はユーザーについて判断する `auth.Ability` を返します。直接関数を呼ぶため名前の誤記や型の違いをコンパイル時に検出できます。

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

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

## Writing policies


`policies` パッケージにモデルごとのファイルを置きます。各関数は判断に必要なレコードを受け取り `auth.Ability` を返します。この能力関数はログイン中のユーザーを受け、許可なら `nil`、拒否なら拒否結果を返します。


各 `Post` が著者の `UserID` を持つ場合、次の `policies/post.go` は著者だけに更新・削除を許可します。

```go
package policies

import (
	"go.laravel.com/auth"

	"app/models"
)

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

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


`auth.Allow` は引数が真なら `nil`、それ以外は拒否を返します。登録不要で、確認する場所に `policies` をインポートします。


関数名は操作とモデルに合わせます。通常は `ViewAnyPost`、`ViewPost`、`CreatePost`、`UpdatePost`、`DeletePost`、`RestorePost`、`ForceDeletePost` で、必要な能力を追加できます。


通常の関数なので、同じ判断をする能力は同じファイルの非公開ヘルパを共有できます。

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

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

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

<a name="denying-with-a-message"></a>

### Policy responses


`auth.Allow` の拒否は `403` と既定メッセージ「This action is unauthorized.」になります。独自メッセージは `auth.Deny` に渡し、許可には `nil` を返します。

```go
func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return func(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
func ViewProject(project *models.Project) auth.Ability[models.User] {
	return func(user *models.User) error {
		if user.TeamID != project.TeamID {
			return auth.DenyAsNotFound()
		}

		return nil
	}
}
```


別のコードには `auth.DenyWithStatus` を使います。`401` の「Unauthorized」など、指定コードと標準の文言を返します。

```go
return auth.DenyWithStatus(401)
```

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

### Abilities without a record


投稿作成などレコードがまだない能力は引数を取りません。次はメール認証済みユーザーに投稿作成を許可します。

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


管理画面など特定モデルに関係しない能力は `policies/admin.go` などに置きます。`IsAdmin` フィールドがある場合の例です。

```go
package policies

import (
	"go.laravel.com/auth"

	"app/models"
)

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

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

### Guests


既定では実行前にゲストを拒否するため `auth.Ability` は必ずユーザーを受け取ります。自分で判断するにはゲストで `nil` を受け取る `auth.GuestAbility` を返します。`Published` がある投稿を、公開済みなら誰でも、下書きなら著者だけが閲覧する例です。

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

<a name="allowing-administrators-everything"></a>

### Allowing administrators everything


管理者に全操作を許す場合、各能力で `IsAdmin` を調べる代わりに、同じファイルに検査用ラッパーを作り、常に許す能力を包みます。

```go
func orAdmin(ability auth.Ability[models.User]) auth.Ability[models.User] {
	return func(user *models.User) error {
		if user.IsAdmin {
			return nil
		}

		return ability(user)
	}
}

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


ラッパーは能力より先に実行され、3 通りで判断します。


- `nil` を返すと能力を実行せず即座に許可します。
- 停止ユーザーへの `auth.Deny("Your account is suspended.")` などを返すと即座に拒否します。
- 包んだ能力を呼ぶと、その能力が判断します。


`auth.Ability` の前にゲストを拒否するため `orAdmin` に `nil` は渡りません。`auth.GuestAbility` には先に `nil` を調べる別のラッパーが必要です。


完全削除など一部の操作を管理者にも制限するには、その能力に `orAdmin` を付けません。

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

<a name="abilities-that-query-the-database"></a>

### Abilities that query the database


認可に DB 検索が必要なら第 1 引数で `context.Context` を受けて使います。次はコメントがない間だけ著者に削除を許可します。

```go
package policies

import (
	"context"

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

	"app/models"
)

func DeletePost(ctx context.Context, post *models.Post) auth.Ability[models.User] {
	return func(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
	}
}
```


ハンドラーは `policies.DeletePost(r, &post)` のように `r` を渡します。検索失敗など拒否以外のエラーは認可拒否として扱わず、`500` で失敗させます。

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

## Checking abilities


作成後はハンドラーでリクエストと能力を `auth.Authorize` または `auth.Can` に渡して確認します。


次のハンドラーは [`model.FromRoute`](/ja/go/docs/models#finding-a-model-from-a-route) で投稿を探します。更新できるユーザーだけが編集ページを見られ、投稿ページは**削除**ボタンを表示するかをフロントエンドへ伝えます。

```go
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` で [denial's status and message](#denying-with-a-message) を返せます。`auth.Can` は分岐用の `bool` を返し、拒否ではなく検索失敗などの場合だけエラーを返します。


`CreatePost` などレコードを取らない能力は引数なしで呼びます。

```go
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`](/ja/go/docs/authentication#retrieving-the-logged-in-user) と同様にコンテキストから読み、ゲスト用ルートでも動作します。[`GuestAbility`](#guests) 以外ではゲストに `auth.Authorize` は `403`、`auth.Can` は `false` を返します。呼び出された関数でも `ctx` を使い `auth.Authorize(ctx, policies.UpdatePost(&post))` と検査できます。

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

### Passing more arguments


ポリシーは必要な数のレコードを受け取れます。次はロックされていない `Category` にだけ著者が投稿を移動できる例です。

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


検査時は関数の順序でレコードを渡します。

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

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

### Authorizing a form


[form type](/ja/go/docs/validation#authorizing-the-request) 自体で認可すれば全ハンドラーで同じ能力を検査でき、`auth.Authorize` の呼び出しは不要です。型に `Authorize` を追加します。`/posts/{post}` などのモデルが必要ならルートから探し、`auth.Authorize` の結果を返します。

```go
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` を呼びます。更新権限がなければバリデーションエラーではなく拒否応答になります。

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

### Checking types other than users


プランでプロジェクト数が制限されるチームなど、ユーザー以外の型も判断できます。ユーザーの代わりにその型を使います。

```go
func CreateProject() auth.Ability[models.Team] {
	return func(team *models.Team) error {
		return auth.Allow(team.ProjectsCount < team.ProjectLimit)
	}
}
```


`auth.Authorize` と `auth.Can` はログイン中ユーザーだけを調べるため、チームを直接能力へ渡します。`/teams/{team}/projects` の例のように拒否は `403` とメッセージになります。

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

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

	// ...
}
```


`auth.AuthorizeFor(&team, policies.CreateProject())` も同じ拒否を返し、`nil` はゲスト扱いです。`bool` なら `auth.Allows(&team, policies.CreateProject())` を使います。両方ともチームの各メンバーなど別ユーザーを検査できます。


ハンドラー外では上のチームと同様、引数で受けたユーザーを直接渡します。ジョブやコマンドでも動作します。

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

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

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

## Sharing abilities with the frontend


編集不能なユーザーに**編集**ボタンを隠すため、ページでも権限が必要です。サーバーで確認してビューや Inertia に渡します。

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

### In views


サーバーの [view](/ja/go/docs/views) ではボタン位置の `can` に能力を渡します。`cannot` は逆です。渡した関数だけを呼べるため、[users and abilities](/ja/go/docs/templates#users-and-abilities) のように `bootstrap/app.go` の `ViewFuncs` に追加して分岐します。

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

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

### With Inertia


[Inertia](/ja/go/docs/inertia) ではハンドラーで検査して props に渡します。

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


投稿作成可否など共通の能力は `bootstrap/app.go` の Inertia ミドルウェアの [`share`](/ja/go/docs/inertia#shared-data) で返します。ドット付きキーは共有 `auth` prop の `auth.user` の隣に追加します。

```go
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` が必要です。

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

## Testing


認可テストは [`ActingAs`](/ja/go/docs/authentication#testing) で異なるユーザーとして送り、応答を確認します。次は [policy responses](#denying-with-a-message) の `UpdatePost` を想定します。

```go
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)(&user)` のようにテスト用レコードで直接呼べます。`orAdmin` などのラッパーも実行されます。