fusenapi/server/backend/internal/svc/servicecontext.go

63 lines
1.5 KiB
Go
Raw Normal View History

2023-06-25 10:30:39 +00:00
package svc
import (
"errors"
"fmt"
2023-07-25 11:32:51 +00:00
"fusenapi/fsm"
2023-06-25 10:30:39 +00:00
"fusenapi/server/backend/internal/config"
"net/http"
2023-06-27 10:09:56 +00:00
"time"
2023-06-25 10:30:39 +00:00
"fusenapi/initalize"
"fusenapi/model/gmodel"
"github.com/golang-jwt/jwt"
"gorm.io/gorm"
)
type ServiceContext struct {
2023-07-25 11:32:51 +00:00
Config config.Config
2023-07-30 16:41:04 +00:00
SharedState *fsm.SharedState
2023-06-25 10:30:39 +00:00
MysqlConn *gorm.DB
AllModels *gmodel.AllModelsGen
}
func NewServiceContext(c config.Config) *ServiceContext {
2023-06-27 10:09:56 +00:00
db := initalize.InitMysql(c.SourceMysql).Set("gorm:slow_query_time", time.Second*15)
2023-06-25 10:30:39 +00:00
return &ServiceContext{
Config: c,
MysqlConn: initalize.InitMysql(c.SourceMysql),
2023-06-27 10:09:56 +00:00
AllModels: gmodel.NewAllModels(db),
2023-06-25 10:30:39 +00:00
}
}
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}
2023-07-10 09:54:10 +00:00
AuthKey = AuthKey[7:]
2023-06-25 10:30:39 +00:00
token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) {
// 检查签名方法是否为 HS256
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// 返回用于验证签名的密钥
return []byte(svcCtx.Config.Auth.AccessSecret), nil
})
if err != nil {
return nil, errors.New(fmt.Sprint("Error parsing token:", err))
}
// 验证成功返回
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New(fmt.Sprint("Invalid token", err))
}