Skip to content

Commit

Permalink
调整角色ID为uint格式,增加embed打包,更改日志格式。 (flipped-aurora#1144)
Browse files Browse the repository at this point in the history
* feature: 根据 flipped-aurora#377 pr进行修改embed, 打包静态文件夹与配置文件

* 修改角色id为uint

* 修改日志格式

Co-authored-by: SliverHorn <[email protected]>
Co-authored-by: cg81344 <[email protected]>
  • Loading branch information
3 people authored Jun 29, 2022
1 parent 78e6271 commit 68317c1
Show file tree
Hide file tree
Showing 30 changed files with 223 additions and 76 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,5 @@ yarn-error.log*
/server/latest_log

*.iml
web/.pnpm-debug.log
web/pnpm-lock.yaml
46 changes: 44 additions & 2 deletions server/core/internal/zap.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package internal

import (
"bytes"
"fmt"
"github.com/flipped-aurora/gin-vue-admin/server/global"
"go.uber.org/zap"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
"runtime"
"strings"
"time"
)

Expand Down Expand Up @@ -35,7 +39,7 @@ func (z *_zap) GetEncoderConfig() zapcore.EncoderConfig {
EncodeLevel: global.GVA_CONFIG.Zap.ZapEncodeLevel(),
EncodeTime: z.CustomTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.FullCallerEncoder,
EncodeCaller: CallerEncoder,
}
}

Expand All @@ -48,7 +52,7 @@ func (z *_zap) GetEncoderCore(l zapcore.Level, level zap.LevelEnablerFunc) zapco
return nil
}

return zapcore.NewCore(z.GetEncoder(), writer, level)
return zapcore.NewCore(&EscapeSeqJSONEncoder{z.GetEncoder()}, writer, level)
}

// CustomTimeEncoder 自定义日志输出时间格式
Expand Down Expand Up @@ -105,3 +109,41 @@ func (z *_zap) GetLevelPriority(level zapcore.Level) zap.LevelEnablerFunc {
}
}
}

// FuncName 返回调用本函数的函数名称
// pc runtime.Caller 返回的第一个值
func FuncName(pc uintptr) string {
funcName := runtime.FuncForPC(pc).Name()
sFuncName := strings.Split(funcName, ".")
return sFuncName[len(sFuncName)-1]
}

// CallerEncoder serializes a caller in package/file:funcname:line format
func CallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
shortCaller := caller.TrimmedPath()
shortCallerSplited := strings.Split(shortCaller, ":")
funcName := FuncName(caller.PC)
result := shortCallerSplited[0] + ":" + funcName + ":" + shortCallerSplited[1]
enc.AppendString(result)
}

type EscapeSeqJSONEncoder struct {
zapcore.Encoder
}

// EncodeEntry 将方法zap.error中的errorVerbose的堆栈换行符修改
func (enc *EscapeSeqJSONEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
b, err := enc.Encoder.EncodeEntry(entry, fields)
if err != nil {
return nil, err
}
newb := buffer.NewPool().Get()

b1 := bytes.Replace(b.Bytes(), []byte("\\n"), []byte("\n"), -1)
b2 := bytes.Replace(b1, []byte("\\t"), []byte("\t"), -1)
_, err = newb.Write(b2)
if err != nil {
return nil, err
}
return newb, nil
}
100 changes: 100 additions & 0 deletions server/embed.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package main

import (
"embed"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
)

var (
//go:embed resource
//go:embed config.yaml
//go:embed config.docker.yaml
resource embed.FS
)

var Embed = new(_embed)

type _embed struct{}

// RestoreFolder
// Author [SliverHorn](https://github.com/SliverHorn)
// Author [WangLeonard](https://github.com/WangLeonard)
func (e *_embed) RestoreFolder(dir string) {
entries, err := resource.ReadDir(dir)
if err != nil {
fmt.Println("[embed restore resource file]: err:", err)
return
}
for i := 0; i < len(entries); i++ {
if entries[i].IsDir() {
e.RestoreFile(filepath.Join(dir, entries[i].Name()), entries[i])
continue
}
e.RestoreFile(entries[i].Name(), entries[i])
}
}

// RestoreFile
// Author [SliverHorn](https://github.com/SliverHorn)
// Author [WangLeonard](https://github.com/WangLeonard)
func (e *_embed) RestoreFile(path string, entry fs.DirEntry) {
_, err := os.Stat(path)
if entry.IsDir() { // 文件夹
if os.IsNotExist(err) { // 判断 path 变量的文件夹存在, 不存在则创建文件夹
fmt.Printf("[embed restore mkdir] dir:%s\n", path)
err = os.Mkdir(path, os.ModePerm) // 创建文件夹, 权限为 os.ModePerm 可自行修改
if err != nil {
fmt.Printf("[embed restore mkdir] err:%v\n", err)
return
}
}
var entries []fs.DirEntry
entries, err = resource.ReadDir(path) // 读取文件夹的文件和文件夹数据
if err != nil {
return
}
for i := 0; i < len(entries); i++ {
_, err = os.Stat(entries[i].Name()) // 获取子文件夹的信息
dirPath := filepath.Join(path, entries[i].Name())
if os.IsNotExist(err) && entries[i].IsDir() { // 判断子文件夹是否存在, 这里有可能是文件,所以要加上是否为文件夹
fmt.Println("[embed restore mkdir] dir:", dirPath)
err = os.Mkdir(dirPath, os.ModePerm) // 创建文件夹, 权限为 os.ModePerm 可自行修改
if err != nil {
fmt.Println("[embed restore mkdir] err:", err)
return
}
}
e.RestoreFile(dirPath, entries[i])
}
}

if os.IsNotExist(err) && !entry.IsDir() { // 文件
var src fs.File
src, err = resource.Open(path) // 根据path从embed的到文件数据
if err != nil {
fmt.Println("[embed restore resource open file] open embed file failed, err:", err)
return
}
var dst *os.File
dst, err = os.Create(path) // 创建本地文件的 writer
if err != nil {
fmt.Println("[embed restore os create file] write err:", err)
return
}
_, err = io.Copy(dst, src) // 把embed的数据复制到本地
if err != nil {
fmt.Println("[embed restore io copy file] writer file failed, err:", err)
return
}
defer func() { // 关闭文件流
_ = src.Close()
_ = dst.Close()
}()
return
}
fmt.Println("[embed restore resource file] file exist, path:", path)
}
1 change: 1 addition & 0 deletions server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
// @name x-token
// @BasePath /
func main() {
Embed.RestoreFolder(".")
global.GVA_VP = core.Viper() // 初始化Viper
global.GVA_LOG = core.Zap() // 初始化zap日志库
zap.ReplaceGlobals(global.GVA_LOG)
Expand Down
6 changes: 3 additions & 3 deletions server/middleware/casbin_rbac.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/flipped-aurora/gin-vue-admin/server/service"
"github.com/flipped-aurora/gin-vue-admin/server/utils"
"github.com/gin-gonic/gin"
"strconv"
)

var casbinService = service.ServiceGroupApp.SystemServiceGroup.CasbinService
Expand All @@ -19,9 +20,8 @@ func CasbinHandler() gin.HandlerFunc {
// 获取请求方法
act := c.Request.Method
// 获取用户的角色
sub := waitUse.AuthorityId
e := casbinService.Casbin()
// 判断策略中是否存在
sub := strconv.Itoa(int(waitUse.AuthorityId))
e := casbinService.Casbin() // 判断策略中是否存在
success, _ := e.Enforce(sub, obj, act)
if global.GVA_CONFIG.System.Env == "develop" || success {
c.Next()
Expand Down
6 changes: 3 additions & 3 deletions server/model/common/request/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package request

// PageInfo Paging common input parameter structure
type PageInfo struct {
Page int `json:"page" form:"page"` // 页码
PageSize int `json:"pageSize" form:"pageSize"` // 每页大小
Page int `json:"page" form:"page"` // 页码
PageSize int `json:"pageSize" form:"pageSize"` // 每页大小
Keyword string `json:"keyword" form:"keyword"` //关键字
}

Expand All @@ -22,7 +22,7 @@ type IdsReq struct {

// GetAuthorityId Get role by id structure
type GetAuthorityId struct {
AuthorityId string `json:"authorityId" form:"authorityId"` // 角色ID
AuthorityId uint `json:"authorityId" form:"authorityId"` // 角色ID
}

type Empty struct{}
2 changes: 1 addition & 1 deletion server/model/example/exa_customer.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ type ExaCustomer struct {
CustomerName string `json:"customerName" form:"customerName" gorm:"comment:客户名"` // 客户名
CustomerPhoneData string `json:"customerPhoneData" form:"customerPhoneData" gorm:"comment:客户手机号"` // 客户手机号
SysUserID uint `json:"sysUserId" form:"sysUserId" gorm:"comment:管理ID"` // 管理ID
SysUserAuthorityID string `json:"sysUserAuthorityID" form:"sysUserAuthorityID" gorm:"comment:管理角色ID"` // 管理角色ID
SysUserAuthorityID uint `json:"sysUserAuthorityID" form:"sysUserAuthorityID" gorm:"comment:管理角色ID"` // 管理角色ID
SysUser system.SysUser `json:"sysUser" form:"sysUser" gorm:"comment:管理详情"` // 管理详情
}
2 changes: 1 addition & 1 deletion server/model/system/request/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ type BaseClaims struct {
ID uint
Username string
NickName string
AuthorityId string
AuthorityId uint
}
2 changes: 1 addition & 1 deletion server/model/system/request/sys_authority_btn.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ package request

type SysAuthorityBtnReq struct {
MenuID uint `json:"menuID"`
AuthorityId string `json:"authorityId"`
AuthorityId uint `json:"authorityId"`
Selected []uint `json:"selected"`
}
2 changes: 1 addition & 1 deletion server/model/system/request/sys_casbin.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ type CasbinInfo struct {

// Casbin structure for input parameters
type CasbinInReceive struct {
AuthorityId string `json:"authorityId"` // 权限id
AuthorityId uint `json:"authorityId"` // 权限id
CasbinInfos []CasbinInfo `json:"casbinInfos"`
}

Expand Down
2 changes: 1 addition & 1 deletion server/model/system/request/sys_menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
// Add menu authority info structure
type AddMenuAuthorityInfo struct {
Menus []system.SysBaseMenu `json:"menus"`
AuthorityId string `json:"authorityId"` // 角色ID
AuthorityId uint `json:"authorityId"` // 角色ID
}

func DefaultMenu() []system.SysBaseMenu {
Expand Down
20 changes: 10 additions & 10 deletions server/model/system/request/sys_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import model "github.com/flipped-aurora/gin-vue-admin/server/model/system"

// User register structure
type Register struct {
Username string `json:"userName"`
Password string `json:"passWord"`
NickName string `json:"nickName" gorm:"default:'QMPlusUser'"`
HeaderImg string `json:"headerImg" gorm:"default:'https://qmplusimg.henrongyi.top/gva_header.jpg'"`
AuthorityId string `json:"authorityId" gorm:"default:888"`
Enable int `json:"enable"`
AuthorityIds []string `json:"authorityIds"`
Username string `json:"userName"`
Password string `json:"passWord"`
NickName string `json:"nickName" gorm:"default:'QMPlusUser'"`
HeaderImg string `json:"headerImg" gorm:"default:'https://qmplusimg.henrongyi.top/gva_header.jpg'"`
AuthorityId uint `json:"authorityId" gorm:"default:888"`
Enable int `json:"enable"`
AuthorityIds []uint `json:"authorityIds"`
}

// User login structure
Expand All @@ -30,20 +30,20 @@ type ChangePasswordStruct struct {

// Modify user's auth structure
type SetUserAuth struct {
AuthorityId string `json:"authorityId"` // 角色ID
AuthorityId uint `json:"authorityId"` // 角色ID
}

// Modify user's auth structure
type SetUserAuthorities struct {
ID uint
AuthorityIds []string `json:"authorityIds"` // 角色ID
AuthorityIds []uint `json:"authorityIds"` // 角色ID
}

type ChangeUserInfo struct {
ID uint `gorm:"primarykey"` // 主键ID
NickName string `json:"nickName" gorm:"default:系统用户;comment:用户昵称"` // 用户昵称
Phone string `json:"phone" gorm:"comment:用户手机号"` // 用户角色ID
AuthorityIds []string `json:"authorityIds" gorm:"-"` // 角色ID
AuthorityIds []uint `json:"authorityIds" gorm:"-"` // 角色ID
Email string `json:"email" gorm:"comment:用户邮箱"` // 用户邮箱
HeaderImg string `json:"headerImg" gorm:"default:https://qmplusimg.henrongyi.top/gva_header.jpg;comment:用户头像"` // 用户头像
SideMode string `json:"sideMode" gorm:"comment:用户侧边主题"` // 用户侧边主题
Expand Down
2 changes: 1 addition & 1 deletion server/model/system/response/sys_authority.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ type SysAuthorityResponse struct {

type SysAuthorityCopyResponse struct {
Authority system.SysAuthority `json:"authority"`
OldAuthorityId string `json:"oldAuthorityId"` // 旧角色ID
OldAuthorityId uint `json:"oldAuthorityId"` // 旧角色ID
}
4 changes: 2 additions & 2 deletions server/model/system/sys_authority.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ type SysAuthority struct {
CreatedAt time.Time // 创建时间
UpdatedAt time.Time // 更新时间
DeletedAt *time.Time `sql:"index"`
AuthorityId string `json:"authorityId" gorm:"not null;unique;primary_key;comment:角色ID;size:90"` // 角色ID
AuthorityId uint `json:"authorityId" gorm:"not null;unique;primary_key;comment:角色ID;size:90"` // 角色ID
AuthorityName string `json:"authorityName" gorm:"comment:角色名"` // 角色名
ParentId string `json:"parentId" gorm:"comment:父角色ID"` // 父角色ID
ParentId uint `json:"parentId" gorm:"comment:父角色ID"` // 父角色ID
DataAuthorityId []*SysAuthority `json:"dataAuthorityId" gorm:"many2many:sys_data_authority_id;"`
Children []SysAuthority `json:"children" gorm:"-"`
SysBaseMenus []SysBaseMenu `json:"menus" gorm:"many2many:sys_authority_menus;"`
Expand Down
2 changes: 1 addition & 1 deletion server/model/system/sys_authority_btn.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package system

type SysAuthorityBtn struct {
AuthorityId string `gorm:"comment:角色ID"`
AuthorityId uint `gorm:"comment:角色ID"`
SysMenuID uint `gorm:"comment:菜单ID"`
SysBaseMenuBtnID uint `gorm:"comment:菜单按钮ID"`
SysBaseMenuBtn SysBaseMenuBtn ` gorm:"comment:按钮详情"`
Expand Down
4 changes: 2 additions & 2 deletions server/model/system/sys_authority_menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package system
type SysMenu struct {
SysBaseMenu
MenuId string `json:"menuId" gorm:"comment:菜单ID"`
AuthorityId string `json:"-" gorm:"comment:角色ID"`
AuthorityId uint `json:"-" gorm:"comment:角色ID"`
Children []SysMenu `json:"children" gorm:"-"`
Parameters []SysBaseMenuParameter `json:"parameters" gorm:"foreignKey:SysBaseMenuID;references:MenuId"`
Btns map[string]string `json:"btns" gorm:"-"`
Btns map[string]uint `json:"btns" gorm:"-"`
}

type SysAuthorityMenu struct {
Expand Down
2 changes: 1 addition & 1 deletion server/model/system/sys_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type SysUser struct {
HeaderImg string `json:"headerImg" gorm:"default:https://qmplusimg.henrongyi.top/gva_header.jpg;comment:用户头像"` // 用户头像
BaseColor string `json:"baseColor" gorm:"default:#fff;comment:基础颜色"` // 基础颜色
ActiveColor string `json:"activeColor" gorm:"default:#1890ff;comment:活跃颜色"` // 活跃颜色
AuthorityId string `json:"authorityId" gorm:"default:888;comment:用户角色ID"` // 用户角色ID
AuthorityId uint `json:"authorityId" gorm:"default:888;comment:用户角色ID"` // 用户角色ID
Authority SysAuthority `json:"authority" gorm:"foreignKey:AuthorityId;references:AuthorityId;comment:用户角色"`
Authorities []SysAuthority `json:"authorities" gorm:"many2many:sys_user_authority;"`
Phone string `json:"phone" gorm:"comment:用户手机号"` // 用户手机号
Expand Down
4 changes: 2 additions & 2 deletions server/model/system/sys_user_authority.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package system

type SysUseAuthority struct {
SysUserId uint `gorm:"column:sys_user_id"`
SysAuthorityAuthorityId string `gorm:"column:sys_authority_authority_id"`
SysUserId uint `gorm:"column:sys_user_id"`
SysAuthorityAuthorityId uint `gorm:"column:sys_authority_authority_id"`
}

func (s *SysUseAuthority) TableName() string {
Expand Down
4 changes: 2 additions & 2 deletions server/service/example/exa_customer.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func (exa *CustomerService) GetExaCustomer(id uint) (customer example.ExaCustome
//@param: sysUserAuthorityID string, info request.PageInfo
//@return: list interface{}, total int64, err error

func (exa *CustomerService) GetCustomerInfoList(sysUserAuthorityID string, info request.PageInfo) (list interface{}, total int64, err error) {
func (exa *CustomerService) GetCustomerInfoList(sysUserAuthorityID uint, info request.PageInfo) (list interface{}, total int64, err error) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
db := global.GVA_DB.Model(&example.ExaCustomer{})
Expand All @@ -70,7 +70,7 @@ func (exa *CustomerService) GetCustomerInfoList(sysUserAuthorityID string, info
if err != nil {
return
}
var dataId []string
var dataId []uint
for _, v := range auth.DataAuthorityId {
dataId = append(dataId, v.AuthorityId)
}
Expand Down
Loading

0 comments on commit 68317c1

Please sign in to comment.