casbinrest

package module
v1.0.6-0...-c34cab6 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2021 License: MIT Imports: 4 Imported by: 0

README

Casbin RESTful Adapter on Echo Web Framework

Casbin RESTful adapter for Casbin https://github.com/casbin/casbin

Build Status Codecov Go Report Card

Installation:

go get github.com/prongbang/casbinrest

Usage:

package main

import (
	"fmt"

	"github.com/casbin/casbin"
	"github.com/labstack/echo"
	"github.com/prongbang/casbinrest"
)

type redisDataSource struct {
}

func NewRedisDataSource() casbinrest.DataSource {
	return &redisDataSource{}
}

const mockAdminToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"

func (r *redisDataSource) GetRoleByToken(reqToken string) string {
	role := "anonymous"
	if reqToken == mockAdminToken {
		role = "admin"
	}
	return role
}

func main() {
	redisSource := NewRedisDataSource()
	ce := casbin.NewEnforcer("example/auth_model.conf", "example/policy.csv")
	
	e := echo.New()
	e.Use(casbinrest.Middleware(ce, redisSource))
	
	e.GET("/", func(c echo.Context) error {
		return c.JSON(http.StatusOK, "OK")
	})

	e.GET("/login", func(c echo.Context) error {
		return c.JSON(http.StatusOK, "OK")
	})
	
	e.Logger.Fatal(e.Start(":1323"))
}

Request:

curl -i -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" http://localhost:1323/login

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultConfig is the default CasbinAuth middleware config.
	DefaultConfig = Config{
		Skipper: middleware.DefaultSkipper,
	}
)

Functions

func Middleware

func Middleware(ce *casbin.Enforcer, sc DataSource) echo.MiddlewareFunc

Middleware returns a CasbinAuth middleware.

func MiddlewareWithConfig

func MiddlewareWithConfig(config Config) echo.MiddlewareFunc

MiddlewareWithConfig returns a CasbinAuth middleware with config.

Types

type Config

type Config struct {
	Skipper  middleware.Skipper
	Enforcer *casbin.Enforcer
	Source   DataSource
}

Config defines the config for CasbinAuth middleware.

func (*Config) CheckPermission

func (a *Config) CheckPermission(c echo.Context) (bool, error)

CheckPermission checks the role/path/method combination from the request.

func (*Config) GetRole

func (a *Config) GetRole(c echo.Context) string

GetRole gets the role name from the request.

type DataSource

type DataSource interface {
	GetRoleByToken(reqToken string) string
}

DataSource is the Authen from datasource

Jump to

Keyboard shortcuts

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