-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauth.go
More file actions
119 lines (96 loc) · 2.52 KB
/
Copy pathauth.go
File metadata and controls
119 lines (96 loc) · 2.52 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package onedriveclient
import (
"context"
"encoding/json"
"net/http"
"net/url"
"sync"
"time"
"github.com/koofr/go-httpclient"
)
const (
InvalidGrantError = "invalid_grant"
)
type RefreshResp struct {
ExpiresIn int64 `json:"expires_in"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
type RefreshRespError struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
type OneDriveAuth struct {
ClientId string
ClientSecret string
RedirectUri string
AccessToken string
RefreshToken string
ExpiresAt time.Time
OnTokenRefresh func(ctx context.Context)
IsGraph bool
TokenURL string
HTTPClient *httpclient.HTTPClient
mutex sync.Mutex
}
func (a *OneDriveAuth) ValidToken(ctx context.Context) (token string, err error) {
if time.Now().Unix() > a.ExpiresAt.Add(-5*time.Minute).Unix() {
err = a.UpdateRefreshToken(ctx)
if err != nil {
return "", err
}
}
token = a.AccessToken
return token, nil
}
func (a *OneDriveAuth) UpdateRefreshToken(ctx context.Context) (err error) {
a.mutex.Lock()
defer a.mutex.Unlock()
data := url.Values{}
data.Set("grant_type", "refresh_token")
data.Set("client_id", a.ClientId)
data.Set("client_secret", a.ClientSecret)
data.Set("redirect_uri", a.RedirectUri)
data.Set("refresh_token", a.RefreshToken)
var respVal RefreshResp
fullURL := a.TokenURL
if fullURL == "" {
if a.IsGraph {
fullURL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
} else {
fullURL = "https://login.live.com/oauth20_token.srf"
}
}
client := a.HTTPClient
if client == nil {
client = httpclient.DefaultClient
}
_, err = client.Request(&httpclient.RequestData{
Context: ctx,
Method: "POST",
FullURL: fullURL,
ExpectedStatus: []int{http.StatusOK},
ReqEncoding: httpclient.EncodingForm,
ReqValue: data,
RespEncoding: httpclient.EncodingJSON,
RespValue: &respVal,
})
if err != nil {
err = HandleError(err)
if ode, ok := IsOneDriveError(err); ok {
refreshErr := &RefreshRespError{}
if jsonErr := json.Unmarshal([]byte(ode.Err.Message), &refreshErr); jsonErr == nil {
ode.Err.Code = refreshErr.Error
ode.Err.Message = refreshErr.ErrorDescription
}
}
return err
}
a.AccessToken = respVal.AccessToken
a.RefreshToken = respVal.RefreshToken
a.ExpiresAt = time.Now().Add(time.Duration(respVal.ExpiresIn) * time.Second)
if a.OnTokenRefresh != nil {
a.OnTokenRefresh(ctx)
}
return nil
}