Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd95b8d8b1 | ||
|
|
dd9a692858 | ||
|
|
b5374b85ff | ||
|
|
5172824358 | ||
|
|
51ff7d1ffd | ||
|
|
c7f24e3b6d | ||
| f7948263c5 | |||
| fc42bc92ff |
@@ -1,12 +1,13 @@
|
||||
package conf
|
||||
|
||||
type Base struct {
|
||||
Service string `yaml:"Service"` // 服务名称
|
||||
Port string `yaml:"Port"` // 服务监听端口,0为自动随机端口
|
||||
Cache string `yaml:"Cache"` // REDIS缓存
|
||||
SecretKey string `yaml:"SecretKey"` // 服务秘钥
|
||||
BindIP string `yaml:"BindIP"` // 绑定IP
|
||||
Addr string `yaml:"Addr"`
|
||||
Service string `yaml:"Service"` // 服务名称
|
||||
Port string `yaml:"Port"` // 服务监听端口,0为自动随机端口
|
||||
Cache string `yaml:"Cache"` // REDIS缓存
|
||||
SecretKey string `yaml:"SecretKey"` // 服务秘钥
|
||||
BindIP string `yaml:"BindIP"` // 绑定IP
|
||||
Addr string `yaml:"Addr"`
|
||||
OnMicroService bool `yaml:"OnMicroService"`
|
||||
}
|
||||
|
||||
type DBConf struct {
|
||||
@@ -48,11 +49,14 @@ type RpcConf struct {
|
||||
}
|
||||
|
||||
type OssConf struct {
|
||||
Platform string `yaml:"Platform"` // oss平台:aliyun,tencent,huawei,aws,minio
|
||||
Site string `yaml:"Site"` // oss站点HOST
|
||||
Endpoint string `yaml:"Endpoint"` // oss服务接入地址
|
||||
Region string `yaml:"Region"` // oss服务区域
|
||||
AccessKeyID string `yaml:"AccessKeyId"` // oss AccessKeyId
|
||||
AccessKeySecret string `yaml:"AccessKeySecret"` // oss AccessKeySecret
|
||||
UseSSL bool `yaml:"UseSSL"` // 是否使用SSL
|
||||
|
||||
}
|
||||
|
||||
type MqConf struct {
|
||||
|
||||
@@ -17,14 +17,14 @@ var (
|
||||
|
||||
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)
|
||||
grantResp, err := lease.Grant(context.TODO(), 5)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
serviceAddr := utils.GetLocationIP() + ":" + utils.Int2String(port)
|
||||
serviceAddr := utils.GetLocationIP() + ":" + port
|
||||
|
||||
key := RootPrefix + serviceName + "/" + utils.Int642String(time.Now().UnixNano())
|
||||
_, err = cli.KV.Put(context.TODO(), key, serviceAddr, clientv3.WithLease(grantResp.ID))
|
||||
|
||||
73
middleware/jwt.go
Normal file
73
middleware/jwt.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"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
|
||||
}
|
||||
@@ -2,81 +2,57 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"git.apinb.com/bsm-sdk/core/crypto/encipher"
|
||||
"git.apinb.com/bsm-sdk/core/errcode"
|
||||
"git.apinb.com/bsm-sdk/core/types"
|
||||
"git.apinb.com/bsm-sdk/core/utils"
|
||||
"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"`
|
||||
}
|
||||
|
||||
// 解析Context中MetaData的数据
|
||||
type ParseOptions struct {
|
||||
RoleValue string // 判断角色的值
|
||||
MustPrivateAllow bool // 是否只允许私有IP访问
|
||||
}
|
||||
|
||||
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*Meta, error) {
|
||||
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, error) {
|
||||
// 解析metada中的信息并验证
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errcode.ErrJWTAuthNotFound
|
||||
}
|
||||
|
||||
// 安全获取 metadata 中的值
|
||||
identityValues := md.Get("authorization_identity")
|
||||
clientValues := md.Get("client")
|
||||
|
||||
if len(identityValues) == 0 {
|
||||
return nil, errcode.ErrJWTAuthNotFound
|
||||
}
|
||||
if len(clientValues) == 0 {
|
||||
var Authorizations []string = md.Get("authorization")
|
||||
if len(Authorizations) == 0 || Authorizations[0] == "" {
|
||||
return nil, errcode.ErrJWTAuthNotFound
|
||||
}
|
||||
|
||||
meta := &Meta{
|
||||
IDENTITY: md["authorization_identity"][0],
|
||||
CLIENT: md["client"][0],
|
||||
}
|
||||
|
||||
if id, err := strconv.Atoi(md["authorization_id"][0]); err != nil {
|
||||
return nil, errcode.ErrJWTAuthKeyId
|
||||
} else {
|
||||
meta.ID = uint(id)
|
||||
}
|
||||
|
||||
data := make(map[string]string)
|
||||
if err := json.Unmarshal([]byte(md["authorization_extend"][0]), &data); err == nil {
|
||||
meta.EXTEND = data
|
||||
claims, err := encipher.ParseTokenAes(Authorizations[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if opts != nil {
|
||||
if !meta.CheckRole("role", opts.RoleValue) {
|
||||
if !checkRole(claims, "role", opts.RoleValue) {
|
||||
return nil, errcode.ErrPermissionDenied
|
||||
}
|
||||
if opts.MustPrivateAllow {
|
||||
if utils.IsPublicIP(meta.CLIENT) {
|
||||
if utils.IsPublicIP(claims.Client) {
|
||||
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 == "" {
|
||||
return true
|
||||
}
|
||||
if role, exists := m.EXTEND[roleKey]; !exists || role != roleValue {
|
||||
if role, exists := claims.Extend[roleKey]; !exists || role != roleValue {
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
|
||||
@@ -31,7 +31,7 @@ type (
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_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.
|
||||
|
||||
Reference in New Issue
Block a user