casbin

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2023 License: Apache-2.0 Imports: 8 Imported by: 0

README

Casbin (This is a community driven project)

Casbin is an authorization library that supports access control models like ACL, RBAC, ABAC.

This repo inspired by fiber-casbin and adapted to Hertz.

Install

go get github.com/hertz-contrib/casbin

Import

import "github.com/hertz-contrib/casbin"

Example

package main

import (
    "context"
    "log"
    
    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/app/server"
    "github.com/hertz-contrib/casbin"
    "github.com/hertz-contrib/sessions"
    "github.com/hertz-contrib/sessions/cookie"
)

func main() {
    h := server.Default()
    
    // Using sessions and casbin.
    store := cookie.NewStore([]byte("secret"))
    h.Use(sessions.New("session", store))
    auth, err := casbin.NewCasbinMiddleware("example/config/model.conf", "example/config/policy.csv", subjectFromSession)
    if err != nil {
        log.Fatal(err)
    }
    
    h.POST("/login", func(ctx context.Context, c *app.RequestContext) {
        // Verify username and password.
        // ...
    
        // Store current subject in session
        session := sessions.Default(c)
        session.Set("name", "alice")
        err := session.Save()
        if err != nil {
            log.Fatal(err)
        }
        c.String(200, "you login successfully")
    })
    
    h.GET("/book", auth.RequiresPermissions("book:read", casbin.WithLogic(casbin.AND)), func(ctx context.Context, c *app.RequestContext) {
        c.String(200, "you read the book successfully")
    })
    h.GET("/book", auth.RequiresPermissions("book:read book:write", casbin.WithLogic(casbin.AND)), func(ctx context.Context, c *app.RequestContext) {
        c.String(200, "you read the book failed")
    })
    h.GET("/book", auth.RequiresPermissions("book:read && book:write", casbin.WithLogic(casbin.CUSTOM)), func(ctx context.Context, c *app.RequestContext) {
        c.String(200, "you read the book failed")
    })
    
    h.POST("/book", auth.RequiresRoles("user", casbin.WithLogic(casbin.AND)), func(ctx context.Context, c *app.RequestContext) {
        c.String(200, "you posted a book successfully")
    })
    h.POST("/book", auth.RequiresRoles("user admin", casbin.WithLogic(casbin.AND)), func(ctx context.Context, c *app.RequestContext) {
        c.String(200, "you posted a book failed")
    })
    h.POST("/book", auth.RequiresRoles("user && admin", casbin.WithLogic(casbin.CUSTOM)), func(ctx context.Context, c *app.RequestContext) {
        c.String(200, "you posted a book failed")
    })
    
    h.Spin()
}

// subjectFromSession get subject from session.
func subjectFromSession(ctx context.Context, c *app.RequestContext) string {
    // Get subject from session.
    session := sessions.Default(c)
    if subject, ok := session.Get("name").(string); !ok {
        return ""
    } else {
        return subject
    }
}

Options

Option Default Description
Logic AND Logic is the logical operation (AND/OR/CUSTOM) used in permission checks in case multiple permissions or roles are specified.
PermissionParser PermissionParserWithSeparator(":") PermissionParserFunc is used for parsing the permission to extract object and action usually.
PermissionParserSeparator * PermissionParserSeparator is used for parsing the permission to extract object and action usually.
Unauthorized func(ctx context.Context, c *app.RequestContext) { c.AbortWithStatus(consts.StatusUnauthorized) } Unauthorized defines the response body for unauthorized responses.
Forbidden func(ctx context.Context, c *app.RequestContext) { c.AbortWithStatus(consts.StatusForbidden) } Forbidden defines the response body for forbidden responses.

Attention: when use CUSTOM in WithLogic, use WithPermissionParser Option is forbidden.

Documentation

Index

Constants

View Source
const (
	DefaultPermissionSeparator = ":"
)

Variables

View Source
var OptionsDefault = Options{
	Logic:               AND,
	PermissionParser:    PermissionParserWithSeparator(DefaultPermissionSeparator),
	PermissionSeparator: DefaultPermissionSeparator,
	Unauthorized: func(ctx context.Context, c *app.RequestContext) {
		c.AbortWithStatus(consts.StatusUnauthorized)
	},
	Forbidden: func(ctx context.Context, c *app.RequestContext) {
		c.AbortWithStatus(consts.StatusForbidden)
	},
}

Functions

This section is empty.

Types

type Logic

type Logic int

Logic is the logical operation (AND/OR) used in permission checks in case multiple permissions or roles are specified.

const (
	AND Logic = iota
	OR
	CUSTOM
)

type LookupHandler

type LookupHandler func(ctx context.Context, c *app.RequestContext) string

LookupHandler is used to look up current subject in runtime. If it can not find anything, just return an empty string.

type Middleware

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

func NewCasbinMiddleware

func NewCasbinMiddleware(modelFile string, adapter interface{}, lookup LookupHandler) (*Middleware, error)

NewCasbinMiddleware returns a new Middleware using Casbin's Enforcer internally.

modelFile is the file path to Casbin model file e.g. path/to/rbac_model.conf. adapter can be a file or a DB adapter. lookup is a function that looks up the current subject in runtime and returns an empty string if nothing found.

func NewCasbinMiddlewareFromEnforcer

func NewCasbinMiddlewareFromEnforcer(e casbin.IEnforcer, lookup LookupHandler) (*Middleware, error)

NewCasbinMiddlewareFromEnforcer creates from given Enforcer.

func (*Middleware) RequiresPermissions

func (m *Middleware) RequiresPermissions(expression string, opts ...Option) app.HandlerFunc

RequiresPermissions tries to find the current subject and determine if the subject has the required permissions according to predefined Casbin policies.

func (*Middleware) RequiresRoles

func (m *Middleware) RequiresRoles(expression string, opts ...Option) app.HandlerFunc

RequiresRoles tries to find the current subject and determine if the subject has the required roles according to predefined Casbin policies.

type Option

type Option struct {
	F func(o *Options)
}

Option is the only struct that can be used to set Options.

func WithForbidden

func WithForbidden(f app.HandlerFunc) Option

WithForbidden defines the response body for forbidden responses.

func WithLogic

func WithLogic(logic Logic) Option

WithLogic sets the logical operator used in permission or role checks.

func WithPermissionParser

func WithPermissionParser(pp PermissionParserFunc) Option

WithPermissionParser sets parsing the permission func. Attention: It is only enabled when logic is `AND` or `OR`

func WithPermissionParserSeparator

func WithPermissionParserSeparator(sep string) Option

WithPermissionParserSeparator sets permission parsing separator

func WithUnauthorized

func WithUnauthorized(u app.HandlerFunc) Option

WithUnauthorized defines the response body for unauthorized responses.

type Options

type Options struct {
	// Logic is the logical operation (AND/OR) used in permission checks
	// in case multiple permissions or roles are specified.
	// Optional. Default: AND
	Logic Logic

	// PermissionParserFunc is used for parsing the permission
	// to extract object and action usually
	// Optional. Default: PermissionParserWithSeparator(":")
	PermissionParser PermissionParserFunc
	// PermissionSeparator permission parsing separator
	PermissionSeparator string

	// Unauthorized defines the response body for unauthorized responses.
	// Optional. Default: func(ctx context.Context, c *app.RequestContext) {
	//		c.AbortWithStatus(consts.StatusUnauthorized)
	//	},
	Unauthorized app.HandlerFunc

	// Forbidden defines the response body for forbidden responses.
	// Optional. Default: func(ctx context.Context, c *app.RequestContext) {
	//		c.AbortWithStatus(consts.StatusForbidden)
	//	},
	Forbidden app.HandlerFunc
}

func NewOptions

func NewOptions(opts ...Option) *Options

func (*Options) Apply

func (o *Options) Apply(opts []Option)

Apply to apply options.

type PermissionParserFunc

type PermissionParserFunc func(str string) []string

PermissionParserFunc is used for parsing the permission to extract object and action usually

func PermissionParserWithSeparator

func PermissionParserWithSeparator(sep string) PermissionParserFunc

PermissionParserWithSeparator is a permission parser with separator.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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