fibercasbin

package module
v2.31.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2022 License: MIT Imports: 6 Imported by: 1

README

Casbin

Casbin middleware for Fiber

Install

go get -u github.com/gofiber/fiber/v2
go get -u github.com/arsmn/fiber-casbin/v2

choose an adapter from here

go get -u github.com/casbin/xorm-adapter

Signature

fibercasbin.New(config ...fibercasbin.Config) *fibercasbin.CasbinMiddleware

Config

Property Type Description Default
ModelFilePath string Model file path "./model.conf"
PolicyAdapter persist.Adapter Database adapter for policies ./policy.csv
Enforcer *casbin.Enforcer Custom casbin enforcer Middleware generated enforcer using ModelFilePath & PolicyAdapter
Lookup func(*fiber.Ctx) string Look up for current subject ""
Unauthorized func(*fiber.Ctx) error Response body for unauthorized responses Unauthorized
Forbidden func(*fiber.Ctx) error Response body for forbidden responses Forbidden

Examples

CustomPermission

package main

import (
  "github.com/gofiber/fiber/v2"
  "github.com/arsmn/fiber-casbin/v2"
  _ "github.com/go-sql-driver/mysql"
  "github.com/casbin/xorm-adapter/v2"
)

func main() {
  app := fiber.New()

  authz := fibercasbin.New(fibercasbin.Config{
      ModelFilePath: "path/to/rbac_model.conf",
      PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
      Lookup: func(c *fiber.Ctx) string {
          // fetch authenticated user subject
      },
  })

  app.Post("/blog",
      authz.RequiresPermissions([]string{"blog:create"}, fibercasbin.WithValidationRule(fibercasbin.MatchAllRule)),
      func(c *fiber.Ctx) error {
        // your handler
      },
  )
  
  app.Delete("/blog/:id",
    authz.RequiresPermissions([]string{"blog:create", "blog:delete"}, fibercasbin.WithValidationRule(fibercasbin.AtLeastOneRule)),
    func(c *fiber.Ctx) error {
      // your handler
    },
  )

  app.Listen(":8080")
}

RoutePermission

package main

import (
  "github.com/gofiber/fiber/v2"
  "github.com/arsmn/fiber-casbin/v2"
  _ "github.com/go-sql-driver/mysql"
  "github.com/casbin/xorm-adapter/v2"
)

func main() {
  app := fiber.New()

  authz := fibercasbin.New(fibercasbin.Config{
      ModelFilePath: "path/to/rbac_model.conf",
      PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
      Lookup: func(c *fiber.Ctx) string {
          // fetch authenticated user subject
      },
  })

  // check permission with Method and Path
  app.Post("/blog",
    authz.RoutePermission(),
    func(c *fiber.Ctx) error {
      // your handler
    },
  )

  app.Listen(":8080")
}

RoleAuthorization

package main

import (
  "github.com/gofiber/fiber/v2"
  "github.com/arsmn/fiber-casbin/v2"
  _ "github.com/go-sql-driver/mysql"
  "github.com/casbin/xorm-adapter/v2"
)

func main() {
  app := fiber.New()

  authz := fibercasbin.New(fibercasbin.Config{
      ModelFilePath: "path/to/rbac_model.conf",
      PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
      Lookup: func(c *fiber.Ctx) string {
          // fetch authenticated user subject
      },
  })
  
  app.Put("/blog/:id",
    authz.RequiresRoles([]string{"admin"}),
    func(c *fiber.Ctx) error {
      // your handler
    },
  )

  app.Listen(":8080")
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ConfigDefault = Config{
	ModelFilePath: "./model.conf",
	PolicyAdapter: fileadapter.NewAdapter("./policy.csv"),
	Lookup:        func(c *fiber.Ctx) string { return "" },
	Unauthorized:  func(c *fiber.Ctx) error { return c.SendStatus(fiber.StatusUnauthorized) },
	Forbidden:     func(c *fiber.Ctx) error { return c.SendStatus(fiber.StatusForbidden) },
}
View Source
var OptionsDefault = Options{
	ValidationRule:   MatchAllRule,
	PermissionParser: PermissionParserWithSeperator(":"),
}

Functions

This section is empty.

Types

type CasbinMiddleware

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

CasbinMiddleware ...

func New

func New(config ...Config) *CasbinMiddleware

New creates an authorization middleware for use in Fiber

func (*CasbinMiddleware) RequiresPermissions

func (cm *CasbinMiddleware) RequiresPermissions(permissions []string, opts ...Option) fiber.Handler

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

func (*CasbinMiddleware) RequiresRoles

func (cm *CasbinMiddleware) RequiresRoles(roles []string, opts ...Option) fiber.Handler

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

func (*CasbinMiddleware) RoutePermission

func (cm *CasbinMiddleware) RoutePermission() fiber.Handler

RoutePermission tries to find the current subject and determine if the subject has the required permissions according to predefined Casbin policies. This method uses http Path and Method as object and action.

type Config

type Config struct {
	// ModelFilePath is path to model file for Casbin.
	// Optional. Default: "./model.conf".
	ModelFilePath string

	// PolicyAdapter is an interface for different persistent providers.
	// Optional. Default: fileadapter.NewAdapter("./policy.csv").
	PolicyAdapter persist.Adapter

	// Enforcer is an enforcer. If you want to use your own enforcer.
	// Optional. Default: nil
	Enforcer *casbin.Enforcer

	// Lookup is a function that is used to look up current subject.
	// An empty string is considered as unauthenticated user.
	// Optional. Default: func(c *fiber.Ctx) string { return "" }
	Lookup func(*fiber.Ctx) string

	// Unauthorized defines the response body for unauthorized responses.
	// Optional. Default: func(c *fiber.Ctx) error { return c.SendStatus(401) }
	Unauthorized fiber.Handler

	// Forbidden defines the response body for forbidden responses.
	// Optional. Default: func(c *fiber.Ctx) error { return c.SendStatus(403) }
	Forbidden fiber.Handler
}

Config holds the configuration for the middleware

type Option added in v2.24.0

type Option interface {
	// contains filtered or unexported methods
}

Option specifies casbin configuration options.

func WithPermissionParser added in v2.24.0

func WithPermissionParser(pp PermissionParserFunc) Option

func WithValidationRule added in v2.24.0

func WithValidationRule(vr ValidationRule) Option

type OptionFunc added in v2.24.0

type OptionFunc func(*Options)

type Options

type Options struct {
	ValidationRule   ValidationRule
	PermissionParser PermissionParserFunc
}

Options holds Options of middleware

type PermissionParserFunc

type PermissionParserFunc func(str string) []string

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

func PermissionParserWithSeperator

func PermissionParserWithSeperator(sep string) PermissionParserFunc

type ValidationRule added in v2.24.0

type ValidationRule int
const (
	MatchAllRule ValidationRule = iota
	AtLeastOneRule
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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