Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP:Write a business demo code use Hertz #75

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions bizdemo/hertz_casbin/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
*.o
*.a
*.so
_obj
_test
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.exe~
*.test
*.prof
*.rar
*.zip
*.gz
*.psd
*.bmd
*.cfg
*.pptx
*.log
*nohup.out
*settings.pyc
*.sublime-project
*.sublime-workspace
!.gitkeep
.DS_Store
/.idea
/.vscode
/output
*.local.yml
dumped_hertz_remote_config.json

3 changes: 3 additions & 0 deletions bizdemo/hertz_casbin/.hz
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Code generated by hz. DO NOT EDIT.

hz version: v0.5.1
61 changes: 61 additions & 0 deletions bizdemo/hertz_casbin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# hertz_casbin

## Introduce

A demo with `Hertz` and `Casbin`, this demo aims to understand the application of rbac.

Casbin is a powerful and efficient open-source access control library for Golang projects. It provides support for enforcing authorization based on various access control models.

- Use `thrift` IDL to define `HTTP` interface
- Use `hz` to generate code
- Use `casbin` to judgment authority
- Use `Gorm` and `MySQL`
- Use `JWT` to complete login and authentication


## casbin

Simplistic Example of role-based HTTP Authorization with [casbin](https://github.com/casbin/casbin) using [scs](https://github.com/alexedwards/scs) for session handling.

## IDL

This demo use `thrift` IDL to define `HTTP` interface. The specific interface define in [user.thrift](idl/casbin.thrift)

## Code generation tool

This demo use `hz` to generate code. The use of `hz` refers to [hz](https://www.cloudwego.io/docs/hertz/tutorials/toolkit/toolkit/)

The `hz` commands used can be found in [Makefile](Makefile)

## Binding and Validate

The use of binding and Validate refers
to [Binding and Validate](https://www.cloudwego.io/docs/hertz/tutorials/basic-feature/binding-and-validate/)

## Gorm

This demo use `Gorm` to operate `MySQL` and refers to [Gorm](https://gorm.io/)


## How to run

### Run MySQL

```bash
cd bizdemo/hertz_casbin && docker-compose up
```

### Generate MySQL table

Connect MySQL and execute [casbin.sql](biz/model/sql/casbin.sql)

### Run demo

```bash
cd bizdemo/hertz_casbin
go run .

```



24 changes: 24 additions & 0 deletions bizdemo/hertz_casbin/biz/dal/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dal

import "github.com/cloudwego/hertz-examples/bizdemo/hertz_casbin/biz/dal/mysql"

func Init() {
mysql.Init()

}
46 changes: 46 additions & 0 deletions bizdemo/hertz_casbin/biz/dal/mysql/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package mysql

import (
"github.com/cloudwego/hertz-examples/bizdemo/hertz_casbin/biz/model/casbin"
"github.com/cloudwego/hertz-examples/bizdemo/hertz_casbin/pkg/consts"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

var DB *gorm.DB

func Init() {
var err error
DB, err = gorm.Open(mysql.Open(consts.MysqlDSN), &gorm.Config{
SkipDefaultTransaction: true,
PrepareStmt: true,
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
panic(err)
}
m := DB.Migrator()
if m.HasTable(&casbin.User{}) {
return
}
if err = m.CreateTable(&casbin.User{}, &casbin.Role{}, &casbin.Permission{}, &casbin.UserRole{}, &casbin.PermissionRole{}); err != nil {
panic(err)
}
}
55 changes: 55 additions & 0 deletions bizdemo/hertz_casbin/biz/dal/mysql/permission.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package mysql

import "github.com/cloudwego/hertz-examples/bizdemo/hertz_casbin/biz/model/casbin"

func CreatePermission(permission *casbin.Permission) error {
return DB.Create(permission).Error
}

func BindPermissionRole(permissionRole *casbin.PermissionRole) error {
return DB.Create(permissionRole).Error
}

func QueryPermissionById(id int) (*casbin.Permission, error) {
var permission casbin.Permission
DB.First(&permission, id)
return &permission, nil
}

func QueryPermissionByV(v1 string, v2 string) (*casbin.Permission, error) {
var permission casbin.Permission
DB.Where("v1= ? AND v2 =?", v1, v2).First(&permission)
return &permission, nil
}

func QuerypermissionRoleByIds(pid, rid int) []casbin.PermissionRole {

var permissionRole []casbin.PermissionRole
tx := DB.Model(new(casbin.PermissionRole))
if pid != 0 {
tx.Where("pid= ?", pid)
}
if rid != 0 {
tx.Where("rid= ?", rid)
}

tx.Select("pid,rid,id").Find(&permissionRole)

return permissionRole
}
69 changes: 69 additions & 0 deletions bizdemo/hertz_casbin/biz/dal/mysql/role.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package mysql

import (
"github.com/cloudwego/hertz-examples/bizdemo/hertz_casbin/biz/model/casbin"
)

func CreateRole(role *casbin.Role) error {
return DB.Create(role).Error
}

func BindRole(userRole *casbin.UserRole) error {
return DB.Create(userRole).Error
}

func QueryRoleById(id int) (*casbin.Role, error) {
var role casbin.Role
DB.First(&role, id)
return &role, nil
}

func QueryRoleByName(name string) (*casbin.Role, error) {
var role casbin.Role
DB.Where("name= ?", name).First(&role)
return &role, nil
}

func QueryUserRoleByIds(uid, rid int) []casbin.UserRole {

var userRole []casbin.UserRole
tx := DB.Model(new(casbin.UserRole))
if uid != 0 {
tx.Where("uid= ?", uid)
}
if rid != 0 {
tx.Where("rid= ?", rid)
}

tx.Select("rid,uid,id").Find(&userRole)

return userRole
}

func QueryRolesByUid(uid int) []casbin.Role {

var userRole []casbin.Role
_ = DB.Model(new(casbin.UserRole)).
Joins("LEFT JOIN roles on roles.id=user_roles.rid ").
Select("roles.id,roles.name").
Where("user_roles.uid=?", uid).
Scan(&userRole)

return userRole
}
42 changes: 42 additions & 0 deletions bizdemo/hertz_casbin/biz/dal/mysql/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package mysql

import "github.com/cloudwego/hertz-examples/bizdemo/hertz_casbin/biz/model/casbin"

func CreateUser(user *casbin.User) error {
return DB.Create(user).Error

}

func QueryUser(username, password string) (*casbin.User, error) {
var user casbin.User
DB.Where("username=? AND password =? ", username, password).First(&user)
return &user, nil
}

func QueryUserByUsername(username string) (*casbin.User, error) {
var user casbin.User
DB.Where("username = ?", username).First(&user)
return &user, nil
}

func QueryUserById(id int) (*casbin.User, error) {
var user casbin.User
DB.First(&user, id)
return &user, nil
}
Loading