authkit initial

This commit is contained in:
juancwu 2026-04-26 01:36:53 +00:00
commit 134393fbca
43 changed files with 5188 additions and 1 deletions

85
service_authz.go Normal file
View file

@ -0,0 +1,85 @@
package authkit
import (
"context"
"git.juancwu.dev/juancwu/errx"
"github.com/google/uuid"
)
// UserPermissions returns the union of permission names a user holds via
// their assigned roles. Resolved at call time; v1 does not cache.
func (a *Auth) UserPermissions(ctx context.Context, userID uuid.UUID) ([]string, error) {
const op = "authkit.Auth.UserPermissions"
perms, err := a.deps.Permissions.GetUserPermissions(ctx, userID)
if err != nil {
return nil, errx.Wrap(op, err)
}
out := make([]string, len(perms))
for i, p := range perms {
out[i] = p.Name
}
return out, nil
}
// HasPermission checks whether a user holds the named permission via any
// assigned role.
func (a *Auth) HasPermission(ctx context.Context, userID uuid.UUID, name string) (bool, error) {
const op = "authkit.Auth.HasPermission"
perms, err := a.UserPermissions(ctx, userID)
if err != nil {
return false, errx.Wrap(op, err)
}
for _, p := range perms {
if p == name {
return true, nil
}
}
return false, nil
}
// HasRole checks whether a user is assigned the named role.
func (a *Auth) HasRole(ctx context.Context, userID uuid.UUID, name string) (bool, error) {
const op = "authkit.Auth.HasRole"
ok, err := a.deps.Roles.HasAnyRole(ctx, userID, []string{name})
if err != nil {
return false, errx.Wrap(op, err)
}
return ok, nil
}
// HasAnyRole checks whether a user holds at least one of the named roles.
func (a *Auth) HasAnyRole(ctx context.Context, userID uuid.UUID, names []string) (bool, error) {
const op = "authkit.Auth.HasAnyRole"
ok, err := a.deps.Roles.HasAnyRole(ctx, userID, names)
if err != nil {
return false, errx.Wrap(op, err)
}
return ok, nil
}
// AssignRole is a convenience that looks up a role by name and assigns it.
func (a *Auth) AssignRole(ctx context.Context, userID uuid.UUID, roleName string) error {
const op = "authkit.Auth.AssignRole"
r, err := a.deps.Roles.GetRoleByName(ctx, roleName)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.deps.Roles.AssignRoleToUser(ctx, userID, r.ID); err != nil {
return errx.Wrap(op, err)
}
return nil
}
// RemoveRole is the symmetric helper for AssignRole.
func (a *Auth) RemoveRole(ctx context.Context, userID uuid.UUID, roleName string) error {
const op = "authkit.Auth.RemoveRole"
r, err := a.deps.Roles.GetRoleByName(ctx, roleName)
if err != nil {
return errx.Wrap(op, err)
}
if err := a.deps.Roles.RemoveRoleFromUser(ctx, userID, r.ID); err != nil {
return errx.Wrap(op, err)
}
return nil
}