-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdigest.go
79 lines (62 loc) · 1.79 KB
/
digest.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package gosip
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/patrickmn/go-cache"
)
var storage = cache.New(5*time.Minute, 10*time.Minute)
type contextInfoResponse struct {
D struct {
GetContextWebInformation struct {
FormDigestTimeoutSeconds time.Duration `json:"FormDigestTimeoutSeconds"`
FormDigestValue string `json:"FormDigestValue"`
LibraryVersion string `json:"LibraryVersion"`
} `json:"GetContextWebInformation"`
} `json:"d"`
}
// GetDigest retrieves and caches SharePoint API X-RequestDigest value
func GetDigest(context context.Context, client *SPClient) (string, error) {
siteURL := client.AuthCnfg.GetSiteURL()
cacheKey := siteURL + "@digest@" + fmt.Sprintf("%#v", client.AuthCnfg)
if digestValue, found := storage.Get(cacheKey); found {
return digestValue.(string), nil
}
contextInfoURL := siteURL + "/_api/ContextInfo"
req, err := http.NewRequest("POST", contextInfoURL, nil)
if err != nil {
return "", err
}
if context != nil {
req = req.WithContext(context)
}
req.Header.Set("Accept", "application/json;odata=verbose")
resp, err := client.Execute(req)
if err != nil {
return "", err
}
defer func() { _ = resp.Body.Close() }()
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
results := &contextInfoResponse{}
err = json.Unmarshal(data, &results)
if err != nil {
return "", err
}
if results.D.GetContextWebInformation.FormDigestValue == "" {
return "", errors.New("received empty FormDigestValue")
}
expiry := (results.D.GetContextWebInformation.FormDigestTimeoutSeconds - 60) * time.Second
storage.Set(
cacheKey,
results.D.GetContextWebInformation.FormDigestValue,
expiry,
)
return results.D.GetContextWebInformation.FormDigestValue, nil
}