Compare commits

...

17 Commits

Author SHA1 Message Date
zhaoxiaorong 21f09ea41e fix 2025-04-24 17:52:29 +08:00
yanweidong 4d06ad3e8b add err code 2025-04-19 20:14:37 +08:00
yanweidong 52a81a404e fix infra response 2025-04-18 19:11:50 +08:00
yanweidong 6cd06d86bc add std_owner 2025-04-17 17:18:58 +08:00
zhaoxiaorong ca9f7047c6 fix 兼容性调整 2025-04-15 21:49:17 +08:00
zhaoxiaorong 2de73fea00 fix 兼容性调整 2025-04-15 20:50:28 +08:00
zhaoxiaorong 4b73f086b1 dev oplog 2025-04-11 18:14:07 +08:00
zhaoxiaorong c08950c10a fix 2025-04-11 18:06:08 +08:00
zhaoxiaorong d691648916 fix 2025-04-11 17:53:50 +08:00
zhaoxiaorong 8060cdb508 fix 2025-04-11 17:50:06 +08:00
zhaoxiaorong 50c23df124 fix 2025-04-11 17:44:49 +08:00
zhaoxiaorong 04b8e5b03b fix 2025-04-11 16:45:11 +08:00
zhaoxiaorong dd95b8d8b1 fix 2025-04-09 15:24:28 +08:00
zhaoxiaorong dd9a692858 fix 2025-04-09 11:12:42 +08:00
zhaoxiaorong b5374b85ff fix 2025-04-09 10:56:49 +08:00
zhaoxiaorong 5172824358 fix 2025-04-09 10:34:01 +08:00
zhaoxiaorong 51ff7d1ffd fix 2025-04-09 10:19:15 +08:00
9 changed files with 162 additions and 57 deletions

View File

@ -1,12 +1,14 @@
package conf package conf
type Base struct { type Base struct {
Service string `yaml:"Service"` // 服务名称 Service string `yaml:"Service"` // 服务名称
Port string `yaml:"Port"` // 服务监听端口,0为自动随机端口 Port string `yaml:"Port"` // 服务监听端口,0为自动随机端口
Cache string `yaml:"Cache"` // REDIS缓存 Cache string `yaml:"Cache"` // REDIS缓存
SecretKey string `yaml:"SecretKey"` // 服务秘钥 SecretKey string `yaml:"SecretKey"` // 服务秘钥
BindIP string `yaml:"BindIP"` // 绑定IP BindIP string `yaml:"BindIP"` // 绑定IP
Addr string `yaml:"Addr"` Addr string `yaml:"Addr"`
OnMicroService bool `yaml:"OnMicroService"`
LoginUrl string `yaml:"LoginUrl"`
} }
type DBConf struct { type DBConf struct {
@ -48,11 +50,14 @@ type RpcConf struct {
} }
type OssConf struct { type OssConf struct {
Platform string `yaml:"Platform"` // oss平台aliyun,tencent,huawei,aws,minio
Site string `yaml:"Site"` // oss站点HOST Site string `yaml:"Site"` // oss站点HOST
Endpoint string `yaml:"Endpoint"` // oss服务接入地址 Endpoint string `yaml:"Endpoint"` // oss服务接入地址
Region string `yaml:"Region"` // oss服务区域 Region string `yaml:"Region"` // oss服务区域
AccessKeyID string `yaml:"AccessKeyId"` // oss AccessKeyId AccessKeyID string `yaml:"AccessKeyId"` // oss AccessKeyId
AccessKeySecret string `yaml:"AccessKeySecret"` // oss AccessKeySecret AccessKeySecret string `yaml:"AccessKeySecret"` // oss AccessKeySecret
UseSSL bool `yaml:"UseSSL"` // 是否使用SSL
} }
type MqConf struct { type MqConf struct {

View File

@ -15,13 +15,18 @@ var (
// standard error code ,start:110 // standard error code ,start:110
var ( var (
ErrEmpty = NewError(110, "Data Is Empty") ErrEmpty = NewError(110, "Data Is Empty")
ErrRequestParse = NewError(111, "Request Parse Fail") ErrRequestParse = NewError(111, "Request Parse Fail")
ErrRequestMust = NewError(112, "Request Params Required") ErrRequestMust = NewError(112, "Request Params Required")
ErrPermission = NewError(113, "Permission Denied") ErrPermission = NewError(113, "Permission Denied")
ErrJsonUnmarshal = NewError(114, "Json Unmarshal Fail") ErrJsonUnmarshal = NewError(114, "Json Unmarshal Fail")
ErrJsonMarshal = NewError(115, "Json Marshal Fail") ErrJsonMarshal = NewError(115, "Json Marshal Fail")
ErrInternal = NewError(116, "Internal Server Error") ErrInternal = NewError(116, "Internal Server Error")
ErrPassword = NewError(117, "Password Incorrect")
ErrAccountNotFound = NewError(118, "Account Not Found")
ErrAccountDisabled = NewError(119, "Account Disabled")
ErrDisabled = NewError(120, "Status Disabled")
ErrRecordNotFound = NewError(121, "Record Not Found")
) )
// jwt error code ,start:130 // jwt error code ,start:130

View File

@ -8,29 +8,29 @@ import (
var Response Reply var Response Reply
type Reply struct { type Reply struct {
Code int `json:"code"` Code int32 `json:"code"`
Msg string `json:"msg"` Message string `json:"message"`
Data any `json:"data"` Result any `json:"result"`
} }
func (reply *Reply) Success(ctx *gin.Context, data any) { func (reply *Reply) Success(ctx *gin.Context, data any) {
reply.Code = 200 reply.Code = 0
reply.Data = data reply.Result = data
reply.Msg = "" reply.Message = ""
if data == nil { if data == nil {
reply.Data = "" reply.Result = ""
} }
ctx.JSON(200, reply) ctx.JSON(200, reply)
} }
func (reply *Reply) Error(ctx *gin.Context, err error) { func (reply *Reply) Error(ctx *gin.Context, err error) {
reply.Code = 500 reply.Code = 500
reply.Data = "" reply.Result = ""
// Status code defaults to 500 // Status code defaults to 500
e, ok := status.FromError(err) e, ok := status.FromError(err)
if ok { if ok {
reply.Code = int(e.Code()) reply.Code = int32(e.Code())
} }
reply.Msg = e.Message() reply.Message = e.Message()
// Send error // Send error
ctx.JSON(200, reply) ctx.JSON(200, reply)

View File

@ -17,14 +17,14 @@ var (
type service struct{} type service struct{}
func (s *service) Register(cli *clientv3.Client, serviceName string, port int) error { func (s *service) Register(cli *clientv3.Client, serviceName string, port string) error {
lease := clientv3.NewLease(cli) lease := clientv3.NewLease(cli)
grantResp, err := lease.Grant(context.TODO(), 5) grantResp, err := lease.Grant(context.TODO(), 5)
if err != nil { if err != nil {
return err return err
} }
serviceAddr := utils.GetLocationIP() + ":" + utils.Int2String(port) serviceAddr := utils.GetLocationIP() + ":" + port
key := RootPrefix + serviceName + "/" + utils.Int642String(time.Now().UnixNano()) key := RootPrefix + serviceName + "/" + utils.Int642String(time.Now().UnixNano())
_, err = cli.KV.Put(context.TODO(), key, serviceAddr, clientv3.WithLease(grantResp.ID)) _, err = cli.KV.Put(context.TODO(), key, serviceAddr, clientv3.WithLease(grantResp.ID))

72
middleware/jwt.go Normal file
View File

@ -0,0 +1,72 @@
package middleware
import (
"encoding/json"
"log"
"net/http"
"git.apinb.com/bsm-sdk/core/cache/redis"
"git.apinb.com/bsm-sdk/core/crypto/encipher"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/types"
"github.com/gin-gonic/gin"
)
func JwtAuth(redis *redis.RedisClient) gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头中获取 Authorization
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
log.Println("获取token异常:", "Authorization header is required")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
c.Abort()
return
}
// 提取Token
claims, err := encipher.ParseTokenAes(authHeader)
if err != nil || claims == nil {
log.Println("提取token异常:", "Token is required")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is required"})
c.Abort()
return
}
// 从redis 获取token,判断当前redis 是否为空
// tokenKey := fmt.Sprintf("%d-%s-%s", claims.ID, claims.Role, "token")
// redisToken := redis.Client.Get(redis.Ctx, tokenKey)
// if redisToken.Val() == "" {
// log.Println("redis异常", "Token status unauthorized")
// c.JSON(http.StatusUnauthorized, gin.H{"error": "Token status unauthorized"})
// c.Abort()
// return
// }
// 将解析后的 Token 存储到上下文中
c.Set("Auth", claims)
// 如果 Token 有效,继续处理请求
c.Next()
}
}
// 获取上下文用户登录信息
func ParseAuth(c *gin.Context) (*types.JwtClaims, error) {
claims, ok := c.Get("Auth")
if !ok {
log.Printf("获取登录信息异常: %v", errcode.ErrJWTAuthNotFound)
return nil, errcode.ErrJWTAuthNotFound
}
json_claims, err := json.Marshal(claims)
if err != nil {
log.Printf("解析json异常: %v", err)
return nil, errcode.ErrJsonMarshal
}
var auth *types.JwtClaims
if err := json.Unmarshal(json_claims, &auth); err != nil {
log.Printf("解析json异常: %v", err)
return nil, errcode.ErrJsonUnmarshal
}
return auth, nil
}

14
oplog/new.go Normal file
View File

@ -0,0 +1,14 @@
package oplog
import (
"encoding/json"
"git.apinb.com/bsm-sdk/core/utils"
)
func New(endpoint string, data []*LogItem) {
jsonBytes, _ := json.Marshal(data)
go utils.HttpPost(endpoint, nil, jsonBytes)
}

18
oplog/types.go Normal file
View File

@ -0,0 +1,18 @@
package oplog
type LogItem struct {
OpID uint `json:"op_id"`
OpName string `json:"op_name"`
OpType string `json:"op_type"`
Text string `json:"text"`
}
var (
Type_Login string = "login"
Type_Logout string = "logout"
Type_Register string = "register"
Type_Update string = "update"
Type_Delete string = "delete"
Type_Query string = "query"
Type_Other string = "other"
)

View File

@ -5,25 +5,18 @@ import (
"git.apinb.com/bsm-sdk/core/crypto/encipher" "git.apinb.com/bsm-sdk/core/crypto/encipher"
"git.apinb.com/bsm-sdk/core/errcode" "git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/types"
"git.apinb.com/bsm-sdk/core/utils" "git.apinb.com/bsm-sdk/core/utils"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
) )
type Meta struct {
ID uint `json:"id"`
IDENTITY string `json:"identity"`
EXTEND map[string]string `json:"extend"`
CLIENT string `json:"client"`
ROLE string `json:"role"`
}
// 解析Context中MetaData的数据 // 解析Context中MetaData的数据
type ParseOptions struct { type ParseOptions struct {
RoleValue string // 判断角色的值 RoleValue string // 判断角色的值
MustPrivateAllow bool // 是否只允许私有IP访问 MustPrivateAllow bool // 是否只允许私有IP访问
} }
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*Meta, error) { func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, error) {
// 解析metada中的信息并验证 // 解析metada中的信息并验证
md, ok := metadata.FromIncomingContext(ctx) md, ok := metadata.FromIncomingContext(ctx)
if !ok { if !ok {
@ -40,34 +33,26 @@ func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*Meta, error) {
return nil, err return nil, err
} }
meta := &Meta{
ID: claims.ID,
IDENTITY: claims.Identity,
CLIENT: claims.Client,
EXTEND: claims.Extend,
ROLE: claims.Role,
}
if opts != nil { if opts != nil {
if !meta.CheckRole("role", opts.RoleValue) { if !checkRole(claims, "role", opts.RoleValue) {
return nil, errcode.ErrPermissionDenied return nil, errcode.ErrPermissionDenied
} }
if opts.MustPrivateAllow { if opts.MustPrivateAllow {
if utils.IsPublicIP(meta.CLIENT) { if utils.IsPublicIP(claims.Client) {
return nil, errcode.ErrPermissionDenied return nil, errcode.ErrPermissionDenied
} }
} }
} }
return meta, nil return claims, nil
} }
func (m *Meta) CheckRole(roleKey, roleValue string) bool { func checkRole(claims *types.JwtClaims, roleKey, roleValue string) bool {
if roleValue == "" { if roleValue == "" {
return true return true
} }
if role, exists := m.EXTEND[roleKey]; !exists || role != roleValue { if role, exists := claims.Extend[roleKey]; !exists || role != roleValue {
return false return false
} else { } else {
return true return true

View File

@ -21,37 +21,43 @@ type (
// standard ID,Identity definition. // standard ID,Identity definition.
Std_IDIdentity struct { Std_IDIdentity struct {
ID uint `gorm:"primarykey;" json:"id"` ID uint `gorm:"primarykey;" json:"id"`
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;default:uuid_generate_v4()" json:"identity"` // 唯一标识24位NanoID,36位为ULID Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为ULID
} }
// standard ID,Created,Updated,Deleted definition. // standard ID,Created,Updated,Deleted definition.
Std_IICUDS struct { Std_IICUDS struct {
ID uint `gorm:"primarykey;" json:"id"` ID uint `gorm:"primarykey;" json:"id"`
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;default:uuid_generate_v4()" json:"identity"` // 唯一标识24位NanoID,36位为ULID Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为ULID
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `gorm:"" json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `gorm:"" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"` DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
Status int64 `gorm:"default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常 Status int8 `gorm:"default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
} }
// standard ID,Identity,Created,Updated,Deleted,Status definition. // standard ID,Identity,Created,Updated,Deleted,Status definition.
Std_ICUD struct { Std_ICUD struct {
ID uint `gorm:"primarykey;" json:"id"` ID uint `gorm:"primarykey;" json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `gorm:"" json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `gorm:"" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"` DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
} }
// standard ID,Created definition. // standard ID,Created definition.
Std_IdCreated struct { Std_IdCreated struct {
ID uint `gorm:"primarykey;" json:"id"` ID uint `gorm:"primarykey;" json:"id"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `gorm:"" json:"created_at"`
} }
// standard PassportID,PassportIdentity definition. // standard PassportID,PassportIdentity definition.
Std_Passport struct { Std_Passport struct {
PassportID uint `gorm:"column:passport_id;Index;" json:"passport_id"` PassportID uint `gorm:"column:passport_id;Index;" json:"passport_id"`
PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;default:uuid_generate_v4()" json:"passport_identity"` // 用户唯一标识24位NanoID,36位为ULID PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;" json:"passport_identity"` // 用户唯一标识24位NanoID,36位为UUID
}
// standard OwnerID,OwnerIdentity definition.
Std_Owner struct {
OwnerID uint `gorm:"column:owner_id;Index;" json:"owner_id"`
OwnerIdentity string `gorm:"column:owner_identity;type:varchar(36);Index;" json:"owner_identity"` // 用户唯一标识24位NanoID,36位为UUID
} }
// standard ID definition. // standard ID definition.
@ -61,7 +67,7 @@ type (
// standard Identity definition. // standard Identity definition.
Std_Identity struct { Std_Identity struct {
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;default:uuid_generate_v4()" json:"identity"` // 唯一标识24位NanoID,36位为ULID Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为UUID
} }
// standard Status definition. // standard Status definition.