-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsdk.go
102 lines (81 loc) · 2.33 KB
/
sdk.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package login_sdk_go
import (
"context"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/xsolla/login-sdk-go/cache"
"github.com/xsolla/login-sdk-go/contract"
"github.com/xsolla/login-sdk-go/internal/adapter/login"
vl "github.com/xsolla/login-sdk-go/internal/service/validator"
)
const (
defaultLoginAPIURL = "https://login.xsolla.com"
keyTTL = 10 * time.Minute
defaultAPITimeout = 5 * time.Second
)
type Config struct {
IgnoreSslErrors bool
ShaSecretKey string
LoginAPIURL string
Cache contract.ValidationKeysCache
APITimeout time.Duration
ExtraHeaderName string
ExtraHeaderValue string
}
type ConfigOption func(*Config)
type validator interface {
Validate(ctx context.Context, jwt string, claims contract.Claims) (*jwt.Token, error)
}
type LoginSdk struct {
config Config
validator validator
}
func New(config Config) (*LoginSdk, error) {
config.fillDefaults()
loginApi := login.NewAdapter(config.LoginAPIURL, config.IgnoreSslErrors, config.APITimeout,
config.ExtraHeaderName, config.ExtraHeaderValue)
validator, err := vl.New(vl.Config{
ShaSecretKey: config.ShaSecretKey,
Cache: config.Cache,
}, loginApi)
if err != nil {
return nil, err
}
l := &LoginSdk{
config: config,
validator: validator,
}
return l, nil
}
func (c *Config) fillDefaults() {
if c.LoginAPIURL == "" {
c.LoginAPIURL = defaultLoginAPIURL
}
if c.Cache == nil {
c.Cache = cache.NewDefaultCache(keyTTL)
}
if c.APITimeout == 0 {
c.APITimeout = defaultAPITimeout
}
}
func (sdk *LoginSdk) ValidateWithContext(ctx context.Context, token string) (*jwt.Token, *WrappedError) {
parsedToken, err := sdk.validator.Validate(ctx, token, &CustomClaims{})
return parsedToken, WrapError(err)
}
func (sdk *LoginSdk) Validate(token string) (*jwt.Token, *WrappedError) {
return sdk.ValidateWithContext(context.Background(), token)
}
func (sdk *LoginSdk) ValidateWithClaimsAndContext(
ctx context.Context,
token string,
claims contract.Claims,
) (*jwt.Token, *WrappedError) {
parsedToken, err := sdk.validator.Validate(ctx, token, claims)
if err != nil {
return nil, WrapError(err)
}
return parsedToken, nil
}
func (sdk *LoginSdk) ValidateWithClaims(token string, claims contract.Claims) (*jwt.Token, *WrappedError) {
return sdk.ValidateWithClaimsAndContext(context.Background(), token, claims)
}