Skip to content

Commit

Permalink
feat: 添加cos令牌发放
Browse files Browse the repository at this point in the history
  • Loading branch information
Lansongxx committed Jan 18, 2024
1 parent 50b07be commit a11bd6f
Show file tree
Hide file tree
Showing 10 changed files with 254 additions and 12 deletions.
13 changes: 13 additions & 0 deletions biz/adaptor/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@ import (
type StsServerImpl struct {
*config.Config
AuthService service.AuthService
CosService service.CosService
}

func (s *StsServerImpl) GenCosSts(ctx context.Context, req *sts.GenCosStsReq) (res *sts.GenCosStsResp, err error) {
return s.CosService.GenCosSts(ctx, req)
}

func (s *StsServerImpl) GenSignedUrl(ctx context.Context, req *sts.GenSignedUrlReq) (res *sts.GenSignedUrlResp, err error) {
return s.CosService.GenSignedUrl(ctx, req)
}

func (s *StsServerImpl) DeleteObject(ctx context.Context, req *sts.DeleteObjectReq) (res *sts.DeleteObjectResp, err error) {
return s.CosService.DeleteObject(ctx, req)
}

func (s *StsServerImpl) AppendAuth(ctx context.Context, req *sts.AppendAuthReq) (resp *sts.AppendAuthResp, err error) {
Expand Down
91 changes: 91 additions & 0 deletions biz/application/service/cos.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package service

import (
"context"
"fmt"
"github.com/CloudStriver/cloudmind-sts/biz/infrastructure/config"
"github.com/CloudStriver/cloudmind-sts/biz/infrastructure/util/sdk/cos"
gensts "github.com/CloudStriver/service-idl-gen-go/kitex_gen/cloudmind/sts"
"github.com/google/wire"
cossts "github.com/tencentyun/qcloud-cos-sts-sdk/go"
"github.com/xh-polaris/platform-sts/biz/infrastructure/consts"
"time"
)

type ICosService interface {
GenCosSts(ctx context.Context, req *gensts.GenCosStsReq) (*gensts.GenCosStsResp, error)
GenSignedUrl(ctx context.Context, req *gensts.GenSignedUrlReq) (*gensts.GenSignedUrlResp, error)
DeleteObject(ctx context.Context, req *gensts.DeleteObjectReq) (*gensts.DeleteObjectResp, error)
}

type CosService struct {
Config *config.Config
CosSDK *cos.CosSDK
}

var CosSet = wire.NewSet(
wire.Struct(new(CosService), "*"),
wire.Bind(new(ICosService), new(*CosService)),
)

func (s *CosService) GenCosSts(ctx context.Context, req *gensts.GenCosStsReq) (*gensts.GenCosStsResp, error) {
cosConfig := s.Config.CosConfig
stsOption := &cossts.CredentialOptions{
// 临时密钥有效时长,单位是秒
DurationSeconds: int64(10 * time.Minute.Seconds()),
Region: cosConfig.Region,
Policy: &cossts.CredentialPolicy{
Statement: []cossts.CredentialPolicyStatement{
{
// 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
Action: []string{
// 简单上传
"name/cos:PostObject",
"name/cos:PutObject",
// 分片上传
"name/cos:InitiateMultipartUpload",
"name/cos:ListMultipartUploads",
"name/cos:ListParts",
"name/cos:UploadPart",
"name/cos:CompleteMultipartUpload",
},
Effect: "allow",
// 密钥可控制的资源列表。此处开放名字为用户ID的文件夹及其子文件夹
Resource: []string{
fmt.Sprintf("qcs::cos:%s:uid/%s:%s/%s",
cosConfig.Region, cosConfig.AppId, cosConfig.BucketName, req.Path),
},
},
},
},
}

res, err := s.CosSDK.GetCredential(ctx, stsOption)
if err != nil {
return nil, err
}

return &gensts.GenCosStsResp{
SecretId: res.Credentials.TmpSecretID,
SecretKey: res.Credentials.TmpSecretKey,
SessionToken: res.Credentials.SessionToken,
ExpiredTime: int64(res.ExpiredTime),
StartTime: int64(res.StartTime),
}, nil
}

func (s *CosService) GenSignedUrl(ctx context.Context, req *gensts.GenSignedUrlReq) (*gensts.GenSignedUrlResp, error) {
signedUrl, err := s.CosSDK.GetPresignedURL(ctx, req.Method, req.Path, req.SecretId, req.SecretKey, time.Minute, nil)
if err != nil {
return nil, err
}
return &gensts.GenSignedUrlResp{SignedUrl: signedUrl.String()}, nil
}

func (s *CosService) DeleteObject(ctx context.Context, req *gensts.DeleteObjectReq) (*gensts.DeleteObjectResp, error) {
res, err := s.CosSDK.Delete(ctx, req.Path)
if err != nil || res.StatusCode != 200 {
return nil, consts.ErrCannotDeleteObject
}
return &gensts.DeleteObjectResp{}, nil
}
18 changes: 18 additions & 0 deletions biz/infrastructure/config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"fmt"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/core/stores/cache"
Expand All @@ -15,6 +16,22 @@ type EmailConf struct {
Email string
}

type CosConfig struct {
AppId string
BucketName string
Region string
SecretId string
SecretKey string
}

func (c *CosConfig) CosHost() string {
return fmt.Sprintf("https://%s.cos.%s.myqcloud.com", c.BucketName, c.Region)
}

func (c *CosConfig) CIHost() string {
return fmt.Sprintf("https://%s.ci.%s.myqcloud.com", c.BucketName, c.Region)
}

type Config struct {
service.ServiceConf
ListenOn string
Expand All @@ -25,6 +42,7 @@ type Config struct {
CacheConf cache.CacheConf
Redis *redis.RedisConf
EmailConf EmailConf
CosConfig *CosConfig
}

func NewConfig() (*Config, error) {
Expand Down
8 changes: 3 additions & 5 deletions biz/infrastructure/util/email/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ import (

const (
contentType = "text/html; charset=UTF-8"
body = "<body><div class=\"container\"><p>你好,</p><p>你此次重置密码的验证码如下,请在 5 分钟内输入验证码进行下一步操作。如非你本人操作,请忽略此邮件。</p><p><strong>验证码:</strong>{{.code}}</p></div></body><style>body{font-family:Arial,sans-serif;background-color:#f0f0f0;margin:0;padding:0;}.container{max-width:600px;margin:0 auto;padding:20px;background-color:#ffffff;border-radius:5px;box-shadow:0 0 10px rgba(0,0,0,.1);}p{font-size:16px;line-height:1.6;color:#333333;}strong{font-weight:bold;}</style>\n"
body = "<body><div class=\"container\"><p>你好,</p><p>你此次{{.subject}}的验证码如下,请在 5 分钟内输入验证码进行下一步操作。如非你本人操作,请忽略此邮件。</p><p><strong>验证码:</strong>{{.code}}</p></div></body><style>body{font-family:Arial,sans-serif;background-color:#f0f0f0;margin:0;padding:0;}.container{max-width:600px;margin:0 auto;padding:20px;background-color:#ffffff;border-radius:5px;box-shadow:0 0 10px rgba(0,0,0,.1);}p{font-size:16px;line-height:1.6;color:#333333;}strong{font-weight:bold;}</style>\n"
)

func SendEmail(ctx context.Context, EmailConf config.EmailConf, toEmail, subject string) (string, error) {
_, span := trace.TracerFromContext(ctx).Start(ctx, "auth/SendEmail", oteltrace.WithTimestamp(time.Now()), oteltrace.WithSpanKind(oteltrace.SpanKindClient))
_, span := trace.TracerFromContext(ctx).Start(ctx, "auth.SendEmail", oteltrace.WithTimestamp(time.Now()), oteltrace.WithSpanKind(oteltrace.SpanKindClient))
defer func() {
span.End(oteltrace.WithTimestamp(time.Now()))
}()
Expand All @@ -33,10 +33,8 @@ func SendEmail(ctx context.Context, EmailConf config.EmailConf, toEmail, subject
header["Content-Type"] = contentType

Code := util.GenerateCode()
message := buildMessage(header, strings.Replace(body, "{{.code}}", Code, 1))

message := buildMessage(header, strings.Replace(strings.Replace(body, "{{.code}}", Code, 1), "{{.subject}}", subject, 1))
auth := smtp.PlainAuth("", EmailConf.Email, EmailConf.Password, EmailConf.Host)

return Code, SendMailWithTLS(fmt.Sprintf("%s:%d", EmailConf.Host, EmailConf.Port), auth, EmailConf.Email, []string{toEmail}, pconvertor.String2Bytes(message))
}

Expand Down
82 changes: 82 additions & 0 deletions biz/infrastructure/util/sdk/cos/cos.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package cos

import (
"context"
"github.com/CloudStriver/cloudmind-sts/biz/infrastructure/config"
"github.com/tencentyun/cos-go-sdk-v5"
"net/http"
"net/url"
"time"

"github.com/google/wire"
sts "github.com/tencentyun/qcloud-cos-sts-sdk/go"
"github.com/zeromicro/go-zero/core/trace"
oteltrace "go.opentelemetry.io/otel/trace"
)

type CosSDK struct {
stsClient *sts.Client
cosClient *cos.Client
}

func NewCosSDK(config *config.Config) (*CosSDK, error) {
bucketURL, err := url.Parse(config.CosConfig.CosHost())
if err != nil {
return nil, err
}
ciURL, err := url.Parse(config.CosConfig.CIHost())
if err != nil {
return nil, err
}
return &CosSDK{
stsClient: sts.NewClient(
config.CosConfig.SecretId,
config.CosConfig.SecretKey,
nil),
cosClient: cos.NewClient(&cos.BaseURL{
BucketURL: bucketURL,
CIURL: ciURL,
}, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: config.CosConfig.SecretId,
SecretKey: config.CosConfig.SecretKey,
},
}),
}, nil
}

func (s *CosSDK) GetCredential(ctx context.Context, opt *sts.CredentialOptions) (*sts.CredentialResult, error) {
_, span := trace.TracerFromContext(ctx).Start(ctx, "sts/GetCredential", oteltrace.WithTimestamp(time.Now()), oteltrace.WithSpanKind(oteltrace.SpanKindClient))
defer func() {
span.End(oteltrace.WithTimestamp(time.Now()))
}()
return s.stsClient.GetCredential(opt)
}

func (s *CosSDK) GetPresignedURL(ctx context.Context, httpMethod, name, ak, sk string, expired time.Duration, opt interface{}, signHost ...bool) (*url.URL, error) {
ctx, span := trace.TracerFromContext(ctx).Start(ctx, "cos/Object/GetPresignedURL", oteltrace.WithTimestamp(time.Now()), oteltrace.WithSpanKind(oteltrace.SpanKindClient))
defer func() {
span.End(oteltrace.WithTimestamp(time.Now()))
}()
return s.cosClient.Object.GetPresignedURL(ctx, httpMethod, name, ak, sk, expired, opt, signHost...)
}

func (s *CosSDK) Delete(ctx context.Context, name string, opt ...*cos.ObjectDeleteOptions) (*cos.Response, error) {
ctx, span := trace.TracerFromContext(ctx).Start(ctx, "cos/Object/Delete", oteltrace.WithTimestamp(time.Now()), oteltrace.WithSpanKind(oteltrace.SpanKindClient))
defer func() {
span.End(oteltrace.WithTimestamp(time.Now()))
}()
return s.cosClient.Object.Delete(ctx, name, opt...)
}

func (s *CosSDK) BatchImageAuditing(ctx context.Context, opt *cos.BatchImageAuditingOptions) (*cos.BatchImageAuditingJobResult, *cos.Response, error) {
ctx, span := trace.TracerFromContext(ctx).Start(ctx, "cos/CI/BatchImageAuditing", oteltrace.WithTimestamp(time.Now()), oteltrace.WithSpanKind(oteltrace.SpanKindClient))
defer func() {
span.End(oteltrace.WithTimestamp(time.Now()))
}()
return s.cosClient.CI.BatchImageAuditing(ctx, opt)
}

var CosSet = wire.NewSet(
NewCosSDK,
)
1 change: 0 additions & 1 deletion biz/infrastructure/util/types/types.go

This file was deleted.

11 changes: 9 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ go 1.20

require (
github.com/CloudStriver/go-pkg v0.0.0-20240115102515-f1d7bfa047af
github.com/CloudStriver/service-idl-gen-go v0.0.0-20240115022159-dd3577d2191f
github.com/CloudStriver/service-idl-gen-go v0.0.0-20240117150051-ecfa6300e8c4
github.com/cloudwego/kitex v0.8.0
github.com/google/wire v0.5.0
github.com/kitex-contrib/obs-opentelemetry v0.2.5
github.com/pkg/errors v0.9.1
github.com/tencentyun/cos-go-sdk-v5 v0.7.45
github.com/tencentyun/qcloud-cos-sts-sdk v0.0.0-20231121073521-dd65d8941a16
github.com/xh-polaris/platform-sts v1.4.34
github.com/zeromicro/go-zero v1.6.1
go.mongodb.org/mongo-driver v1.13.1
go.opentelemetry.io/otel/trace v1.19.0
Expand All @@ -26,6 +29,7 @@ require (
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
github.com/chenzhuoyu/iasm v0.9.1 // indirect
github.com/choleraehyq/pid v0.0.17 // indirect
github.com/clbanning/mxj v1.8.4 // indirect
github.com/cloudwego/configmanager v0.2.0 // indirect
github.com/cloudwego/dynamicgo v0.1.6 // indirect
github.com/cloudwego/fastpb v0.0.4 // indirect
Expand All @@ -41,9 +45,10 @@ require (
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-logr/logr v1.3.0 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-redis/redis/v8 v8.11.5 // indirect
github.com/go-redis/redis/v8 v8.11.6-0.20220405070650-99c79f7041fc // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/go-querystring v1.0.0 // indirect
github.com/google/pprof v0.0.0-20230509042627-b1315fad0c5a // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect
Expand All @@ -55,10 +60,12 @@ require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/gls v0.0.0-20220109145502-612d0167dce5 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
github.com/mozillazg/go-httpheader v0.2.1 // indirect
github.com/oleiade/lane v1.0.1 // indirect
github.com/openzipkin/zipkin-go v0.4.2 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
Expand Down
Loading

0 comments on commit a11bd6f

Please sign in to comment.