forked from omniboost/go-fortnox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.go
78 lines (63 loc) · 1.56 KB
/
oauth.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
package fortnox
import (
"context"
"errors"
"time"
"github.com/go-redis/redis/v9"
"golang.org/x/oauth2"
)
const (
rdsTokenKey = "fortnox_token"
)
var (
ErrNoTokenInTokenStorage = errors.New("fortnox: no token in token storage")
)
type TokenStorage interface {
GetToken(ctx context.Context) (string, error)
SetToken(ctx context.Context, token []byte) error
}
type ResultIface interface {
Result() (string, error)
}
type ErrorIface interface {
Err() error
}
type StorageProvider interface {
Get(ctx context.Context, key string) ResultIface
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) ErrorIface
}
type tokenStorage struct {
sp StorageProvider
}
func NewTokenStorage(sp StorageProvider) TokenStorage {
return &tokenStorage{sp: sp}
}
func (t *tokenStorage) GetToken(ctx context.Context) (string, error) {
tokenJSON, err := t.sp.Get(ctx, rdsTokenKey).Result()
if err != nil && err == redis.Nil {
return "", ErrNoTokenInTokenStorage
}
return tokenJSON, nil
}
func (t *tokenStorage) SetToken(ctx context.Context, token []byte) error {
return t.sp.Set(ctx, rdsTokenKey, token, 0).Err()
}
type Oauth2Config struct {
oauth2.Config
}
func NewOauth2Config() *Oauth2Config {
config := &Oauth2Config{
Config: oauth2.Config{
RedirectURL: "",
ClientID: "",
ClientSecret: "",
Scopes: []string{},
Endpoint: oauth2.Endpoint{
AuthURL: "https://apps.fortnox.se/oauth-v1/auth",
TokenURL: "https://apps.fortnox.se/oauth-v1/token",
AuthStyle: oauth2.AuthStyleInHeader,
},
},
}
return config
}