forked from g8rswimmer/go-twitter
/
auth.go
67 lines (53 loc) · 1.46 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
package twitter
import (
"context"
"errors"
"net/http"
"github.com/dghubble/oauth1"
)
var (
ErrOAuth1NotSetup = errors.New("twitter: oauth1 not setup")
)
// Authorizer will add the authorization to the HTTP request
type Authorizer interface {
Add(req *http.Request)
}
type TwOAuth1 struct {
config *oauth1.Config
token *oauth1.Token
}
func (t *TwOAuth1) Client(ctx context.Context) *http.Client {
return t.config.Client(ctx, t.token)
}
func (t *TwOAuth1) TwitterClient(ctx context.Context) *Client {
return &Client{
Client: t.Client(ctx),
Host: "https://api.twitter.com",
}
}
func NewOAuth1Config(consumerKey, consumerSecret, accessToken, accessTokenSecret string) TwOAuth1 {
return TwOAuth1{
config: oauth1.NewConfig(consumerKey, consumerSecret),
token: oauth1.NewToken(accessToken, accessTokenSecret),
}
}
// ==== Singleton
var globalTwiOAuth1 TwOAuth1
func SetOAuth1(consumerKey, consumerSecret, accessToken, accessTokenSecret string) {
globalTwiOAuth1 = TwOAuth1{
config: oauth1.NewConfig(consumerKey, consumerSecret),
token: oauth1.NewToken(accessToken, accessTokenSecret),
}
}
func NewOAuth1Client(ctx context.Context) (*http.Client, error) {
if globalTwiOAuth1.config == nil {
return nil, ErrOAuth1NotSetup
}
return globalTwiOAuth1.Client(ctx), nil
}
func NewTwitterV2OAuth1(ctx context.Context) (*Client, error) {
if globalTwiOAuth1.config == nil {
return nil, ErrOAuth1NotSetup
}
return globalTwiOAuth1.TwitterClient(ctx), nil
}