Compare commits

...

2 Commits

Author SHA1 Message Date
daniel.w 2ae757f92a add get role 2024-08-20 00:59:38 +08:00
daniel.w 8ae8a17bbb feat: add role and update role 2024-08-19 09:39:05 +08:00
37 changed files with 1551 additions and 50 deletions

View File

@ -19,31 +19,42 @@ type (
CheckPermissionByRoleReq = permission.CheckPermissionByRoleReq CheckPermissionByRoleReq = permission.CheckPermissionByRoleReq
CreateOneTimeTokenReq = permission.CreateOneTimeTokenReq CreateOneTimeTokenReq = permission.CreateOneTimeTokenReq
CreateOneTimeTokenResp = permission.CreateOneTimeTokenResp CreateOneTimeTokenResp = permission.CreateOneTimeTokenResp
CreateRoleReq = permission.CreateRoleReq
DoTokenByDeviceIDReq = permission.DoTokenByDeviceIDReq DoTokenByDeviceIDReq = permission.DoTokenByDeviceIDReq
DoTokenByUIDReq = permission.DoTokenByUIDReq DoTokenByUIDReq = permission.DoTokenByUIDReq
GetPermissionStatusByPathReq = permission.GetPermissionStatusByPathReq GetPermissionStatusByPathReq = permission.GetPermissionStatusByPathReq
GetRoleReq = permission.GetRoleReq
GetRoleResp = permission.GetRoleResp
GetUserRoleResp = permission.GetUserRoleResp
ListPermissionResp = permission.ListPermissionResp ListPermissionResp = permission.ListPermissionResp
ListPermissionStatusResp = permission.ListPermissionStatusResp ListPermissionStatusResp = permission.ListPermissionStatusResp
MapPermissionStatusResp = permission.MapPermissionStatusResp MapPermissionStatusResp = permission.MapPermissionStatusResp
NoneReq = permission.NoneReq NoneReq = permission.NoneReq
OKResp = permission.OKResp OKResp = permission.OKResp
PageResponse = permission.PageResponse
PermissionItem = permission.PermissionItem PermissionItem = permission.PermissionItem
PermissionResp = permission.PermissionResp PermissionResp = permission.PermissionResp
PermissionStatusItem = permission.PermissionStatusItem PermissionStatusItem = permission.PermissionStatusItem
QueryTokenByUIDReq = permission.QueryTokenByUIDReq QueryTokenByUIDReq = permission.QueryTokenByUIDReq
RefreshTokenReq = permission.RefreshTokenReq RefreshTokenReq = permission.RefreshTokenReq
RefreshTokenResp = permission.RefreshTokenResp RefreshTokenResp = permission.RefreshTokenResp
RoleResp = permission.RoleResp
Token = permission.Token Token = permission.Token
TokenResp = permission.TokenResp TokenResp = permission.TokenResp
Tokens = permission.Tokens Tokens = permission.Tokens
UpdateRoleReq = permission.UpdateRoleReq
UserPermissionReq = permission.UserPermissionReq
UserPermissionResp = permission.UserPermissionResp
UserRoleReq = permission.UserRoleReq
UserRoleResp = permission.UserRoleResp
ValidationTokenReq = permission.ValidationTokenReq ValidationTokenReq = permission.ValidationTokenReq
ValidationTokenResp = permission.ValidationTokenResp ValidationTokenResp = permission.ValidationTokenResp
PermissionService interface { PermissionService interface {
// ListPermissionStatus 取得所有權限狀態列表,給前端表演用 // ListPermissionStatus 取得所有權限狀態列表,給前端表演用
ListPermissionStatus(ctx context.Context, in *NoneReq, opts ...grpc.CallOption) (*ListPermissionStatusResp, error) ListPermissionStatus(ctx context.Context, in *NoneReq, opts ...grpc.CallOption) (*ListPermissionStatusResp, error)
// MapPermissionStatus 取得所有權限開閉狀態,簡易版,給前端表演用 // ListPermission 一次性取得所有權限表
MapPermissionStatus(ctx context.Context, in *NoneReq, opts ...grpc.CallOption) (*MapPermissionStatusResp, error) ListPermission(ctx context.Context, in *NoneReq, opts ...grpc.CallOption) (*MapPermissionStatusResp, error)
// CheckPermissionByRole 透過角色 ID 來檢視權限,後台要通過時真的看這個 // CheckPermissionByRole 透過角色 ID 來檢視權限,後台要通過時真的看這個
CheckPermissionByRole(ctx context.Context, in *CheckPermissionByRoleReq, opts ...grpc.CallOption) (*PermissionResp, error) CheckPermissionByRole(ctx context.Context, in *CheckPermissionByRoleReq, opts ...grpc.CallOption) (*PermissionResp, error)
// GetPermissionStatusByPath 透過資源拿取角色的狀態 // GetPermissionStatusByPath 透過資源拿取角色的狀態
@ -67,10 +78,10 @@ func (m *defaultPermissionService) ListPermissionStatus(ctx context.Context, in
return client.ListPermissionStatus(ctx, in, opts...) return client.ListPermissionStatus(ctx, in, opts...)
} }
// MapPermissionStatus 取得所有權限開閉狀態,簡易版,給前端表演用 // ListPermission 一次性取得所有權限表
func (m *defaultPermissionService) MapPermissionStatus(ctx context.Context, in *NoneReq, opts ...grpc.CallOption) (*MapPermissionStatusResp, error) { func (m *defaultPermissionService) ListPermission(ctx context.Context, in *NoneReq, opts ...grpc.CallOption) (*MapPermissionStatusResp, error) {
client := permission.NewPermissionServiceClient(m.cli.Conn()) client := permission.NewPermissionServiceClient(m.cli.Conn())
return client.MapPermissionStatus(ctx, in, opts...) return client.ListPermission(ctx, in, opts...)
} }
// CheckPermissionByRole 透過角色 ID 來檢視權限,後台要通過時真的看這個 // CheckPermissionByRole 透過角色 ID 來檢視權限,後台要通過時真的看這個

View File

@ -19,28 +19,44 @@ type (
CheckPermissionByRoleReq = permission.CheckPermissionByRoleReq CheckPermissionByRoleReq = permission.CheckPermissionByRoleReq
CreateOneTimeTokenReq = permission.CreateOneTimeTokenReq CreateOneTimeTokenReq = permission.CreateOneTimeTokenReq
CreateOneTimeTokenResp = permission.CreateOneTimeTokenResp CreateOneTimeTokenResp = permission.CreateOneTimeTokenResp
CreateRoleReq = permission.CreateRoleReq
DoTokenByDeviceIDReq = permission.DoTokenByDeviceIDReq DoTokenByDeviceIDReq = permission.DoTokenByDeviceIDReq
DoTokenByUIDReq = permission.DoTokenByUIDReq DoTokenByUIDReq = permission.DoTokenByUIDReq
GetPermissionStatusByPathReq = permission.GetPermissionStatusByPathReq GetPermissionStatusByPathReq = permission.GetPermissionStatusByPathReq
GetRoleReq = permission.GetRoleReq
GetRoleResp = permission.GetRoleResp
GetUserRoleResp = permission.GetUserRoleResp
ListPermissionResp = permission.ListPermissionResp ListPermissionResp = permission.ListPermissionResp
ListPermissionStatusResp = permission.ListPermissionStatusResp ListPermissionStatusResp = permission.ListPermissionStatusResp
MapPermissionStatusResp = permission.MapPermissionStatusResp MapPermissionStatusResp = permission.MapPermissionStatusResp
NoneReq = permission.NoneReq NoneReq = permission.NoneReq
OKResp = permission.OKResp OKResp = permission.OKResp
PageResponse = permission.PageResponse
PermissionItem = permission.PermissionItem PermissionItem = permission.PermissionItem
PermissionResp = permission.PermissionResp PermissionResp = permission.PermissionResp
PermissionStatusItem = permission.PermissionStatusItem PermissionStatusItem = permission.PermissionStatusItem
QueryTokenByUIDReq = permission.QueryTokenByUIDReq QueryTokenByUIDReq = permission.QueryTokenByUIDReq
RefreshTokenReq = permission.RefreshTokenReq RefreshTokenReq = permission.RefreshTokenReq
RefreshTokenResp = permission.RefreshTokenResp RefreshTokenResp = permission.RefreshTokenResp
RoleResp = permission.RoleResp
Token = permission.Token Token = permission.Token
TokenResp = permission.TokenResp TokenResp = permission.TokenResp
Tokens = permission.Tokens Tokens = permission.Tokens
UpdateRoleReq = permission.UpdateRoleReq
UserPermissionReq = permission.UserPermissionReq
UserPermissionResp = permission.UserPermissionResp
UserRoleReq = permission.UserRoleReq
UserRoleResp = permission.UserRoleResp
ValidationTokenReq = permission.ValidationTokenReq ValidationTokenReq = permission.ValidationTokenReq
ValidationTokenResp = permission.ValidationTokenResp ValidationTokenResp = permission.ValidationTokenResp
RoleService interface { RoleService interface {
Ping(ctx context.Context, in *OKResp, opts ...grpc.CallOption) (*OKResp, error) // CreateRole 建立角色
CreateRole(ctx context.Context, in *CreateRoleReq, opts ...grpc.CallOption) (*RoleResp, error)
// GetRole 取得搜尋的角色
GetRole(ctx context.Context, in *GetRoleReq, opts ...grpc.CallOption) (*GetRoleResp, error)
// UpdateRole 更新角色
UpdateRole(ctx context.Context, in *UpdateRoleReq, opts ...grpc.CallOption) (*RoleResp, error)
} }
defaultRoleService struct { defaultRoleService struct {
@ -54,7 +70,20 @@ func NewRoleService(cli zrpc.Client) RoleService {
} }
} }
func (m *defaultRoleService) Ping(ctx context.Context, in *OKResp, opts ...grpc.CallOption) (*OKResp, error) { // CreateRole 建立角色
func (m *defaultRoleService) CreateRole(ctx context.Context, in *CreateRoleReq, opts ...grpc.CallOption) (*RoleResp, error) {
client := permission.NewRoleServiceClient(m.cli.Conn()) client := permission.NewRoleServiceClient(m.cli.Conn())
return client.Ping(ctx, in, opts...) return client.CreateRole(ctx, in, opts...)
}
// GetRole 取得搜尋的角色
func (m *defaultRoleService) GetRole(ctx context.Context, in *GetRoleReq, opts ...grpc.CallOption) (*GetRoleResp, error) {
client := permission.NewRoleServiceClient(m.cli.Conn())
return client.GetRole(ctx, in, opts...)
}
// UpdateRole 更新角色
func (m *defaultRoleService) UpdateRole(ctx context.Context, in *UpdateRoleReq, opts ...grpc.CallOption) (*RoleResp, error) {
client := permission.NewRoleServiceClient(m.cli.Conn())
return client.UpdateRole(ctx, in, opts...)
} }

View File

@ -19,23 +19,34 @@ type (
CheckPermissionByRoleReq = permission.CheckPermissionByRoleReq CheckPermissionByRoleReq = permission.CheckPermissionByRoleReq
CreateOneTimeTokenReq = permission.CreateOneTimeTokenReq CreateOneTimeTokenReq = permission.CreateOneTimeTokenReq
CreateOneTimeTokenResp = permission.CreateOneTimeTokenResp CreateOneTimeTokenResp = permission.CreateOneTimeTokenResp
CreateRoleReq = permission.CreateRoleReq
DoTokenByDeviceIDReq = permission.DoTokenByDeviceIDReq DoTokenByDeviceIDReq = permission.DoTokenByDeviceIDReq
DoTokenByUIDReq = permission.DoTokenByUIDReq DoTokenByUIDReq = permission.DoTokenByUIDReq
GetPermissionStatusByPathReq = permission.GetPermissionStatusByPathReq GetPermissionStatusByPathReq = permission.GetPermissionStatusByPathReq
GetRoleReq = permission.GetRoleReq
GetRoleResp = permission.GetRoleResp
GetUserRoleResp = permission.GetUserRoleResp
ListPermissionResp = permission.ListPermissionResp ListPermissionResp = permission.ListPermissionResp
ListPermissionStatusResp = permission.ListPermissionStatusResp ListPermissionStatusResp = permission.ListPermissionStatusResp
MapPermissionStatusResp = permission.MapPermissionStatusResp MapPermissionStatusResp = permission.MapPermissionStatusResp
NoneReq = permission.NoneReq NoneReq = permission.NoneReq
OKResp = permission.OKResp OKResp = permission.OKResp
PageResponse = permission.PageResponse
PermissionItem = permission.PermissionItem PermissionItem = permission.PermissionItem
PermissionResp = permission.PermissionResp PermissionResp = permission.PermissionResp
PermissionStatusItem = permission.PermissionStatusItem PermissionStatusItem = permission.PermissionStatusItem
QueryTokenByUIDReq = permission.QueryTokenByUIDReq QueryTokenByUIDReq = permission.QueryTokenByUIDReq
RefreshTokenReq = permission.RefreshTokenReq RefreshTokenReq = permission.RefreshTokenReq
RefreshTokenResp = permission.RefreshTokenResp RefreshTokenResp = permission.RefreshTokenResp
RoleResp = permission.RoleResp
Token = permission.Token Token = permission.Token
TokenResp = permission.TokenResp TokenResp = permission.TokenResp
Tokens = permission.Tokens Tokens = permission.Tokens
UpdateRoleReq = permission.UpdateRoleReq
UserPermissionReq = permission.UserPermissionReq
UserPermissionResp = permission.UserPermissionResp
UserRoleReq = permission.UserRoleReq
UserRoleResp = permission.UserRoleResp
ValidationTokenReq = permission.ValidationTokenReq ValidationTokenReq = permission.ValidationTokenReq
ValidationTokenResp = permission.ValidationTokenResp ValidationTokenResp = permission.ValidationTokenResp

View File

@ -0,0 +1,97 @@
// Code generated by goctl. DO NOT EDIT.
// Source: permission.proto
package userroleservice
import (
"context"
"ark-permission/gen_result/pb/permission"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
AuthorizationReq = permission.AuthorizationReq
CancelOneTimeTokenReq = permission.CancelOneTimeTokenReq
CancelTokenReq = permission.CancelTokenReq
CheckPermissionByRoleReq = permission.CheckPermissionByRoleReq
CreateOneTimeTokenReq = permission.CreateOneTimeTokenReq
CreateOneTimeTokenResp = permission.CreateOneTimeTokenResp
CreateRoleReq = permission.CreateRoleReq
DoTokenByDeviceIDReq = permission.DoTokenByDeviceIDReq
DoTokenByUIDReq = permission.DoTokenByUIDReq
GetPermissionStatusByPathReq = permission.GetPermissionStatusByPathReq
GetRoleReq = permission.GetRoleReq
GetRoleResp = permission.GetRoleResp
GetUserRoleResp = permission.GetUserRoleResp
ListPermissionResp = permission.ListPermissionResp
ListPermissionStatusResp = permission.ListPermissionStatusResp
MapPermissionStatusResp = permission.MapPermissionStatusResp
NoneReq = permission.NoneReq
OKResp = permission.OKResp
PageResponse = permission.PageResponse
PermissionItem = permission.PermissionItem
PermissionResp = permission.PermissionResp
PermissionStatusItem = permission.PermissionStatusItem
QueryTokenByUIDReq = permission.QueryTokenByUIDReq
RefreshTokenReq = permission.RefreshTokenReq
RefreshTokenResp = permission.RefreshTokenResp
RoleResp = permission.RoleResp
Token = permission.Token
TokenResp = permission.TokenResp
Tokens = permission.Tokens
UpdateRoleReq = permission.UpdateRoleReq
UserPermissionReq = permission.UserPermissionReq
UserPermissionResp = permission.UserPermissionResp
UserRoleReq = permission.UserRoleReq
UserRoleResp = permission.UserRoleResp
ValidationTokenReq = permission.ValidationTokenReq
ValidationTokenResp = permission.ValidationTokenResp
UserRoleService interface {
// CreateUserRole 建立角色
CreateUserRole(ctx context.Context, in *UserRoleReq, opts ...grpc.CallOption) (*UserRoleResp, error)
// UpdateRole 更新角色
UpdateUserRole(ctx context.Context, in *UserRoleReq, opts ...grpc.CallOption) (*UserRoleResp, error)
// GetUserRole 取得角色綁定表,沒有搜尋條件就全部,不分頁
GetUserRole(ctx context.Context, in *UserRoleReq, opts ...grpc.CallOption) (*GetUserRoleResp, error)
// GetUserPermission 取得角色權限
GetUserPermission(ctx context.Context, in *UserPermissionReq, opts ...grpc.CallOption) (*UserPermissionResp, error)
}
defaultUserRoleService struct {
cli zrpc.Client
}
)
func NewUserRoleService(cli zrpc.Client) UserRoleService {
return &defaultUserRoleService{
cli: cli,
}
}
// CreateUserRole 建立角色
func (m *defaultUserRoleService) CreateUserRole(ctx context.Context, in *UserRoleReq, opts ...grpc.CallOption) (*UserRoleResp, error) {
client := permission.NewUserRoleServiceClient(m.cli.Conn())
return client.CreateUserRole(ctx, in, opts...)
}
// UpdateRole 更新角色
func (m *defaultUserRoleService) UpdateUserRole(ctx context.Context, in *UserRoleReq, opts ...grpc.CallOption) (*UserRoleResp, error) {
client := permission.NewUserRoleServiceClient(m.cli.Conn())
return client.UpdateUserRole(ctx, in, opts...)
}
// GetUserRole 取得角色綁定表,沒有搜尋條件就全部,不分頁
func (m *defaultUserRoleService) GetUserRole(ctx context.Context, in *UserRoleReq, opts ...grpc.CallOption) (*GetUserRoleResp, error) {
client := permission.NewUserRoleServiceClient(m.cli.Conn())
return client.GetUserRole(ctx, in, opts...)
}
// GetUserPermission 取得角色權限
func (m *defaultUserRoleService) GetUserPermission(ctx context.Context, in *UserPermissionReq, opts ...grpc.CallOption) (*UserPermissionResp, error) {
client := permission.NewUserRoleServiceClient(m.cli.Conn())
return client.GetUserPermission(ctx, in, opts...)
}

View File

@ -0,0 +1 @@
DROP TABLE IF EXISTS `role`;

View File

@ -0,0 +1,12 @@
CREATE TABLE `role`
(
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'PK',
`role_id` varchar(50) NOT NULL,
`display_name` varchar(255) NOT NULL COMMENT '名稱',
`status` tinyint NOT NULL DEFAULT '1' COMMENT '狀態 1: 啟用, 2: 禁用',
`create_time` bigint DEFAULT 0 NOT NULL COMMENT '創建時間',
`update_time` bigint DEFAULT 0 NOT NULL COMMENT '更新時間',
PRIMARY KEY (`id`),
UNIQUE KEY `uid_unique_key` (`role_id`),
UNIQUE KEY `name_unique_key` (`display_name`)
) ENGINE = InnoDB COMMENT ='角色';

View File

@ -0,0 +1 @@
DROP TABLE IF EXISTS `user_role`;

View File

@ -0,0 +1,12 @@
CREATE TABLE `user_role`
(
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'PK',
`brand` varchar(50) DEFAULT '' NOT NULL COMMENT '',
`uid` varchar(50) NOT NULL,
`role_id` varchar(50) NOT NULL,
`status` tinyint NOT NULL DEFAULT '1' COMMENT '狀態 1: 啟用, 2: 禁用',
`create_time` bigint DEFAULT 0 NOT NULL COMMENT '創建時間',
`update_time` bigint DEFAULT 0 NOT NULL COMMENT '更新時間',
PRIMARY KEY (`id`),
UNIQUE KEY `uid_unique_key` (`uid`)
) ENGINE = InnoDB COMMENT ='會員角色';

View File

@ -0,0 +1 @@
DROP TABLE IF EXISTS `role_permission`;

View File

@ -0,0 +1,10 @@
CREATE TABLE `role_permission`
(
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'PK',
`role_id` bigint unsigned DEFAULT NULL COMMENT 'role.id',
`permission_id` bigint unsigned DEFAULT NULL COMMENT 'permission.id',
`create_time` bigint DEFAULT 0 NOT NULL COMMENT '創建時間',
`update_time` bigint DEFAULT 0 NOT NULL COMMENT '更新時間',
PRIMARY KEY (`id`),
KEY `category_id_permission_id_index` (`role_id`, `permission_id`)
) ENGINE = InnoDB COMMENT ='角色權限';

View File

@ -0,0 +1 @@
DELETE FROM `role` WHERE (`role_id` = 'AM000000');

View File

@ -0,0 +1,3 @@
INSERT INTO `role` (`role_id`, `display_name`, `status`, `create_time`, `update_time`)
VALUES ('AM000000', 'admin', 1, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()),
('AM000001', 'visitor', 1, UNIX_TIMESTAMP(), UNIX_TIMESTAMP());

View File

@ -227,8 +227,99 @@ service PermissionService {
} }
// --------------------------------------------------------------------------------
service RoleService { message GetRoleReq{
rpc Ping(OKResp) returns(OKResp); string role_ids =1;
string display_name=2;
repeated string permissions=3;
PermissionStatus status=4;
int64 page_index=5;
int64 page_size=6;
bool all=7;
} }
// RoleResp Protobuf message
message RoleResp {
int64 id = 1; // ID
string display_name = 2; // name
string role_id = 3; // role_id -> int64
map<string, string> permissions = 4; // permissions
PermissionStatus status = 5; // status
int64 create_time = 6; // create_time
int64 update_time = 7; // update_time
}
// PageResponse pager.Response
message PageResponse {
int64 page_index = 1; //
int64 page_size = 2; //
int64 total_count = 3; //
}
// PageRoleResp Protobuf message
message GetRoleResp {
repeated RoleResp list = 1; // list
PageResponse page = 2; // page
}
message CreateRoleReq{
string display_name=1;
PermissionStatus status = 2; // status
string role_id =3;
}
message UpdateRoleReq{
string role_id =1; //
PermissionStatus status = 2; // status
string display_name =3;
}
// RoleService
service RoleService {
// CreateRole
rpc CreateRole(CreateRoleReq)returns(RoleResp);
// GetRole
rpc GetRole(GetRoleReq)returns(GetRoleResp);
// UpdateRole
rpc UpdateRole(UpdateRoleReq)returns(RoleResp);
}
message UserRoleReq{
string uid =1;
string role_id =2;
}
message UserRoleResp{
string uid =1;
string role_id =2;
int64 create_time = 3; // create_time
int64 update_time = 4; // update_time
}
message GetUserRoleResp{
repeated UpdateRoleReq list=1;
}
message UserPermissionReq{
string uid =1;
}
message UserPermissionResp{
string role_id =1;
map<string, string> permissions = 2; // permissions
}
// UserRoleService
service UserRoleService {
// CreateUserRole
rpc CreateUserRole(UserRoleReq)returns(UserRoleResp);
// UpdateRole
rpc UpdateUserRole(UserRoleReq)returns(UserRoleResp);
// GetUserRole
rpc GetUserRole(UserRoleReq)returns(GetUserRoleResp);
// GetUserPermission
rpc GetUserPermission(UserPermissionReq)returns(UserPermissionResp);
}

View File

@ -39,3 +39,7 @@ const (
PermissionStatusOpenCode PermissionStatus = "open" PermissionStatusOpenCode PermissionStatus = "open"
PermissionStatusCloseCode PermissionStatus = "close" PermissionStatusCloseCode PermissionStatus = "close"
) )
const (
AdminRoleID = "GodDog!@#"
)

17
internal/entity/role.go Normal file
View File

@ -0,0 +1,17 @@
package entity
import "ark-permission/internal/domain"
type Role struct {
ID int64 `gorm:"column:id"`
RoleID string `gorm:"column:role_id"`
DisplayName string `gorm:"column:display_name"`
Status int `gorm:"column:status"`
Permissions domain.Permissions `gorm:"-"`
CreateTime int64 `gorm:"column:create_time;autoCreateTime"`
UpdateTime int64 `gorm:"column:update_time;autoUpdateTime"`
}
func (c *Role) TableName() string {
return "role"
}

View File

@ -0,0 +1,25 @@
package entity
import "ark-permission/internal/domain"
type RoleLog struct {
ID string `json:"id,omitempty"`
Before AlterRoleLog `json:"before"`
After AlterRoleLog `json:"after"`
Name string `json:"name"`
UID string `json:"uid"`
UpdateUserUID string `json:"update_user_uid"`
UpdateUserName string `json:"update_user_name"`
CreateTime int64 `json:"create_time"`
Version string `json:"ver"`
}
type AlterRoleLog struct {
Permissions []AlterPermission `json:"permissions"`
Status int `json:"status"`
}
type AlterPermission struct {
Name string `json:"name"`
Status domain.PermissionStatus `json:"status"`
}

View File

@ -0,0 +1,20 @@
package entity
type UserRole struct {
ID int64 `gorm:"column:id"`
Brand string `gorm:"column:brand"`
UID string `gorm:"column:uid"`
RoleID string `gorm:"column:role_id"`
Status int `gorm:"column:status"`
CreateTime int64 `gorm:"column:create_time;autoCreateTime"`
UpdateTime int64 `gorm:"column:update_time;autoUpdateTime"`
}
func (c *UserRole) TableName() string {
return "user_role"
}
type RoleUserCount struct {
RoleID string `gorm:"column:role_id"`
Count int `gorm:"column:count"`
}

View File

@ -0,0 +1,31 @@
package permissionservicelogic
import (
"context"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type ListPermissionLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewListPermissionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListPermissionLogic {
return &ListPermissionLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// ListPermission 一次性取得所有權限表
func (l *ListPermissionLogic) ListPermission(in *permission.NoneReq) (*permission.MapPermissionStatusResp, error) {
// todo: add your logic here and delete this line
return &permission.MapPermissionStatusResp{}, nil
}

View File

@ -0,0 +1,84 @@
package roleservicelogic
import (
"ark-permission/internal/model"
ers "code.30cm.net/wanderland/library-go/errors"
"context"
"fmt"
"time"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type CreateRoleLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleLogic {
return &CreateRoleLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
type createRoleReq struct {
Status string `json:"status" binding:"required"`
RoleID string `json:"role_id"`
DisplayName string `json:"display_name" binding:"required"`
}
// CreateRole 建立角色
func (l *CreateRoleLogic) CreateRole(in *permission.CreateRoleReq) (*permission.RoleResp, error) {
// 驗證所需
if err := l.svcCtx.Validate.ValidateAll(&createRoleReq{
Status: in.GetStatus().String(),
DisplayName: in.GetDisplayName(),
}); err != nil {
return nil, ers.InvalidFormat(err.Error())
}
// 有操作失敗風險,因為如果並行狀態下有可能撞到產生的 role_id 一樣,不過此時有在表當中,擋 UK ,發生機率小,請使用者重試即可
roleID, err := l.svcCtx.RoleRepo.IncrementID(l.ctx)
if err != nil {
return nil, ers.DBError("[permission.CreateRole] failed to get IncrementID", err.Error())
}
rid := in.GetRoleId()
if rid == "" {
rid = fmt.Sprintf("AM%06d", roleID)
}
now := time.Now().UTC()
data := model.Role{
RoleId: rid,
DisplayName: in.GetDisplayName(),
Status: int64(in.GetStatus().Number()),
CreateTime: now.Unix(),
UpdateTime: now.Unix(),
}
res, err := l.svcCtx.RoleRepo.Insert(l.ctx, &data)
if err != nil {
return nil, ers.DBError("[RoleRepo.Insert] failed to insert role data", err.Error())
}
lastID, err := res.LastInsertId()
if err != nil {
lastID = 0
}
return &permission.RoleResp{
Id: lastID,
DisplayName: data.DisplayName,
RoleId: data.RoleId,
Status: permission.PermissionStatus(data.Status),
CreateTime: data.CreateTime,
UpdateTime: data.UpdateTime,
}, nil
}

View File

@ -0,0 +1,191 @@
package roleservicelogic
import (
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/domain"
"ark-permission/internal/entity"
"ark-permission/internal/model"
"ark-permission/internal/svc"
ers "code.30cm.net/wanderland/library-go/errors"
"context"
"errors"
"github.com/zeromicro/go-zero/core/logx"
)
type GetRoleLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRoleLogic {
return &GetRoleLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// GetRole 取得搜尋的角色
func (l *GetRoleLogic) GetRole(in *permission.GetRoleReq) (*permission.GetRoleResp, error) {
// 檢查是否為全表搜尋
if in.GetAll() {
return l.getAllRoles()
}
// 處理分頁參數
size := int64(20)
if in.GetPageSize() != 0 {
size = in.GetPageSize()
}
index := int64(1)
if in.GetPageIndex() != 0 {
index = in.GetPageIndex()
}
// 執行角色搜尋和計算總數
roles, count, err := l.searchRolesWithCount(in, size, index)
if err != nil {
return nil, err
}
// 組裝結果
return l.buildRoleResp(roles, in.PageSize, in.PageIndex, count, in.GetPermissions()), nil
}
// getAllRoles 獲取全表角色
func (l *GetRoleLogic) getAllRoles() (*permission.GetRoleResp, error) {
// 查詢所有角色
roles, err := l.svcCtx.RoleRepo.Find(l.ctx)
if err != nil {
return nil, l.handleDBError(err, "failed to get role")
}
// 計算總數
count, err := l.svcCtx.RoleRepo.Count(l.ctx, &model.Role{})
if err != nil {
return nil, l.handleDBError(err, "failed to get role")
}
// 組裝結果
return l.buildRoleResp(roles, -1, -1, count, nil), nil
}
// searchRolesWithCount 搜尋角色並計算總數
func (l *GetRoleLogic) searchRolesWithCount(in *permission.GetRoleReq, size, index int64) ([]*model.Role, int64, error) {
// 搜尋角色
roles, err := l.svcCtx.RoleRepo.SearchRoles(l.ctx, &model.Role{
RoleId: in.GetRoleIds(),
DisplayName: in.GetDisplayName(),
Status: int64(in.GetStatus().Number()),
}, size, index)
if err != nil {
return nil, 0, err
}
// 計算總數
count, err := l.svcCtx.RoleRepo.Count(l.ctx, &model.Role{
RoleId: in.GetRoleIds(),
DisplayName: in.GetDisplayName(),
Status: int64(in.GetStatus().Number()),
})
if err != nil {
return nil, 0, l.handleDBError(err, "failed to get role")
}
list := make([]*model.Role, 0, count)
for _, item := range roles {
list = append(list, &item)
}
return list, count, nil
}
// handleDBError 處理資料庫錯誤
func (l *GetRoleLogic) handleDBError(err error, msg string) error {
if errors.Is(model.ErrNotFound, err) {
return ers.ResourceNotFound(msg)
}
return ers.DBError(err.Error())
}
// buildRoleResp 組裝角色回應
func (l *GetRoleLogic) buildRoleResp(roles []*model.Role, pageSize, pageIndex, totalCount int64, filter []string) *permission.GetRoleResp {
list := make([]*permission.RoleResp, 0, len(roles))
for _, item := range roles {
permissions := make(map[string]string)
// Admin 角色
if item.RoleId == domain.AdminRoleID {
data, err := l.svcCtx.Permission.FindAllOpenPermission(l.ctx)
if err != nil {
// log
continue
}
for _, v := range data {
permissions[v.Name] = string(domain.PermissionStatusOpenCode)
}
} else {
rolePermission, err := l.svcCtx.RolePermissionRepo.FindOneByRoleID(l.ctx, item.RoleId)
if err != nil {
// log
continue
}
var rp = make([]entity.RolePermission, 0, len(rolePermission))
for _, item := range rolePermission {
rp = append(rp, entity.RolePermission{
ID: item.Id,
RoleID: item.RoleId.Int64,
PermissionID: item.PermissionId.Int64,
CreateTime: item.CreateTime,
UpdateTime: item.UpdateTime,
})
}
userRolePermission, err := l.svcCtx.PermissionTree.GetRolePermissionTree(rp)
if err != nil {
return nil
}
if filter == nil {
list = append(list, &permission.RoleResp{
Id: item.Id,
DisplayName: item.DisplayName,
RoleId: item.RoleId,
Status: permission.PermissionStatus(item.Status),
Permissions: permissions,
CreateTime: item.CreateTime,
UpdateTime: item.UpdateTime,
})
} else {
for _, p := range filter {
if userRolePermission[p] == domain.PermissionStatusOpenCode {
list = append(list, &permission.RoleResp{
Id: item.Id,
DisplayName: item.DisplayName,
RoleId: item.RoleId,
Status: permission.PermissionStatus(item.Status),
Permissions: permissions,
CreateTime: item.CreateTime,
UpdateTime: item.UpdateTime,
})
break
}
}
}
}
}
return &permission.GetRoleResp{
List: list,
Page: &permission.PageResponse{
PageSize: pageSize,
PageIndex: pageIndex,
TotalCount: totalCount,
},
}
}

View File

@ -1,30 +0,0 @@
package roleservicelogic
import (
"context"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type PingLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewPingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PingLogic {
return &PingLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *PingLogic) Ping(in *permission.OKResp) (*permission.OKResp, error) {
// todo: add your logic here and delete this line
return &permission.OKResp{}, nil
}

View File

@ -0,0 +1,75 @@
package roleservicelogic
import (
ers "code.30cm.net/wanderland/library-go/errors"
"context"
"fmt"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateRoleLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUpdateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRoleLogic {
return &UpdateRoleLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// UpdateRole 更新角色
func (l *UpdateRoleLogic) UpdateRole(in *permission.UpdateRoleReq) (*permission.RoleResp, error) {
if in.GetRoleId() == "" {
return nil, ers.InvalidFormat("failed to get role id")
}
// 暴露出 transaction 的統包,可以實現跨表跟同表
err := l.svcCtx.Conn.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
if in.GetStatus() != 0 {
if in.GetStatus() == permission.PermissionStatus_PERMISSION_STATUS_NONE {
return fmt.Errorf("failed to get role id")
}
err := l.svcCtx.RoleRepo.TransUpdateStatusByRoleID(
ctx, session, int64(in.GetStatus().Number()), in.GetRoleId())
if err != nil {
return err
}
}
if in.GetDisplayName() != "" {
err := l.svcCtx.RoleRepo.TransUpdateDisplayNameByRoleID(
ctx, session, in.GetDisplayName(), in.GetRoleId())
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, ers.DBError(err.Error())
}
result, err := l.svcCtx.RoleRepo.FindOneByRoleId(l.ctx, in.GetRoleId())
if err != nil {
return nil, ers.DBError(err.Error())
}
return &permission.RoleResp{
Id: result.Id,
Status: permission.PermissionStatus(result.Status),
DisplayName: result.DisplayName,
RoleId: result.RoleId,
CreateTime: result.CreateTime,
UpdateTime: result.UpdateTime,
}, nil
}

View File

@ -0,0 +1,31 @@
package userroleservicelogic
import (
"context"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type CreateUserRoleLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewCreateUserRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserRoleLogic {
return &CreateUserRoleLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// CreateUserRole 建立角色
func (l *CreateUserRoleLogic) CreateUserRole(in *permission.UserRoleReq) (*permission.UserRoleResp, error) {
// todo: add your logic here and delete this line
return &permission.UserRoleResp{}, nil
}

View File

@ -0,0 +1,31 @@
package userroleservicelogic
import (
"context"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetUserPermissionLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetUserPermissionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserPermissionLogic {
return &GetUserPermissionLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// GetUserPermission 取得角色權限
func (l *GetUserPermissionLogic) GetUserPermission(in *permission.UserPermissionReq) (*permission.UserPermissionResp, error) {
// todo: add your logic here and delete this line
return &permission.UserPermissionResp{}, nil
}

View File

@ -0,0 +1,30 @@
package userroleservicelogic
import (
"context"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetUserRoleLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetUserRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserRoleLogic {
return &GetUserRoleLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// GetUserRole 取得角色綁定表,沒有搜尋條件就全部,不分頁
func (l *GetUserRoleLogic) GetUserRole(in *permission.UserRoleReq) (*permission.GetUserRoleResp, error) {
return &permission.GetUserRoleResp{}, nil
}

View File

@ -0,0 +1,31 @@
package userroleservicelogic
import (
"context"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateUserRoleLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUpdateUserRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserRoleLogic {
return &UpdateUserRoleLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// UpdateRole 更新角色
func (l *UpdateUserRoleLogic) UpdateUserRole(in *permission.UserRoleReq) (*permission.UserRoleResp, error) {
// todo: add your logic here and delete this line
return &permission.UserRoleResp{}, nil
}

186
internal/model/role_model.go Executable file
View File

@ -0,0 +1,186 @@
package model
import (
"context"
"errors"
"fmt"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"strings"
"time"
)
var _ RoleModel = (*customRoleModel)(nil)
type (
// RoleModel is an interface to be customized, add more methods here,
// and implement the added methods in customRoleModel.
RoleModel interface {
roleModel
IncrementID(ctx context.Context) (int64, error)
TransUpdateStatusByRoleID(
ctx context.Context,
session sqlx.Session,
status int64,
roleId string) error
TransUpdateDisplayNameByRoleID(
ctx context.Context,
session sqlx.Session,
roleId string,
displayName string) error
Find(ctx context.Context) ([]*Role, error)
Count(ctx context.Context, role *Role) (int64, error)
SearchRoles(ctx context.Context, role *Role, pageIndex, PageSize int64) (result []Role, err error)
}
customRoleModel struct {
*defaultRoleModel
}
RoleFilter struct {
PageIndex *int64
PageSize *int64
RoleId *string
DisplayName *string
Status *int64
}
)
// NewRoleModel returns a model for the database table.
func NewRoleModel(conn sqlx.SqlConn) RoleModel {
return &customRoleModel{
defaultRoleModel: newRoleModel(conn),
}
}
func (m *customRoleModel) IncrementID(ctx context.Context) (int64, error) {
var maxID int64
query := fmt.Sprintf("select IFNULL(MAX(`id`), 0) from %s", m.table)
err := m.conn.QueryRowCtx(ctx, &maxID, query)
if err != nil {
return 0, err
}
// 返回最大 ID 加 1
return maxID + 1, nil
}
func (m *customRoleModel) TransUpdateDisplayNameByRoleID(
ctx context.Context,
session sqlx.Session,
displayName string,
roleId string) error {
query := fmt.Sprintf("update %s set `display_name` = ?, `update_time` = ? where `role_id` = ?", m.table)
// 執行更新操作
updateTime := time.Now().UTC().Unix()
_, err := session.ExecCtx(ctx, query, displayName, updateTime, roleId)
return err
}
func (m *customRoleModel) TransUpdateStatusByRoleID(
ctx context.Context,
session sqlx.Session,
status int64,
roleId string) error {
query := fmt.Sprintf("update %s set `status` = ?, `update_time` = ? where `role_id` = ?", m.table)
// 執行更新操作
updateTime := time.Now().UTC().Unix()
_, err := session.ExecCtx(ctx, query, status, updateTime, roleId)
return err
}
func (m *defaultRoleModel) Find(ctx context.Context) ([]*Role, error) {
query := fmt.Sprintf("select %s from %s", roleRows, m.table)
var resp []*Role
err := m.conn.QueryRowsCtx(ctx, &resp, query)
switch {
case err == nil:
return resp, nil
case errors.Is(err, sqlc.ErrNotFound):
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultRoleModel) Count(ctx context.Context, role *Role) (int64, error) {
var conditions []string
var args []any
// 構建條件
if role.RoleId != "" {
conditions = append(conditions, "`role_id` = ?")
args = append(args, role.RoleId)
}
if role.DisplayName != "" {
conditions = append(conditions, "`display_name` = ?")
args = append(args, role.DisplayName)
}
if role.Status != 0 {
conditions = append(conditions, "`status` = ?")
args = append(args, role.Status)
}
// 構建基礎查詢語句
query := fmt.Sprintf("select COUNT(*) from %s", m.table)
// 如果有條件,添加 WHERE 子句
if len(conditions) > 0 {
query += " where " + strings.Join(conditions, " AND ")
}
var resp int64
err := m.conn.QueryRowCtx(ctx, &resp, query, args...)
switch {
case err == nil:
return resp, nil
case errors.Is(err, sqlc.ErrNotFound):
return 0, ErrNotFound
default:
return 0, err
}
}
func (m *customRoleModel) SearchRoles(ctx context.Context, role *Role, pageIndex, PageSize int64) (result []Role, err error) {
var conditions []string
var args []any
// 構建條件
if role.RoleId != "" {
conditions = append(conditions, "`role_id` = ?")
args = append(args, role.RoleId)
}
if role.DisplayName != "" {
conditions = append(conditions, "`display_name` = ?")
args = append(args, role.DisplayName)
}
if role.Status != 0 {
conditions = append(conditions, "`status` = ?")
args = append(args, role.Status)
}
// 構建基礎查詢語句
query := fmt.Sprintf("select * from %s", m.table)
// 如果有條件,添加 WHERE 子句
if len(conditions) > 0 {
query += " where " + strings.Join(conditions, " AND ")
}
// 添加排序和分頁
query += " order by `id` desc limit ? offset ?"
args = append(args, PageSize, (pageIndex-1)*PageSize)
// 執行查詢
err = m.conn.QueryRowCtx(ctx, &result, query, args...)
switch {
case err == nil:
return result, nil
case errors.Is(err, sqlc.ErrNotFound):
return nil, ErrNotFound
default:
return nil, err
}
}

125
internal/model/role_model_gen.go Executable file
View File

@ -0,0 +1,125 @@
// Code generated by goctl. DO NOT EDIT.
package model
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx"
)
var (
roleFieldNames = builder.RawFieldNames(&Role{})
roleRows = strings.Join(roleFieldNames, ",")
roleRowsExpectAutoSet = strings.Join(stringx.Remove(roleFieldNames, "`id`"), ",")
roleRowsWithPlaceHolder = strings.Join(stringx.Remove(roleFieldNames, "`id`"), "=?,") + "=?"
)
type (
roleModel interface {
Insert(ctx context.Context, data *Role) (sql.Result, error)
FindOne(ctx context.Context, id int64) (*Role, error)
FindOneByDisplayName(ctx context.Context, displayName string) (*Role, error)
FindOneByRoleId(ctx context.Context, roleId string) (*Role, error)
Update(ctx context.Context, data *Role) error
Delete(ctx context.Context, id int64) error
}
defaultRoleModel struct {
conn sqlx.SqlConn
table string
}
Role struct {
Id int64 `db:"id"` // PK
RoleId string `db:"role_id"`
DisplayName string `db:"display_name"` // 名稱
Status int64 `db:"status"` // 狀態 1: 啟用, 2: 禁用
CreateTime int64 `db:"create_time"` // 創建時間
UpdateTime int64 `db:"update_time"` // 更新時間
}
)
func newRoleModel(conn sqlx.SqlConn) *defaultRoleModel {
return &defaultRoleModel{
conn: conn,
table: "`role`",
}
}
func (m *defaultRoleModel) withSession(session sqlx.Session) *defaultRoleModel {
return &defaultRoleModel{
conn: sqlx.NewSqlConnFromSession(session),
table: "`role`",
}
}
func (m *defaultRoleModel) Delete(ctx context.Context, id int64) error {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
_, err := m.conn.ExecCtx(ctx, query, id)
return err
}
func (m *defaultRoleModel) FindOne(ctx context.Context, id int64) (*Role, error) {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", roleRows, m.table)
var resp Role
err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultRoleModel) FindOneByDisplayName(ctx context.Context, displayName string) (*Role, error) {
var resp Role
query := fmt.Sprintf("select %s from %s where `display_name` = ? limit 1", roleRows, m.table)
err := m.conn.QueryRowCtx(ctx, &resp, query, displayName)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultRoleModel) FindOneByRoleId(ctx context.Context, roleId string) (*Role, error) {
var resp Role
query := fmt.Sprintf("select %s from %s where `role_id` = ? limit 1", roleRows, m.table)
err := m.conn.QueryRowCtx(ctx, &resp, query, roleId)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultRoleModel) Insert(ctx context.Context, data *Role) (sql.Result, error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, roleRowsExpectAutoSet)
ret, err := m.conn.ExecCtx(ctx, query, data.RoleId, data.DisplayName, data.Status, data.CreateTime, data.UpdateTime)
return ret, err
}
func (m *defaultRoleModel) Update(ctx context.Context, newData *Role) error {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, roleRowsWithPlaceHolder)
_, err := m.conn.ExecCtx(ctx, query, newData.RoleId, newData.DisplayName, newData.Status, newData.CreateTime, newData.UpdateTime, newData.Id)
return err
}
func (m *defaultRoleModel) tableName() string {
return m.table
}

View File

@ -0,0 +1,44 @@
package model
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ RolePermissionModel = (*customRolePermissionModel)(nil)
type (
// RolePermissionModel is an interface to be customized, add more methods here,
// and implement the added methods in customRolePermissionModel.
RolePermissionModel interface {
rolePermissionModel
FindOneByRoleID(ctx context.Context, roleID string) ([]*RolePermission, error)
}
customRolePermissionModel struct {
*defaultRolePermissionModel
}
)
// NewRolePermissionModel returns a model for the database table.
func NewRolePermissionModel(conn sqlx.SqlConn) RolePermissionModel {
return &customRolePermissionModel{
defaultRolePermissionModel: newRolePermissionModel(conn),
}
}
func (m *customRolePermissionModel) FindOneByRoleID(ctx context.Context, roleID string) ([]*RolePermission, error) {
var resp []*RolePermission
query := fmt.Sprintf("select %s from %s where `role_id` = ?", userRoleRows, m.table)
err := m.conn.QueryRowsCtx(ctx, &resp, query, roleID)
switch err {
case nil:
return resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}

View File

@ -0,0 +1,94 @@
// Code generated by goctl. DO NOT EDIT.
package model
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx"
)
var (
rolePermissionFieldNames = builder.RawFieldNames(&RolePermission{})
rolePermissionRows = strings.Join(rolePermissionFieldNames, ",")
rolePermissionRowsExpectAutoSet = strings.Join(stringx.Remove(rolePermissionFieldNames, "`id`"), ",")
rolePermissionRowsWithPlaceHolder = strings.Join(stringx.Remove(rolePermissionFieldNames, "`id`"), "=?,") + "=?"
)
type (
rolePermissionModel interface {
Insert(ctx context.Context, data *RolePermission) (sql.Result, error)
FindOne(ctx context.Context, id int64) (*RolePermission, error)
Update(ctx context.Context, data *RolePermission) error
Delete(ctx context.Context, id int64) error
}
defaultRolePermissionModel struct {
conn sqlx.SqlConn
table string
}
RolePermission struct {
Id int64 `db:"id"` // PK
RoleId sql.NullInt64 `db:"role_id"` // role.id
PermissionId sql.NullInt64 `db:"permission_id"` // permission.id
CreateTime int64 `db:"create_time"` // 創建時間
UpdateTime int64 `db:"update_time"` // 更新時間
}
)
func newRolePermissionModel(conn sqlx.SqlConn) *defaultRolePermissionModel {
return &defaultRolePermissionModel{
conn: conn,
table: "`role_permission`",
}
}
func (m *defaultRolePermissionModel) withSession(session sqlx.Session) *defaultRolePermissionModel {
return &defaultRolePermissionModel{
conn: sqlx.NewSqlConnFromSession(session),
table: "`role_permission`",
}
}
func (m *defaultRolePermissionModel) Delete(ctx context.Context, id int64) error {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
_, err := m.conn.ExecCtx(ctx, query, id)
return err
}
func (m *defaultRolePermissionModel) FindOne(ctx context.Context, id int64) (*RolePermission, error) {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", rolePermissionRows, m.table)
var resp RolePermission
err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultRolePermissionModel) Insert(ctx context.Context, data *RolePermission) (sql.Result, error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?)", m.table, rolePermissionRowsExpectAutoSet)
ret, err := m.conn.ExecCtx(ctx, query, data.RoleId, data.PermissionId, data.CreateTime, data.UpdateTime)
return ret, err
}
func (m *defaultRolePermissionModel) Update(ctx context.Context, data *RolePermission) error {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, rolePermissionRowsWithPlaceHolder)
_, err := m.conn.ExecCtx(ctx, query, data.RoleId, data.PermissionId, data.CreateTime, data.UpdateTime, data.Id)
return err
}
func (m *defaultRolePermissionModel) tableName() string {
return m.table
}

View File

@ -0,0 +1,26 @@
package model
import (
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ UserRoleModel = (*customUserRoleModel)(nil)
type (
// UserRoleModel is an interface to be customized, add more methods here,
// and implement the added methods in customUserRoleModel.
UserRoleModel interface {
userRoleModel
}
customUserRoleModel struct {
*defaultUserRoleModel
}
)
// NewUserRoleModel returns a model for the database table.
func NewUserRoleModel(conn sqlx.SqlConn) UserRoleModel {
return &customUserRoleModel{
defaultUserRoleModel: newUserRoleModel(conn),
}
}

View File

@ -0,0 +1,111 @@
// Code generated by goctl. DO NOT EDIT.
package model
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx"
)
var (
userRoleFieldNames = builder.RawFieldNames(&UserRole{})
userRoleRows = strings.Join(userRoleFieldNames, ",")
userRoleRowsExpectAutoSet = strings.Join(stringx.Remove(userRoleFieldNames, "`id`"), ",")
userRoleRowsWithPlaceHolder = strings.Join(stringx.Remove(userRoleFieldNames, "`id`"), "=?,") + "=?"
)
type (
userRoleModel interface {
Insert(ctx context.Context, data *UserRole) (sql.Result, error)
FindOne(ctx context.Context, id int64) (*UserRole, error)
FindOneByUid(ctx context.Context, uid string) (*UserRole, error)
Update(ctx context.Context, data *UserRole) error
Delete(ctx context.Context, id int64) error
}
defaultUserRoleModel struct {
conn sqlx.SqlConn
table string
}
UserRole struct {
Id int64 `db:"id"` // PK
Brand string `db:"brand"`
Uid string `db:"uid"`
RoleId string `db:"role_id"`
Status int64 `db:"status"` // 狀態 1: 啟用, 2: 禁用
CreateTime int64 `db:"create_time"` // 創建時間
UpdateTime int64 `db:"update_time"` // 更新時間
}
)
func newUserRoleModel(conn sqlx.SqlConn) *defaultUserRoleModel {
return &defaultUserRoleModel{
conn: conn,
table: "`user_role`",
}
}
func (m *defaultUserRoleModel) withSession(session sqlx.Session) *defaultUserRoleModel {
return &defaultUserRoleModel{
conn: sqlx.NewSqlConnFromSession(session),
table: "`user_role`",
}
}
func (m *defaultUserRoleModel) Delete(ctx context.Context, id int64) error {
query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
_, err := m.conn.ExecCtx(ctx, query, id)
return err
}
func (m *defaultUserRoleModel) FindOne(ctx context.Context, id int64) (*UserRole, error) {
query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRoleRows, m.table)
var resp UserRole
err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUserRoleModel) FindOneByUid(ctx context.Context, uid string) (*UserRole, error) {
var resp UserRole
query := fmt.Sprintf("select %s from %s where `uid` = ? limit 1", userRoleRows, m.table)
err := m.conn.QueryRowCtx(ctx, &resp, query, uid)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUserRoleModel) Insert(ctx context.Context, data *UserRole) (sql.Result, error) {
query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?)", m.table, userRoleRowsExpectAutoSet)
ret, err := m.conn.ExecCtx(ctx, query, data.Brand, data.Uid, data.RoleId, data.Status, data.CreateTime, data.UpdateTime)
return ret, err
}
func (m *defaultUserRoleModel) Update(ctx context.Context, newData *UserRole) error {
query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, userRoleRowsWithPlaceHolder)
_, err := m.conn.ExecCtx(ctx, query, newData.Brand, newData.Uid, newData.RoleId, newData.Status, newData.CreateTime, newData.UpdateTime, newData.Id)
return err
}
func (m *defaultUserRoleModel) tableName() string {
return m.table
}

View File

@ -28,10 +28,10 @@ func (s *PermissionServiceServer) ListPermissionStatus(ctx context.Context, in *
return l.ListPermissionStatus(in) return l.ListPermissionStatus(in)
} }
// MapPermissionStatus 取得所有權限開閉狀態,簡易版,給前端表演用 // ListPermission 一次性取得所有權限表
func (s *PermissionServiceServer) MapPermissionStatus(ctx context.Context, in *permission.NoneReq) (*permission.MapPermissionStatusResp, error) { func (s *PermissionServiceServer) ListPermission(ctx context.Context, in *permission.NoneReq) (*permission.MapPermissionStatusResp, error) {
l := permissionservicelogic.NewMapPermissionStatusLogic(ctx, s.svcCtx) l := permissionservicelogic.NewListPermissionLogic(ctx, s.svcCtx)
return l.MapPermissionStatus(in) return l.ListPermission(in)
} }
// CheckPermissionByRole 透過角色 ID 來檢視權限,後台要通過時真的看這個 // CheckPermissionByRole 透過角色 ID 來檢視權限,後台要通過時真的看這個

View File

@ -22,7 +22,20 @@ func NewRoleServiceServer(svcCtx *svc.ServiceContext) *RoleServiceServer {
} }
} }
func (s *RoleServiceServer) Ping(ctx context.Context, in *permission.OKResp) (*permission.OKResp, error) { // CreateRole 建立角色
l := roleservicelogic.NewPingLogic(ctx, s.svcCtx) func (s *RoleServiceServer) CreateRole(ctx context.Context, in *permission.CreateRoleReq) (*permission.RoleResp, error) {
return l.Ping(in) l := roleservicelogic.NewCreateRoleLogic(ctx, s.svcCtx)
return l.CreateRole(in)
}
// GetRole 取得搜尋的角色
func (s *RoleServiceServer) GetRole(ctx context.Context, in *permission.GetRoleReq) (*permission.GetRoleResp, error) {
l := roleservicelogic.NewGetRoleLogic(ctx, s.svcCtx)
return l.GetRole(in)
}
// UpdateRole 更新角色
func (s *RoleServiceServer) UpdateRole(ctx context.Context, in *permission.UpdateRoleReq) (*permission.RoleResp, error) {
l := roleservicelogic.NewUpdateRoleLogic(ctx, s.svcCtx)
return l.UpdateRole(in)
} }

View File

@ -0,0 +1,47 @@
// Code generated by goctl. DO NOT EDIT.
// Source: permission.proto
package server
import (
"context"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/logic/userroleservice"
"ark-permission/internal/svc"
)
type UserRoleServiceServer struct {
svcCtx *svc.ServiceContext
permission.UnimplementedUserRoleServiceServer
}
func NewUserRoleServiceServer(svcCtx *svc.ServiceContext) *UserRoleServiceServer {
return &UserRoleServiceServer{
svcCtx: svcCtx,
}
}
// CreateUserRole 建立角色
func (s *UserRoleServiceServer) CreateUserRole(ctx context.Context, in *permission.UserRoleReq) (*permission.UserRoleResp, error) {
l := userroleservicelogic.NewCreateUserRoleLogic(ctx, s.svcCtx)
return l.CreateUserRole(in)
}
// UpdateRole 更新角色
func (s *UserRoleServiceServer) UpdateUserRole(ctx context.Context, in *permission.UserRoleReq) (*permission.UserRoleResp, error) {
l := userroleservicelogic.NewUpdateUserRoleLogic(ctx, s.svcCtx)
return l.UpdateUserRole(in)
}
// GetUserRole 取得角色綁定表,沒有搜尋條件就全部,不分頁
func (s *UserRoleServiceServer) GetUserRole(ctx context.Context, in *permission.UserRoleReq) (*permission.GetUserRoleResp, error) {
l := userroleservicelogic.NewGetUserRoleLogic(ctx, s.svcCtx)
return l.GetUserRole(in)
}
// GetUserPermission 取得角色權限
func (s *UserRoleServiceServer) GetUserPermission(ctx context.Context, in *permission.UserPermissionReq) (*permission.UserPermissionResp, error) {
l := userroleservicelogic.NewGetUserPermissionLogic(ctx, s.svcCtx)
return l.GetUserPermission(in)
}

View File

@ -2,8 +2,10 @@ package svc
import ( import (
"ark-permission/internal/config" "ark-permission/internal/config"
"ark-permission/internal/domain"
"ark-permission/internal/domain/repository" "ark-permission/internal/domain/repository"
domainUseCase "ark-permission/internal/domain/usecase" domainUseCase "ark-permission/internal/domain/usecase"
"ark-permission/internal/entity"
"ark-permission/internal/lib/required" "ark-permission/internal/lib/required"
"ark-permission/internal/model" "ark-permission/internal/model"
repo "ark-permission/internal/repository" repo "ark-permission/internal/repository"
@ -21,8 +23,13 @@ type ServiceContext struct {
Validate required.Validate Validate required.Validate
Redis redis.Redis Redis redis.Redis
TokenRedisRepo repository.TokenRepository TokenRedisRepo repository.TokenRepository
Permission model.PermissionModel
PolicyAgent domainUseCase.OpaUseCase PolicyAgent domainUseCase.OpaUseCase
PermissionTree usecase.PermissionTree
Conn sqlx.SqlConn
Permission model.PermissionModel
RoleRepo model.RoleModel
RolePermissionRepo model.RolePermissionModel
} }
func NewServiceContext(c config.Config) *ServiceContext { func NewServiceContext(c config.Config) *ServiceContext {
@ -44,6 +51,30 @@ func NewServiceContext(c config.Config) *ServiceContext {
panic(err) panic(err)
} }
t := usecase.NewPermissionTree()
pm := model.NewPermissionModel(sqlConn)
permission, err := pm.FindAllOpenPermission(context.Background())
if err != nil {
panic(err)
}
for _, item := range permission {
err := t.AddPermission(item.Id, entity.Permission{
ID: item.Id,
Parent: item.Parent.Int64,
Name: item.Name,
HTTPPath: item.HttpPath,
HTTPMethod: item.HttpMethod,
Status: int(item.Status),
Type: domain.PermissionType(item.Type),
CreateTime: item.CreateTime,
UpdateTime: item.UpdateTime,
})
if err != nil {
continue
}
}
return &ServiceContext{ return &ServiceContext{
Config: c, Config: c,
Validate: required.MustValidator(), Validate: required.MustValidator(),
@ -51,7 +82,11 @@ func NewServiceContext(c config.Config) *ServiceContext {
TokenRedisRepo: repo.NewTokenRepository(repo.TokenRepositoryParam{ TokenRedisRepo: repo.NewTokenRepository(repo.TokenRepositoryParam{
Store: newRedis, Store: newRedis,
}), }),
Permission: model.NewPermissionModel(sqlConn),
PolicyAgent: pa, PolicyAgent: pa,
PermissionTree: *t,
Permission: pm,
RoleRepo: model.NewRoleModel(sqlConn),
RolePermissionRepo: model.NewRolePermissionModel(sqlConn),
Conn: sqlConn,
} }
} }