forked from TencentAd/marketing-api-go-sdk
/
middleware_auth.go
38 lines (34 loc) · 928 Bytes
/
middleware_auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package ads
import (
"context"
uuid "github.com/google/uuid"
"github.com/tencentad/marketing-api-go-sdk/pkg/config"
"net/http"
"strconv"
"time"
)
// AuthMiddleware ...
type AuthMiddleware struct {
tads *SDKClient
}
// Handle ...
func (a *AuthMiddleware) Handle(
req *http.Request,
next func(req *http.Request) (rsp *http.Response, err error),
) (rsp *http.Response, err error) {
nonce := uuid.New().String()
apiKey := config.APIKey{
AccessToken: a.tads.GetAccessToken(),
Timestamp: strconv.FormatInt(time.Now().Unix(), 10),
Nonce: nonce[0:8] + nonce[9:13] + nonce[14:18],
}
query := req.URL.Query()
query.Set("access_token", apiKey.AccessToken)
query.Set("timestamp", apiKey.Timestamp)
query.Set("nonce", apiKey.Nonce)
req.URL.RawQuery = query.Encode()
ctx := context.WithValue(req.Context(), config.ContextAPIKey, apiKey)
req = req.WithContext(ctx)
rsp, err = next(req)
return rsp, err
}