/
auth.go
106 lines (84 loc) · 2.67 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
103
104
105
106
package auth
import (
"context"
"log"
"net/http"
"time"
"github.com/google/uuid"
"golang.org/x/oauth2"
)
const timeout = 30 * time.Second
// ImplicitGrantFlow is recommended for apps without web service
var ImplicitGrantFlow = oauth2.SetAuthURLParam("response_type", "token")
// Handler handles the authn and authz with Fitbit API
type Handler struct {
config *oauth2.Config
callbackPort int
storage TokenStorage
}
// NewHandler creates new auth handler
func NewHandler(client string, secret string, scopes []string, callbackPort int, storage TokenStorage) *Handler {
config := &oauth2.Config{
ClientID: client,
ClientSecret: secret,
Scopes: scopes,
Endpoint: oauth2.Endpoint{
AuthURL: "https://www.fitbit.com/oauth2/authorize",
TokenURL: "https://api.fitbit.com/oauth2/token",
},
}
return &Handler{config: config, storage: storage, callbackPort: callbackPort}
}
// Client returns an authenticated http client
func (handler Handler) Client(context context.Context) (*http.Client, error) {
token, err := handler.acquireToken()
if err != nil {
return nil, err
}
tokenSource := handler.createTokenSource(context, token)
return oauth2.NewClient(context, tokenSource), nil
}
// Reset removes the stored tokens and restarts the auth process
func (handler Handler) Reset() error {
return handler.storage.Wipe()
}
func (handler *Handler) acquireToken() (*oauth2.Token, error) {
token, err := handler.loadStoredToken()
if err != nil {
return nil, err
}
if token != nil {
return token, nil
}
return handler.requestInitialToken()
}
func (handler *Handler) loadStoredToken() (*oauth2.Token, error) {
if handler.storage == nil {
return nil, nil
}
token, err := handler.storage.Load()
if err != nil {
log.Printf("error loading token from storage: %s\n", err.Error())
}
return token, err
}
func (handler *Handler) requestInitialToken() (*oauth2.Token, error) {
state, err := uuid.NewRandom()
if err != nil {
return nil, err
}
authURL := handler.config.AuthCodeURL(state.String())
log.Printf("visit URL: %s\n", authURL)
callback := NewCallbackServer(handler.callbackPort)
context, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
code, err := callback.AwaitCode(context)
if err != nil {
return nil, err
}
return handler.config.Exchange(context, code, ImplicitGrantFlow)
}
func (handler *Handler) createTokenSource(context context.Context, token *oauth2.Token) oauth2.TokenSource {
original := handler.config.TokenSource(context, token)
return NewPersistingTokenSource(original, handler.storage)
}