Casbin


Fiber를 위한 Casbin 미들웨어입니다.

주의: Go 1.18 이상이 필요합니다

Installation

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

여기에서 어댑터를 선택하세요

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

Signatures

casbin.New(config ...casbin.Config) *casbin.Middleware

Config

속성
타입
설명
기본값

ModelFilePath

string

모델 파일 경로

"./model.conf"

PolicyAdapter

persist.Adapter

정책을 위한 데이터베이스 어댑터

./policy.csv

Enforcer

*casbin.Enforcer

사용자 지정 casbin enforcer

Middleware generated enforcer using ModelFilePath & PolicyAdapter

Lookup

func(*fiber.Ctx) string

현재 주체를 찾기 위한 함수

""

Unauthorized

func(*fiber.Ctx) error

권한이 없는 응답을 위한 응답 본문

Unauthorized

Forbidden

func(*fiber.Ctx) error

금지된 응답을 위한 응답 본문

Forbidden

Examples

CustomPermission

package main

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

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

  authz := casbin.New(casbin.Config{
      ModelFilePath: "path/to/rbac_model.conf",
      PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
      Lookup: func(c *fiber.Ctx) string {
          // 인증된 사용자 주체 가져오기
      },
  })

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

  app.Listen(":8080")
}

RoutePermission

package main

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

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

  authz := casbin.New(casbin.Config{
      ModelFilePath: "path/to/rbac_model.conf",
      PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
      Lookup: func(c *fiber.Ctx) string {
          // 인증된 사용자 주체 가져오기
      },
  })

  // Method와 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/gofiber/contrib/casbin"
  _ "github.com/go-sql-driver/mysql"
  "github.com/casbin/xorm-adapter/v2"
)

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

  authz := casbin.New(casbin.Config{
      ModelFilePath: "path/to/rbac_model.conf", 
      PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
      Lookup: func(c *fiber.Ctx) string {
          // 인증된 사용자 주체 가져오기
      },
  })
  
  app.Put("/blog/:id",
    authz.RequiresRoles([]string{"admin"}),
    func(c *fiber.Ctx) error {
      // your handler  
    },
  )

  app.Listen(":8080")
}

Last updated