# Authorization

Source: https://bogie-go.com/docs/authorization.html

Since v0.7.0, `bogie g policy` writes authorization as plain Go. There is no Bogie import, no role table, and no framework runtime. [Authentication](https://bogie-go.com/docs/authentication.html) is who is asking; a policy is whether they may. The generated guards still answer 401 when the request is not authenticated. A policy denial is 403.

## The commands

The usual path is token authentication first, then a scaffold with `--policy`:

```
bogie g authentication token
bogie g scaffold post title:string body:text --policy
```

The second command prints:

```
      create  db/migrate/20261113092202_create_posts.sql
      create  db/queries/posts.sql
      create  app/models/post.go
      create  app/models/post_test.go
      create  db/adapter/posts.go
      create  db/adapter/posts_test.go
      create  test/factories/posts.go
      create  app/views/posts.go
      create  app/controllers/posts_controller.go
      create  app/controllers/posts_controller_test.go
      create  app/policies/actor.go
      create  app/policies/policies_suite_test.go
      create  app/policies/post_policy.go
      create  app/policies/post_policy_test.go
      create  app/services/posts/posts.go
      create  app/services/posts/posts_suite_test.go
      create  app/services/posts/posts_test.go
      insert  app/controllers/application.go: Posts *PostsController
      insert  app/application.go: server.Posts = controllers.NewPostsController(posts.New(store, log), log)
      insert  app/controllers/routes.go: s.Posts.SetupRoutes(s.WithUser(&r.RouterGroup))
         run  sqlc generate
```

The migration stamp is the UTC time it was generated; yours will differ. The controller is constructed with the new service, not the store, and the route is mounted on `s.WithUser`. The model gains a `user_id` string when it does not already have one.

`--policy` needs token authentication already in the app. Without it, the generator writes nothing and says:

```
bogie: generate scaffold: --policy reads the actor from token authentication (middlewares.Subject and middlewares.Role); run bogie g authentication token first
```

When the model already exists and has a `user_id` string, generate the policy alone:

```
bogie g policy note
```

```
   identical  app/policies/actor.go
   identical  app/policies/policies_suite_test.go
      create  app/policies/note_policy.go
      create  app/policies/note_policy_test.go
      create  app/services/notes/notes.go
      create  app/services/notes/notes_suite_test.go
      create  app/services/notes/notes_test.go
```

A second run reports each of those files `identical`. There is no model, or it has no `UserID` field:

```
bogie: generate policy: no model widget (app/models/widget.go); bogie g model widget user_id:string first, or bogie g scaffold widget --policy
bogie: generate policy: app/models/widget.go: no UserID field; add user_id:string
```

`--policy` also works on `g scaffold_controller`, when the model already has `user_id`.

## The policy file

`app/policies/post_policy.go` has one method per action on `policies.Post`: `CanIndex`, `CanShow`, `CanCreate`, `CanUpdate`, `CanDestroy`. Each takes an `Actor` and a `*models.Post` and returns bool. They are methods, not package functions, so `policies.Note` can define the same five actions in the same package.

```
// Post is the authorization for a post. Call it as policies.Post.CanShow(actor, post).
var Post PostPolicy

// PostPolicy is one function per action. Each takes the actor and the post
// and returns whether the actor may do it. The default allows only what the
// actor owns.
type PostPolicy struct{}

// CanShow reports whether actor may read a post. Allowed only when the actor owns it.
func (PostPolicy) CanShow(actor Actor, post *models.Post) bool {
	return PostPolicy{}.owns(actor, post)
}

// owns reports whether actor owns post. The owner is post.UserID, the same
// string authentication records as the subject. An actor with no id owns
// nothing, and a nil post is not owned by anyone. A role does not widen
// this: an admin owns only their own post until a method above says so.
func (PostPolicy) owns(actor Actor, post *models.Post) bool {
	return actor.ID != "" && post != nil && post.UserID == actor.ID
}
```

The other four actions call the same `owns` helper. Change a method when a role should widen that default. The actor is an id and a role string, already put on the request by token authentication (`middlewares.Subject`, `middlewares.Role`). Nothing in this package loads a user or a role:

```
// ErrDenied is a policy that refused. A controller maps it to 403 the same
// way it maps models.ErrNotFound to 404, with errors.Is, in the one place
// that mapping lives.
var ErrDenied = errors.New("denied")

// Actor is who is asking. ID is the subject authentication put on the
// request (a user id, usually) and Role is the role string it put beside
// the subject. Both are already on the request context; nothing here loads
// a user or a role.
type Actor struct {
	ID   string
	Role string
}
```

The spec beside the policy is a table: one row per role (`member`, `admin`) and action, for the owner (`user-1`) and for someone else (`user-2`). Under the default, a member and an admin are allowed only for their own post; a role is not a grant until you change a method. Two extra examples deny an actor with no id and a nil post.

## The service and the 403

`--policy` also writes `app/services/posts`, which checks the policy and then the store. It knows nothing about HTTP. A refusal is `policies.ErrDenied`. Create stamps the owner from the actor before it asks the policy, so the body cannot choose one; update keeps the stored `UserID`. Index returns only the rows the actor may list:

```
func (s *Service) Create(ctx context.Context, actor policies.Actor, p models.Post) (models.Post, error) {
	p.UserID = actor.ID
	if !policies.Post.CanCreate(actor, &p) {
		s.deny(ctx, "create", actor)
		return models.Post{}, policies.ErrDenied
	}
	return s.store.CreatePost(ctx, p)
}

func (s *Service) Index(ctx context.Context, actor policies.Actor, limit int32) ([]models.Post, error) {
	posts, err := s.store.ListPosts(ctx, limit)
	if err != nil {
		return nil, err
	}
	owned := make([]models.Post, 0, len(posts))
	for i := range posts {
		if policies.Post.CanIndex(actor, &posts[i]) {
			owned = append(owned, posts[i])
		}
	}
	return owned, nil
}
```

The controller reads the actor off the request, calls one service method, and maps errors in `fail`. A denial is 403, in the same switch as 404 and 422:

```
func (ctl *PostsController) actor(c *gin.Context) policies.Actor {
	return policies.Actor{ID: middlewares.Subject(c), Role: middlewares.Role(c)}
}

func (ctl *PostsController) fail(c *gin.Context, err error) {
	switch {
	case errors.Is(err, models.ErrNotFound):
		c.JSON(http.StatusNotFound, views.ErrorMessage("no such post"))
	case errors.Is(err, models.ErrInvalid):
		c.JSON(http.StatusUnprocessableEntity, views.Error(err))
	case errors.Is(err, policies.ErrDenied):
		c.JSON(http.StatusForbidden, views.ErrorMessage("forbidden"))
	default:
		ctl.Log.ErrorContext(c.Request.Context(), "posts: request failed",
			"path", c.FullPath(), "err", err, "request_id", c.GetString("request_id"))
		c.JSON(http.StatusInternalServerError, views.ErrorMessage("internal error"))
	}
}
```

`views.ErrorMessage("forbidden")` is the body `{"status":"error","error":"forbidden"}`. Create takes only `title` and `body` from the JSON; the service sets `UserID`. Update loads the post through `Show` first (so a non-owner is already denied) and passes the stored `UserID` through.

A non-owner's `GET /posts/1` is 403. Their `GET /posts` is 200 with `{"posts":[]}`: index returns only rows the actor owns. A request with no token is still 401 from the guard, `{"status":"error","error":"a bearer token is required"}`, the same as on the [Authentication](https://bogie-go.com/docs/authentication.html) page.

## The role claim and MintFor

The token-auth generator now keeps an optional `role` claim. `Mint(subject, ttl)` still signs a token with no role; it is a wrapper around `MintFor`:

```
func (m Maker) Mint(subject string, ttl time.Duration) (string, error) {
	return m.MintFor(subject, "", ttl)
}

// MintFor signs a token for subject in role. An empty role is the same as Mint.
func (m Maker) MintFor(subject, role string, ttl time.Duration) (string, error) {
	if subject == "" {
		return "", fmt.Errorf("%w: empty subject", ErrInvalid)
	}
	now := time.Now()
	claims := signedClaims{
		Role: role,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    m.Issuer,
			Subject:   subject,
			IssuedAt:  jwt.NewNumericDate(now),
			ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
			ID:        uuid.NewString(),
		},
	}
	return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(m.Secret)
}
```

The JWT payload is the registered claims plus `` `json:"role,omitempty"` ``. Verify copies that string onto `Claims.Role`. The guard puts it on the context beside the subject, and `middlewares.Role(c)` reads it (empty when the token carried none, or when the route is not behind `RequireUser`). A role still does not widen the default policy until you change a method.

The request helper `.As(subject)` still calls `Mint`, so a request spec mints a token with an empty role. To send a role, mint with `MintFor` and pass the token in yourself (`WithAuthorization`).

An app that already had token authentication before v0.7.0 does not get these files from `app:update`. Re-run `bogie g authentication token` after porting any hand edits, or add the claim and `MintFor` by hand. See [Upgrading an app](https://bogie-go.com/docs/upgrading.html#v0-7).

## Removing

```
bogie d policy post
```

removes the policy, its spec and its service. It refuses when a controller is still wired to that service:

```
bogie: destroy policy: the posts controller is wired to this policy's service; bogie d scaffold post removes the resource and the policy together
```

`bogie d scaffold post` removes the resource and the policy together. `bogie d policy note`, on a policy with no controller wired, removes the five files it created (the policy, its spec, and the service package).
