-
Notifications
You must be signed in to change notification settings - Fork 30
/
token_authorize.go
67 lines (60 loc) · 1.53 KB
/
token_authorize.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
package pocketbase
import (
"fmt"
"time"
"github.com/go-resty/resty/v2"
"golang.org/x/sync/singleflight"
)
type authorizeToken struct {
client *resty.Client
url string
token string
tokenValid time.Time
tokenSingle singleflight.Group
}
func newAuthorizeToken(c *resty.Client, url string, token string) authStore {
c.SetHeader("Authorization", token)
return &authorizeToken{
client: c,
url: url,
token: token,
tokenSingle: singleflight.Group{},
}
}
func (a *authorizeToken) authorize() error {
type authResponse struct {
Token string `json:"token"`
}
_, err, _ := a.tokenSingle.Do("auth-refresh", func() (interface{}, error) {
if time.Now().Before(a.tokenValid) {
return nil, nil
}
resp, err := a.client.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", a.token).
SetResult(&authResponse{}).
Post(a.url)
if err != nil {
return nil, fmt.Errorf("[auth-refresh] can't send request to pocketbase %w", err)
}
if resp.IsError() {
return nil, fmt.Errorf("[auth-refresh] pocketbase returned status: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
auth := *resp.Result().(*authResponse)
a.token = auth.Token
a.client.SetHeader("Authorization", auth.Token)
a.tokenValid = time.Now().Add(60 * time.Minute)
return nil, nil
})
return err
}
func (a *authorizeToken) IsValid() bool {
return time.Now().Before(a.tokenValid)
}
func (a *authorizeToken) Token() string {
return a.token
}