# 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](/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


기본적으로 Laravel은 능력을 실행하기 전에 비로그인 사용자를 거부하므로 `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)
	})
}
```


래퍼는 능력보다 먼저 실행되며 세 가지 방식으로 판단합니다.


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


인가에 조회가 필요하면 폴리시의 첫 인수로 `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`을 전달합니다. 조회 실패 등 거부 이외의 오류가 반환되면 Laravel은 인가 거부 대신 `500` 서버 오류로 요청을 실패시킵니다.

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

## Checking abilities


폴리시 작성 후 핸들러에서 요청과 반환된 능력을 `auth.Authorize`나 `auth.Can`에 전달하여 검사하세요.


다음 핸들러는 [`model.FromRoute`](/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`](/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](/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](/go/docs/views)에서는 버튼 위치의 `can`에 능력을 전달하세요. `cannot`은 반대입니다. 뷰는 전달받은 함수만 호출하므로 [users and abilities](/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](/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`](/go/docs/inertia#shared-data)에서 반환하세요. 점이 있는 키는 `auth.user` 옆의 공유 `auth` prop에 추가됩니다.

```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`](/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` 같은 래퍼도 직접 호출 시 실행됩니다.