groups

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2025 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MustHave

func MustHave(fn func(*gin.Context) (authenticated bool, groups Groups), rule Rule, more ...Rule) gin.HandlerFunc

MustHave returns a gin middleware that aborts the request with either http.StatusUnauthorized or http.StatusForbidden depending on whether there exists a user with the current session whose group membership satisfies the given rules.

The middleware must be given a function that can retrieve the user's group from the current request. The argument fn returns whether the session is authenticated and the groups associated with the user. If session is not authenticated then the request is aborted with http.StatusUnauthorized. If the session is authenticated but the groups do not satisfy the rules, the request is aborted with http.StatusForbidden. Otherwise, the request goes through.

Usage:

type MySession struct {
	SessionId string `dynamodbav:"sessionId,hashkey" tableName:"sessions"`
	User      *User `dynamodbav:"user,omitempty"`
}

type User struct {
	Sub    string `dynamodbav:"user"`
	Groups []string `dynamodbav:"groups,stringset"
}

r := gin.Default()
r.Use(sessions.Session[MySession]("sid"))
r.GET(
	"/protected/resource",
	groups.MustHave(func (c *gin.Context) (bool, groups.Groups) {
		var s *Session = sessions.Get[MySession](c)
		if s.User == nil {
			return false, nil
		}

		return true, s.User.Groups
	}, groups.OneOf("readResource", "writeResource"))

Types

type Groups

type Groups []string

Groups is a string list, preferably a string set.

func (Groups) Test

func (groups Groups) Test(rule Rule, more ...Rule) bool

Test verifies that the user's groups satisfy the membership rules.

Use AllOf and/or OneOf to describe how to authorise the user's groups.

Usage:

// user must be able to read both payments and inventory.
Groups([]string{...}).Test(AllOf("can_read_payment", "can_read_inventory"))

// user must be able to read both payments and inventory, but write permissions implies read as well.
Groups([]string{...}).Test(OneOf("can_read_payment", "can_write_payment"), OneOf("can_read_inventory", "can_write_inventory"))

type Rule

type Rule func(*rules)

Rule can only be either AllOf or OneOf.

func AllOf

func AllOf(group string, more ...string) Rule

AllOf adds a rule that the user must belong to all the groups specified here.

func OneOf

func OneOf(first, second string, more ...string) Rule

OneOf adds a rule that the user must belong to at least one of the groups specified here.

Jump to

Keyboard shortcuts

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