forked from huandu/facebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
102 lines (82 loc) · 2.48 KB
/
auth.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 facebook
import (
"context"
"errors"
"github.com/dreamdata-io/facebook/internal"
"golang.org/x/oauth2"
)
type AuthClient interface {
ClientID() string
ClientSecret() string
OAuth2Config() *oauth2.Config
AuthCodeURL(ctx context.Context, state string, options ...oauth2.AuthCodeOption) string
ExchangeOAuth2Code(ctx context.Context, oauth2Code string) (*oauth2.Token, error)
AccessToken(ctx context.Context, refreshToken string) (*oauth2.Token, error)
// RevokeAccessToken revokes the token, this method requires authorization
RevokeAccessToken(ctx context.Context, refreshToken string) error
}
type AuthOption func(*oauth2.Config)
func WithScopes(scopes ...string) AuthOption {
return func(cfg *oauth2.Config) {
cfg.Scopes = scopes
}
}
func (c *Client) Auth(ctx context.Context, token *oauth2.Token, opts ...AuthOption) IClient {
cfg := c.oauth2Config
for _, option := range opts {
option(cfg)
}
session := c.app.Session("")
session.Version = c.version
session.HttpClient = cfg.Client(ctx, token)
return &Client{
app: c.app,
oauth2Config: cfg,
session: session,
version: c.version,
}
}
func (c *Client) ClientID() string {
return c.oauth2Config.ClientID
}
func (c *Client) ClientSecret() string {
return c.oauth2Config.ClientSecret
}
func (c *Client) OAuth2Config() *oauth2.Config {
return c.oauth2Config
}
func (c *Client) AuthCodeURL(_ context.Context, state string, options ...oauth2.AuthCodeOption) string {
return c.oauth2Config.AuthCodeURL(state, options...)
}
func (c *Client) ExchangeOAuth2Code(ctx context.Context, oauth2Code string) (*oauth2.Token, error) {
return c.oauth2Config.Exchange(ctx, oauth2Code)
}
func (c *Client) AccessToken(ctx context.Context, refreshToken string) (*oauth2.Token, error) {
t, err := c.oauth2Config.TokenSource(ctx, &oauth2.Token{RefreshToken: refreshToken}).Token()
if err != nil {
return nil, err
}
return t, nil
}
func (c *Client) RevokeAccessToken(_ context.Context, accessToken string) error {
params := map[string]string{
"client_id": c.oauth2Config.ClientID,
"client_secret": c.oauth2Config.ClientSecret,
"revoke_token": accessToken,
"access_token": accessToken,
}
res, err := c.session.Get("/oauth/revoke", internal.MakeParams(params))
if err != nil {
return err
}
var revocation struct {
Success bool `json:"success"`
}
if err = res.Decode(&revocation); err != nil {
return err
}
if !revocation.Success {
return errors.New("failed to revoke token")
}
return nil
}