RBAC scaffolding based on Gin + Gorm+ Casbin + Wire

Overview

Gin Admin

基于 GIN + GORM + CASBIN + WIRE 实现的RBAC权限管理脚手架,目的是提供一套轻量的中后台开发框架,方便、快速的完成业务需求的开发。

ReportCard GoDoc License

特性

  • 遵循 RESTful API 设计规范 & 基于接口的编程规范
  • 基于 GIN 框架,提供了丰富的中间件支持(JWTAuth、CORS、RequestLogger、RequestRateLimiter、TraceID、CasbinEnforce、Recover、GZIP)
  • 基于 Casbin 的 RBAC 访问控制模型 -- 权限控制可以细粒度到按钮 & 接口
  • 基于 Gorm 的数据库存储
  • 基于 WIRE 的依赖注入 -- 依赖注入本身的作用是解决了各个模块间层级依赖繁琐的初始化过程
  • 基于 Logrus & Context 实现了日志输出,通过结合 Context 实现了统一的 TraceID/UserID 等关键字段的输出(同时支持日志钩子写入到Gorm)
  • 基于 JWT 的用户认证 -- 基于 JWT 的黑名单验证机制
  • 基于 Swaggo 自动生成 Swagger 文档 -- 独立于接口的 mock 实现
  • 基于 net/http/httptest 标准包实现了 API 的单元测试
  • 基于 go mod 的依赖管理(国内源可使用:https://goproxy.cn/)

依赖工具

go get -u github.com/cosmtrek/air
go get -u github.com/google/wire/cmd/wire
go get -u github.com/swaggo/swag/cmd/swag
  • air -- Live reload for Go apps
  • wire -- Compile-time Dependency Injection for Go
  • swag -- Automatically generate RESTful API documentation with Swagger 2.0 for Go.

依赖框架

  • Gin -- The fastest full-featured web framework for Go.
  • GORM -- The fantastic ORM library for Golang
  • Casbin -- An authorization library that supports access control models like ACL, RBAC, ABAC in Golang
  • Wire -- Compile-time Dependency Injection for Go

快速开始

也可以使用国内源:https://gitee.com/lyric/gin-admin

$ git clone https://github.com/LyricTian/gin-admin

$ cd gin-admin

# 使用AIR工具运行
$ air

# OR 基于Makefile运行
$ make start

# OR 使用go命令运行
$ go run cmd/gin-admin/main.go web -c ./configs/config.toml -m ./configs/model.conf --menu ./configs/menu.yaml

启动成功之后,可在浏览器中输入地址进行访问:http://127.0.0.1:10088/swagger/index.html

生成swagger文档

# 基于Makefile
make swagger

# OR 使用swag命令
swag init --parseDependency --generalInfo ./cmd/${APP}/main.go --output ./internal/app/swagger

重新生成依赖注入文件

# 基于Makefile
make wire

# OR 使用wire命令
wire gen ./internal/app

gin-admin-cli 工具使用

创建项目

gin-admin-cli new -d test-gin-admin -p test-gin-admin -m

快速生成业务模块

创建模板 task.yaml

name: Task
comment: 任务管理
fields:
  - name: Code
    type: string
    comment: 任务编号
    required: true
    binding_options: ""
    gorm_options: "size:50;index;"
  - name: Name
    type: string
    comment: 任务名称
    required: true
    binding_options: ""
    gorm_options: "size:50;index;"
  - name: Memo
    type: string
    comment: 任务备注
    required: false
    binding_options: ""
    gorm_options: "size:1024;"

执行生成命令并运行

cd test-gin-admin
gin-admin-cli g -d . -p test-gin-admin -f ./task.yaml

# 生成 swagger
make swagger

# 生成依赖项
make wire

# 运行服务
make start

前端工程

Questions

OSX 下基于 sqlite3 运行出现:'stdlib.h' file not found

export CGO_ENABLED=1; export CC=gcc; go get -v -x github.com/mattn/go-sqlite3

互动交流

wechat qqgroup

MIT License

Copyright (c) 2021 Lyric
Issues
  • 编译运行时候提示资源不存在?

    编译运行时候提示资源不存在?

    $ ./server -c ../../config/config.toml -m ../../config/model.conf 开始运行服务,服务版本号:1.2.0-dev INFO[0000] 服务已运行在[test]模式下,运行版本:1.2.0-dev,进程号:8878 span_function= span_id=61b97f94-b06d-418e-8f1f-5882e8851c0e span_title= started_at="2019-01-16 10:47:40.631298875 +0800 CST m=+0.105783090" trace_id=cdb4c6b1-f010-4ca3-8d17-d721afe353ba user_id= INFO[0000] HTTP服务开始启动,监听地址为:[127.0.0.1:8086] span_function= span_id=1b38453f-12c3-43cb-bd02-6d63b484a4cf span_title= started_at="2019-01-16 10:47:40.63526605 +0800 CST m=+0.109750342" trace_id=cdb4c6b1-f010-4ca3-8d17-d721afe353ba user_id= WARN[0009] [请求错误] 资源不存在

    opened by pt00ls 5
  • Cannot get latest version: module contains a go.mod file, so module path should be github.com/LyricTian/gin-admin/v5

    Cannot get latest version: module contains a go.mod file, so module path should be github.com/LyricTian/gin-admin/v5

    Background

    The github.com/LyricTian/gin-admin uses Go modules and the current release version is v5. And it’s module path is "github.com/LyricTian/gin-admin", instead of "github.com/LyricTian/gin-admin/v5". It must comply with the specification of "Releasing Modules for v2 or higher" available in the Modules documentation. Quoting the specification:

    A package that has opted in to modules must include the major version in the import path to import any v2+ modules To preserve import compatibility, the go command requires that modules with major version v2 or later use a module path with that major version as the final element. For example, version v2.0.0 of example.com/m must instead use module path example.com/m/v2. https://github.com/golang/go/wiki/Modules#releasing-modules-v2-or-higher

    Steps to Reproduce

    GO111MODULE=on, run go get targeting any version >= v2.0.0 of the LyricTian/gin-admin:

    $ go get github.com/LyricTian/[email protected]
    go: finding github.com/LyricTian/gin-admin v5.2.3
    go: finding github.com/LyricTian/gin-admin v5.2.3
    go get github.com/LyricTian/[email protected]: github.com/LyricTian/[email protected]: invalid version: module contains a go.mod file, so major version must be compatible: should be v0 or v1, not v5
    

    run go get github.com/LyricTian/gin-admin, the version will stuck in v1.1.0:

    $go get github.com/LyricTian/gin-admin
    go: downloading github.com/LyricTian/gin-admin v1.1.0
    go: github.com/LyricTian/gin-admin upgrade => v1.1.0
    

    SO anyone using Go modules will not be able to easily use any newer version of LyricTian/gin-admin.

    Solution

    1. Kill the go.mod files, rolling back to GOPATH.

    This would push them back to not being managed by Go modules (instead of incorrectly using Go modules). Ensure compatibility for downstream module-aware projects and module-unaware projects projects

    I see these dependencies in your go.mod file, which need modle awareness. So you'd better not use third-party tools(such as: Dep, glide, govendor…).

    github.com/casbin/casbin/v2 v2.4.1
    github.com/urfave/cli/v2
    

    You also need to update the import path to:

    import github.com/casbin/casbin/…
    import github.com/urfave/cli/…
    

    2. Fix module path to strictly follow SIV rules.

    Patch the go.mod file to declare the module path as github.com/LyricTian/gin-admin/v5 as per the specs. And adjust all internal imports. The downstream projects might be negatively affected in their building if they are module-unaware (Go versions older than 1.9.7 and 1.10.3; Or use third-party dependency management tools, such as: Dep, glide,govendor…).

    [*] You can see who will be affected here: [1 module-unaware user, i.e., BrettCao/gox ] https://github.com/BrettCao/gox/search?q=github.com%2FLyricTian%2Fgin-admin&unscoped_q=github.com%2FLyricTian%2Fgin-admin

    If you don't want to break the above repos. This method can provides better backwards-compatibility. Release a v2 or higher module through the major subdirectory strategy: Create a new v5 subdirectory (github.com/LyricTian/gin-admin/v5) and place a new go.mod file in that subdirectory. The module path must end with /v5. Copy or move the code into the v5 subdirectory. Update import statements within the module to also use /v5 (import "github.com/LyricTian/gin-admin/v5/…"). Tag the release with v5.x.y.

    3. Suggest your downstream module users use hash instead of a version tag.

    If the standard rule of go modules conflicts with your development mode. Or not intended to be used as a library and does not make any guarantees about the API. So you can’t comply with the specification of "Releasing Modules for v2 or higher" available in the Modules documentation. Regardless, since it's against one of the design choices of Go, it'll be a bit of a hack. Instead of go get github.com/LyricTian/[email protected], module users need to use this following way to get the LyricTian/gin-admin: (1) Search for the tag you want (in browser) (2) Get the commit hash for the tag you want (3) Run go get github.com/LyricTian/[email protected] (4) Edit the go.mod file to put a comment about which version you actually used This will make it difficult for module users to get and upgrade LyricTian/gin-admin.

    [*] You can see who will be affected here: [8 module users, e.g., ForTheOne/rbac, fdgo/prone, hblcok/go-micro-gateway] https://github.com/search?q=github.com%2FLyricTian%2Fgin-admin+extension%3Amod&type=Code&ref=advsearch&l=&l=

    Summary

    You can make a choice to fix DM issues by balancing your own development schedules/mode against the affects on the downstream projects.

    For this issue, Solution 2 can maximize your benefits and with minimal impacts to your downstream projects the ecosystem.

    References

    • https://github.com/golang/go/wiki/Modules#semantic-import-versioning
    • https://golang.org/cmd/go/#hdr-Module_compatibility_and_semantic_versioning
    • https://github.com/golang/go/wiki/Modules#releasing-modules-v2-or-higher
    opened by KateGo520 4
  • GOCACHE is not defined 出现这个错误

    GOCACHE is not defined 出现这个错误

    ` $ make start

    build cache is required, but could not be located: GOCACHE is not defined and %L ocalAppData% is not defined

    make: *** [Makefile:15: start] Error 1 ` 执行Makefile出错,但是我看了,这个编译代码,怎么会提示这个错误呢

    opened by lchjczw 4
  • v2.0.0版本功能列表

    v2.0.0版本功能列表

    • 重构服务端代码,实现业务逻辑和存储完全分离,提供统一的事务处理上下文和完整的日志跟踪
    • 加入gorm存储层的支持
    • 加入日志管理功能,支持日志查询及清理
    • 加入接口管理功能,支持服务端动态注入
    • 加入查询个人信息及修改个人密码的功能
    • 菜单管理支持以选择接口的方式批量增加资源
    • 引入JWT认证的支持,提供参数配置,支持session与jwt
    • 引入Swagger的支持,可提供一整套完整的接口文档
    • 引入CORS中间件,可作为参数项配置,支持跨域
    • 引入静态文件服务中间件,可作为命令行参数项,提供静态文件服务
    • 引入请求频次限制中间件,支持GET/POST的请求频次限制,可接入memory/redis
    • 提供HTTP优雅重启的支持
    • 用户登录增加图形验证码的支持,支持memory/redis存储
    opened by LyricTian 4
  • Provide English version (UI, README)

    Provide English version (UI, README)

    As you may know, Casbin have users from different countries. Most of them use English. I think it will be better for them to use this project if it provides English UI and documentation.

    opened by hsluoyz 3
  • Why use Ant Design instead of Vue or React?

    Why use Ant Design instead of Vue or React?

    I think Vue or React is more popular as a front-end framework than Ant Design. The users of your project will enlarge if you use those popular frameworks.

    opened by hsluoyz 3
  • ginplus.go line35 冗余代码

    ginplus.go line35 冗余代码

    ginplus.go line35 parent = logger.NewTraceIDContext(parent, GetTraceID(c)) 中的 GetTraceID(c)这次调用为冗余操作

    func NewContext(c *gin.Context) context.Context {
    	parent := context.Background()
    
    	if v := GetTraceID(c); v != "" {
    		parent = icontext.NewTraceID(parent, v)
    		parent = logger.NewTraceIDContext(parent, GetTraceID(c))
    	}
    
    	if v := GetUserID(c); v != "" {
    		parent = icontext.NewUserID(parent, v)
    		parent = logger.NewUserIDContext(parent, v)
    	}
    
    	return parent
    }
    

    首先感谢作者开源;另外,想请教下为什么这里要这么多层ctx(在只有traceID和userID且均为已知的情况下)?

    opened by pwli0755 2
  • github.com/LyricTian/captcha

    github.com/LyricTian/captcha

    您好,在看您的代码的时候发现您仓库中github.com/LyricTian/captcha 这个代码和您vendor中的github.com/LyricTian/captcha 并不是一致的,可以更改成一致的么,还是说出于其他考虑没有更改,我这边直接用的go module 做的包管理,所以直接是go get github.com/LyricTian/captcha 但是包里是缺少redis_options.go 文件的

    opened by pythonsite 2
  • go build -o server报错

    go build -o server报错

    go build -o server

    github.com/LyricTian/gin-admin/src/web/router

    ../../src/web/router/r_mw_recover.go:29:17: too many arguments in call to logger.System have (string, string) want ("context".Context) ../../src/web/router/r_mw_recover.go:36:5: ctx.Next undefined (type *"github.com/LyricTian/gin-admin/src/web/context".Context has no field or method Next)

    opened by bencen 2
  • user role map转换问题

    user role map转换问题

    描述: // ToMap 转换为map func (a UserRoles) ToMap() map[string]*UserRole { m := make(map[string]*UserRole) for _, item := range a { m[item.RoleID] = item } return m } 我理解的是一个角色ID对应一条数据userrole,如果一个用户多个角色,同时一个角色也能赋值给多个用户,那么roleID不是唯一的。。。。是否有问题?

    opened by lihong12500 1
  • fix auth pkg degraded

    fix auth pkg degraded

    我修改了以下内容

    • https://github.com/LyricTian/gin-admin/pull/80 这个提交应是错误的,store应只保存Blacklisting JWT,auth的测试代码也发生了错误
    === RUN   TestAuth
        TestAuth: auth_test.go:26: 
                    Error Trace:    auth_test.go:26
                    Error:          Expected nil, but got: &errors.errorString{s:"invalid token"}
                    Test:           TestAuth
        TestAuth: auth_test.go:27: 
                    Error Trace:    auth_test.go:27
                    Error:          Not equal: 
                                    expected: "test"
                                    actual  : ""
                                    
                                    Diff:
                                    --- Expected
                                    +++ Actual
                                    @@ -1 +1 @@
                                    -test
                                    +
                    Test:           TestAuth
        TestAuth: auth_test.go:33: 
                    Error Trace:    auth_test.go:33
                    Error:          Expected value not to be nil.
                    Test:           TestAuth
        TestAuth: auth_test.go:34: 
                    Error Trace:    auth_test.go:34
                    Error:          An error is expected but got nil.
                    Test:           TestAuth
        TestAuth: auth_test.go:35: 
                    Error Trace:    auth_test.go:35
                    Error:          Should be empty, but was test
                    Test:           TestAuth
    
    • go test测试了所有的go pkg
    opened by linzhengen 1
  • 集成OpenTelemetry,增加Jaeger Trace

    集成OpenTelemetry,增加Jaeger Trace

    集成Opentelemetry,把 Trace中间件改为OpenTelemetry Trace,使用Jaeger作为 exporter, 同时把 Jaeger 的 trace id传给logger,以打通logger和jaeger的trace id 后续将增加Prometheus中间件作为 Metrics exporter

    目前OpenTelemetry HTTP Handler还有点问题, 无法集成Prometheus

    opened by drinks5 0
Releases(v8.1.0)
Owner
Lyric
Stay hungry,stay foolish.
Lyric
Go + Vue开发的管理系统脚手架, 前后端分离, 仅包含项目开发的必需部分, 基于角色的访问控制(RBAC), 分包合理, 精简易于扩展。 后端Go包含了gin、 gorm、 jwt和casbin等的使用, 前端Vue基于vue-element-admin开发

go-web-mini Go + Vue开发的管理系统脚手架, 前后端分离, 仅包含项目开发的必需部分, 基于角色的访问控制(RBAC), 分包合理, 精简易于扩展。 后端Go包含了gin、 gorm、 jwt和casbin等的使用, 前端Vue基于vue-element-admin开发: http

gnimli 41 May 10, 2022
Another casbin implementation in golang

casbin Another casbin implementation in golang. Diffrent with the official casbin implementation Use google Common Expression Language as the matcher

null 1 Jan 25, 2022
goRBAC provides a lightweight role-based access control (RBAC) implementation in Golang.

goRBAC goRBAC provides a lightweight role-based access control implementation in Golang. For the purposes of this package: * an identity has one or mo

Xing 1.3k May 18, 2022
Role Based Access Control (RBAC) with database persistence

Authority Role Based Access Control (RBAC) Go package with database persistence Install First get authority go get github.com/harranali/authority Next

null 218 May 2, 2022
Generate K8s RBAC policies based on e2e test runs

rbac-audit Have you ever wondered whether your controller actually needs all the permissions it has granted to it? Wonder no more! This repo contains

Jason Hall 28 Aug 2, 2021
A single sign-on solution based on go-oauth2 / oauth2 and gin-gonic/gin

A single sign-on solution based on go-oauth2 / oauth2 and gin-gonic/gin

yinhuanyi 1 Nov 17, 2021
Account-jwt-go - Simple JWT api with go, gorm, gin

Account JWT on Go Go, gorm, Gin web framework 를 활용하여 만든 간단한 JWT API 입니다. Dajngo의

Deagwon Bu 1 Apr 14, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Golang

Casbin News: still worry about how to write the correct Casbin policy? Casbin online editor is coming to help! Try it at: https://casbin.org/editor/ C

Casbin 11.9k May 13, 2022
Minimalistic RBAC package for Go applications

RBAC Overview RBAC is a package that makes it easy to implement Role Based Access Control (RBAC) models in Go applications. Download To download this

Zack Patrick 95 Apr 22, 2022
YSHOP-GO基于当前流行技术组合的前后端RBAC管理系统:Go1.15.x+Beego2.x+Jwt+Redis+Mysql8+Vue 的前后端分离系统,权限控制采用 RBAC,支持数据字典与数据权限管理,支持动态路由等

YSHOP-GO 后台管理系统 项目简介 YSHOP-GO基于当前流行技术组合的前后端RBAC管理系统:Go1.15.x+Beego2.x+Jwt+Redis+Mysql8+Vue 的前后端分离系统,权限控制采用 RBAC,支持数据字典与数据权限管理,支持动态路由等 体验地址: https://go

null 94 May 10, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Golang

Casbin News: still worry about how to write the correct Casbin policy? Casbin online editor is coming to help! Try it at: https://casbin.org/editor/ C

Casbin 11.9k May 11, 2022
ACL, RBAC, ABAC authorization middleware for KubeSphere

casbin-kubesphere-auth Casbin-kubesphere-auth is a plugin which apply several security authentication check on kubesphere via casbin. This plugin supp

Casbin 3 Nov 5, 2021
Incomplete CRUD/RBAC service meant to be a practice for Go

Incomplete CRUD / RBAC Service in Go The repository name means nothing. But your task is to complete this repository on your own to be a functional CR

Teknologi Umum 5 Nov 9, 2021
A practical RBAC implementation

RBAC This project contains a practical RBAC implementation by Golang. It's actually a demo now. With in-memory storage, no database or file storage ye

Max Xu 0 Dec 1, 2021
Golang based User creation and Management application. GORM, Fiber, JWT

User Creation and Management app (BACK-END) Auth Features: Create Clients (regular password + 6 one-time passwords + (optional) QR code and Secret for

Artūras 4 Apr 25, 2022
OAuth 2.0 middleware service for chi (ported from gin by community member)

oauth middleware OAuth 2.0 Authorization Server & Authorization Middleware for go-chi This library was ported to go-chi from https://github.com/maxzer

go-chi 12 Apr 1, 2022
jwt package for gin go applications

gin-jwt jwt package for gin go applications Usage Download using go module: go get github.com/ennaque/gin-jwt Import it in your code: import gwt "gith

Igor Volkov 2 Apr 21, 2022
Golang with JWT, Go Gin and MongoDB

User authentication in Golang with JWT, Go Gin and MongoDB Golang backend application that uses JWT tokens for users Locally Up Setup your .env file,

Al Mamun Khan 8 May 1, 2022
Go (Golang) JWTAuth with Gin Framework

go-auth-server Go (Golang) JWTAuth with Gin Framework 1. Project Description JWT authentication Next tutorial is building secret manager 2. Run with D

Tony Aizize 0 Nov 14, 2021