2023-07-06 10:23:43 +00:00
|
|
|
package svc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"fusenapi/server/upload/internal/config"
|
2023-08-09 08:54:52 +00:00
|
|
|
"fusenapi/shared"
|
2023-07-06 10:23:43 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"fusenapi/initalize"
|
|
|
|
"fusenapi/model/gmodel"
|
|
|
|
|
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
|
|
"github.com/aws/aws-sdk-go/aws/credentials"
|
|
|
|
"github.com/aws/aws-sdk-go/aws/session"
|
|
|
|
"github.com/golang-jwt/jwt"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ServiceContext struct {
|
2023-07-25 11:32:51 +00:00
|
|
|
Config config.Config
|
2023-08-09 08:54:52 +00:00
|
|
|
SharedState *shared.SharedState
|
2023-07-06 10:23:43 +00:00
|
|
|
|
2023-08-23 03:09:14 +00:00
|
|
|
MysqlConn *gorm.DB
|
|
|
|
AllModels *gmodel.AllModelsGen
|
|
|
|
AwsSession *session.Session
|
|
|
|
Repositories *initalize.Repositories
|
2023-07-06 10:23:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewServiceContext(c config.Config) *ServiceContext {
|
|
|
|
|
|
|
|
config := aws.Config{
|
|
|
|
Credentials: credentials.NewStaticCredentials(c.AWS.S3.Credentials.AccessKeyID, c.AWS.S3.Credentials.Secret, c.AWS.S3.Credentials.Token),
|
|
|
|
}
|
|
|
|
|
|
|
|
// config.Region = aws.String("us-west-1")
|
|
|
|
|
|
|
|
return &ServiceContext{
|
|
|
|
Config: c,
|
|
|
|
MysqlConn: initalize.InitMysql(c.SourceMysql),
|
|
|
|
AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)),
|
|
|
|
AwsSession: session.Must(session.NewSession(&config)),
|
2023-08-23 03:09:14 +00:00
|
|
|
Repositories: initalize.NewAllRepositories(&initalize.NewAllRepositorieData{
|
|
|
|
GormDB: initalize.InitMysql(c.SourceMysql),
|
|
|
|
BLMServiceUrl: &c.BLMService.Url,
|
|
|
|
AwsSession: session.Must(session.NewSession(&config)),
|
|
|
|
}),
|
2023-07-06 10:23:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
|
|
|
|
AuthKey := r.Header.Get("Authorization")
|
|
|
|
if AuthKey == "" {
|
|
|
|
return nil, nil
|
|
|
|
}
|
2023-07-10 09:54:10 +00:00
|
|
|
AuthKey = AuthKey[7:]
|
2023-07-06 10:23:43 +00:00
|
|
|
|
|
|
|
if len(AuthKey) <= 50 {
|
|
|
|
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
|
|
|
|
}
|
|
|
|
|
|
|
|
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))
|
|
|
|
}
|