authorization

package module
v0.0.0-...-8e6d5bb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 9, 2025 License: MIT Imports: 8 Imported by: 1

Documentation

Index

Constants

View Source
const (
	ContextKeyName = "authorization.authorizations"
)

Variables

View Source
var (
	//nolint:gochecknoglobals // Used as default value and cannot be declared as constant due to its type.
	DefaultExcludedRoutes = make([]string, 0)
	//nolint:gochecknoglobals // Used as default value and cannot be declared as constant due to its type.
	DefaultRoles = make(map[string][]Entitlement)
	//nolint:gochecknoglobals // Used as default value and cannot be declared as constant due to its type.
	DefaultGroups = make(map[string][]Entitlement)
	//nolint:gochecknoglobals // Used as default value and cannot be declared as constant due to its type.
	DefaultUserAuthAdapter = NewJWTUserAuthAdapter

	ErrInvalidExcludedRoutes = errors.New("excluded routes must not be nil")
	ErrInvalidExcludedRoute  = errors.New("excluded route must be absolute and not end with a slash")
	ErrNoRoleMapper          = errors.New("role mapper must not be nil")
	ErrNoGroupMapper         = errors.New("group mapper must not be nil")
	ErrNoRoles               = errors.New("roles must not be nil")
	ErrNoGroups              = errors.New("groups must not be nil")
	ErrNoUserAuthAdapter     = errors.New("user auth adapter must not be nil")
)
View Source
var (
	// Actions is a map that holds a set of predefined actions.
	// This map is used to check if a given action is valid.
	//nolint:gochecknoglobals // Maintain a set of predefined actions that are used throughout the application.
	Actions = map[Action]struct{}{
		CapabilitiesAction: {},
		CreateAction:       {},
		DeleteAction:       {},
		ReadAction:         {},
		ListAction:         {},
		UnknownAction:      {},
		UpdateAction:       {},
	}
)

Functions

func IsAuthorized

func IsAuthorized(ctx *gin.Context, resource string, action Action) bool

IsAuthorized checks if a given action on a resource is authorized for the current context.

func New

func New(config *Config, routerGroup *gin.RouterGroup) gin.HandlerFunc

New creates an authorization middleware handler function for the given configuration and router group. It checks if the request path is excluded from authorization. If not, it generates a new set of authorizations based on the configuration and context, stores them in the context, and proceeds to the next handler.

func RequireAuthorization

func RequireAuthorization(resource string, action Action) gin.HandlerFunc

RequireAuthorization creates a middleware handler that ensures the request is authorized for the specified resource and action. If not authorized, it aborts the request with an error.

func SetAuthorizations

func SetAuthorizations(authorizations Authorizations, ctx *gin.Context)

SetAuthorizations stores the provided Authorizations object in the context.

Types

type Action

type Action string

Action represents the type of action that can be performed on a resource.

const (
	// CapabilitiesAction represents the action of retrieving supported operations on a resource.
	CapabilitiesAction Action = "capabilities"

	// CreateAction represents the action of creating a new resource.
	CreateAction Action = "create"

	// DeleteAction represents the action of deleting an existing resource.
	DeleteAction Action = "delete"

	// ReadAction represents the action of reading or retrieving a single resource.
	ReadAction Action = "read"

	// ListAction represents the action of listing multiple resources.
	ListAction Action = "list"

	// UnknownAction represents an undefined or unsupported action.
	UnknownAction Action = "unknown"

	// UpdateAction represents the action of updating an existing resource.
	UpdateAction Action = "update"
)

type Authorizations

type Authorizations map[string]map[Action]struct{}

Authorizations is a map where the keys are resource names and the values are maps of action names to empty structs. Example:

Authorizations{"books": {"read": {}, "create": {}}, "cars": {{"update": {}}}

func GetAuthorizations

func GetAuthorizations(ctx *gin.Context) (authorizations Authorizations)

GetAuthorizations retrieves the Authorizations object from the context. If no object is found, it returns a new empty Authorizations object instance.

func NewAuthorizations

func NewAuthorizations(config *Config, ctx *gin.Context) Authorizations

NewAuthorizations initializes an Authorizations map based on user, group, and role authorizations. It merges authorizations from user roles and groups, and adds entitlements. Important: The role and group names are converted to lowercase for consistent matching.

func (Authorizations) Add

func (r Authorizations) Add(resource string, action Action)

Add inserts a new action for a resource into the Authorizations map. If the resource already exists, it adds the action to the existing actions.

func (Authorizations) IsAuthorized

func (r Authorizations) IsAuthorized(resource string, action Action) bool

IsAuthorized checks if a given action is authorized for a specified resource. It returns true if the action is allowed, otherwise false.

func (Authorizations) Merge

func (r Authorizations) Merge(authorizations Authorizations)

Merge combines another Authorizations map into the current one. It adds actions from the other map to the existing resources or creates new resources if they don't exist.

type Config

type Config struct {
	// ExcludedRoutes is a list of routes that are excluded from authorization checks.
	ExcludedRoutes []string `json:"excluded_routes" yaml:"excluded_routes" mapstructure:"excluded_routes"`

	// RoleMappingAdapter maps roles to entitlements.
	RoleMappingAdapter RoleGroupMappingAdapter

	// GroupMappingAdapter maps groups to entitlements.
	GroupMappingAdapter RoleGroupMappingAdapter

	// Roles is a map of role names to their entitlements.
	Roles map[string][]Entitlement `json:"roles" yaml:"roles" mapstructure:"roles"`

	// Groups is a map of group names to their entitlements.
	Groups map[string][]Entitlement `json:"groups" yaml:"groups" mapstructure:"groups"`

	// UserAuthAdapter is a function that returns a UserAuthAdapter for user authorization.
	UserAuthAdapter UserAuthAdapterFunc
}

Config holds configuration related to user and API key authentication.

func NewConfig

func NewConfig() *Config

NewConfig creates and returns a new Config having default values.

func (*Config) Validate

func (r *Config) Validate() error

Validate ensures the all necessary configurations are filled and within valid confines. Any misconfiguration results in well-defined standardized errors.

type ConfigRoleGroupMappingAdapter

type ConfigRoleGroupMappingAdapter struct {
	sync.Mutex
	// contains filtered or unexported fields
}

ConfigRoleGroupMappingAdapter maps roles and groups to their authorizations using a configuration.

func NewConfigRoleGroupMappingAdapter

func NewConfigRoleGroupMappingAdapter(config func() map[string][]Entitlement) *ConfigRoleGroupMappingAdapter

NewConfigRoleGroupMappingAdapter initializes a new instance of ConfigRoleGroupMappingAdapter using the provided configuration function. A factory function is necessary as the role and group mappings are not initialized at application startup.

func (*ConfigRoleGroupMappingAdapter) Map

Map returns the cached role-to-authorization map or creates it if not already cached.

type Entitlement

type Entitlement string

Entitlement represents a type for entitlements, which are strings that encode both an action and a resource.

func (Entitlement) Unpack

func (r Entitlement) Unpack() (string, Action)

Unpack splits the Entitlement into its action and resource parts. It returns the resource and action if the Entitlement is valid, otherwise it returns empty strings.

type JWTUserAuthAdapter

type JWTUserAuthAdapter struct {
	// contains filtered or unexported fields
}

JWTUserAuthAdapter is a struct that adapts JWT claims to user authentication details.

func (*JWTUserAuthAdapter) Authorizations

func (r *JWTUserAuthAdapter) Authorizations() Authorizations

Authorizations constructs a map of authorizations from the JWT claims, filtering by known actions.

func (*JWTUserAuthAdapter) Entitlements

func (r *JWTUserAuthAdapter) Entitlements() []string

Entitlements returns the entitlements associated with the user based on the JWT claims.

func (*JWTUserAuthAdapter) Groups

func (r *JWTUserAuthAdapter) Groups() []string

Groups returns the groups associated with the user based on the JWT claims.

func (*JWTUserAuthAdapter) Roles

func (r *JWTUserAuthAdapter) Roles() []string

Roles returns the roles associated with the user based on the JWT claims.

type RoleGroupMap

type RoleGroupMap map[string]Authorizations

RoleGroupMap defines a mapping from role or group names to their respective authorizations.

type RoleGroupMappingAdapter

type RoleGroupMappingAdapter interface {
	Map() RoleGroupMap
}

RoleGroupMappingAdapter is an interface for mapping roles or groups to their authorizations.

type UserAuthAdapter

type UserAuthAdapter interface {
	// Groups returns a slice of group names the user belongs to.
	// Example: ["group1", "group2"]
	Groups() []string

	// Roles returns a slice of role names assigned to the user
	// Example: ["admin", "guest"]
	Roles() []string

	// Entitlements returns a slice of user's entitlements in the format "<action>_<resource>".
	// Example: ["read_resource1", "write_resource2"]
	Entitlements() []string

	// Authorizations returns a map of user's authorizations with the schema: "<resource>[<action>]".
	// The outer map's keys are resource names, and the values are maps where:
	// - The keys are action names.
	// - The values are empty structs.
	// Example: {"resource1": {"read": {}, "write": {}}, "resource2": {"read": {}}}
	Authorizations() Authorizations
}

func NewJWTUserAuthAdapter

func NewJWTUserAuthAdapter(ctx *gin.Context) UserAuthAdapter

NewJWTUserAuthAdapter creates a new instance of JWTUserAuthAdapter by extracting claims from the given context.

type UserAuthAdapterFunc

type UserAuthAdapterFunc func(*gin.Context) UserAuthAdapter

UserAuthAdapterFunc represents a function that accepts a Gin context and yields a UserAuthAdapter. This factory method produces a fresh instance of UserAuthAdapter for every incoming request.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL