-
Notifications
You must be signed in to change notification settings - Fork 1
/
authorizer.go
215 lines (185 loc) · 6.81 KB
/
authorizer.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package fitbit
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/fitbit"
"github.com/galeone/fitbit/v2/scopes"
"github.com/galeone/fitbit/v2/types"
"github.com/google/uuid"
)
// Authorizer is the structure that manages the OAuth2
// authorization process. It depends on a `Storage`
// where the tokens are stored during the various exchanges.
type Authorizer struct {
config *oauth2.Config
authorizing *types.AuthorizingUser
token *oauth2.Token
userID *string
db Storage
}
// NewAuthorizer creates a new Authorizer. The created client
// is already configured for requesting the correct scopes and
// make authenticathed/authorized requests to the fitbit API.
// The db parameter must be a valid implementation of the Storage
// interface.
func NewAuthorizer(db Storage, clientID, clientSecret, redirectURL string) *Authorizer {
client := Authorizer{}
client.db = db
// OAuth2 Client configuration
config := &oauth2.Config{}
config.ClientID = clientID
config.ClientSecret = clientSecret
config.RedirectURL = redirectURL
config.Endpoint = fitbit.Endpoint
config.Scopes = scopes.All()
client.config = config
return &client
}
// SetAuthorizing sets the parameters required during the autorization process
func (c *Authorizer) SetAuthorizing(auth *types.AuthorizingUser) {
c.authorizing = auth
}
// AuthorizationURL returns the URL where to redirect the user
// where it will be asked for giving the permissions for the various scopes
func (c *Authorizer) AuthorizationURL() (*url.URL, error) {
if c.authorizing == nil {
return nil, errors.New("AuthorizationURL called without setting Authorizing parameters first")
}
// The OAuth2 library creates an url with:
// - scopes
// - access_type
// - client_id
// - redirect_uri
// - response_type=code
// - state=`c.authorizing.CSRFToken`
ret, _ := url.Parse(c.config.AuthCodeURL(c.authorizing.CSRFToken, oauth2.AccessTypeOffline))
// But the Fitbit API also requires
// https://dev.fitbit.com/build/reference/web-api/developer-guide/authorization/#Authorization-Code-Grant-Flow-with-PKCE
// - code_challenge
// - code_challenge_method=S256
values := ret.Query()
values.Add("code_challenge_method", "S256")
// base64UrlEncode(sha256Hash(code_verifier))
h := sha256.New()
h.Write([]byte(c.authorizing.Code))
shaSum := h.Sum(nil)
challenge := base64.RawURLEncoding.EncodeToString(shaSum)
values.Add("code_challenge", challenge)
ret.RawQuery = values.Encode()
return ret, nil
}
// CSRFToken returns the CSRF code associated with this session
func (c *Authorizer) CSRFToken() *uuid.UUID {
token := uuid.MustParse(c.authorizing.CSRFToken)
return &token
}
// ExchangeAuthorizationCode exchanges the authorization code for the access
// and refresh tokens.
// In a Server Application Type, this request should be authenticated
// https://dev.fitbit.com/build/reference/web-api/developer-guide/authorization/#Authorization-Code-Grant-Flow-with-PKCE
// See step 4
//
// This method also saves the exchanged token inside the *Authorizer structure. This token
// is later used for creating the HTTP client (see HTTP method).
func (c *Authorizer) ExchangeAuthorizationCode(code string) (token *types.AuthorizedUser, err error) {
// Manually build everyting because adding a custom header in the code exchange request is not supported
// The URL creation is kept from there
// https://github.com/golang/oauth2/blob/2e8d9340160224d36fd555eaf8837240a7e239a7/oauth2.go#L213
v := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {c.config.RedirectURL},
// From step 4
"client_id": {c.config.ClientID},
"code_verifier": {c.authorizing.Code},
}
endpoint, _ := url.Parse(fmt.Sprintf("%s?%s", fitbit.Endpoint.TokenURL, v.Encode()))
var req *http.Request
if req, err = http.NewRequest("POST", endpoint.String(), nil); err != nil {
return nil, err
}
auth := base64.RawStdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.config.ClientID, c.config.ClientSecret)))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", auth))
client := http.Client{}
var res *http.Response
if res, err = client.Do(req); err != nil {
return nil, err
}
body, _ := io.ReadAll(res.Body)
expected := types.AuthorizedUser{}
if err = json.Unmarshal(body, &expected); err != nil {
unexpected := types.OAuth2Error{}
if err = json.Unmarshal(body, &unexpected); err == nil {
var sb strings.Builder
last := len(unexpected.Errors) - 1
for i, err := range unexpected.Errors {
sb.WriteString(err.Message)
if i != last {
sb.WriteRune(',')
}
}
return nil, errors.New(sb.String())
}
return nil, fmt.Errorf("Unexpected return body: %s", string(body))
}
return &expected, nil
}
// Return an HTTP client that uses the specified token for authenticating
// It handles all the refresh-token stuff, and it updates inside the db
// The values for the user that's this *Authorizer
func (c *Authorizer) HTTP() (*http.Client, error) {
tokenSource := c.config.TokenSource(context.Background(), c.token)
newToken, err := tokenSource.Token()
if err != nil {
return nil, err
}
if c.token.AccessToken != newToken.AccessToken {
var dbToken *types.AuthorizedUser
if dbToken, err = c.db.AuthorizedUser(c.token.AccessToken); err != nil {
return nil, err
}
// Now I have the dbToken that contains the UserID (primary key)
// associated with the previous access token
dbToken.AccessToken = newToken.AccessToken
dbToken.ExpiresIn = int64(time.Second * time.Since(newToken.Expiry))
dbToken.RefreshToken = newToken.RefreshToken
if err = c.db.UpsertAuthorizedUser(dbToken); err != nil {
return nil, err
}
c.SetToken(dbToken)
}
return c.config.Client(context.Background(), c.token), nil
}
// UserID returns the ID of the users that authorized this client
// Returns an error if the fitbitClient is not authorized
func (c *Authorizer) UserID() (*string, error) {
if c.token == nil || c.userID == nil {
return nil, errors.New("UserID called, but no user Authorized this client")
}
return c.userID, nil
}
// SetToken sets the token inside the Authorizer. From the types.AuthorizedUser
// to the oauth2.Token representation (privately used).
func (c *Authorizer) SetToken(token *types.AuthorizedUser) {
c.token = &oauth2.Token{
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
Expiry: time.Now().Add(time.Second * time.Duration(token.ExpiresIn)),
TokenType: token.TokenType,
}
c.userID = &token.UserID
}