-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
webauth.go
170 lines (147 loc) · 4.13 KB
/
webauth.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
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"os"
"github.com/zricethezav/go-tdameritrade"
"golang.org/x/oauth2"
)
type HTTPHeaderStore struct{}
func (s *HTTPHeaderStore) StoreToken(token *oauth2.Token, w http.ResponseWriter, req *http.Request) error {
// DO NOT DO THIS IN A PRODUCTION ENVIRONMENT!
// This is just an example.
// Used signed cookies like those provided by https://github.com/gorilla/securecookie
http.SetCookie(
w,
&http.Cookie{
Name: "refreshToken",
Value: token.RefreshToken,
Expires: token.Expiry,
},
)
http.SetCookie(
w,
&http.Cookie{
Name: "accessToken",
Value: token.AccessToken,
Expires: token.Expiry,
},
)
return nil
}
func (s HTTPHeaderStore) GetToken(req *http.Request) (*oauth2.Token, error) {
// DO NOT DO THIS IN A PRODUCTION ENVIRONMENT!
// This is just an example.
// Used signed cookies like those provided by https://github.com/gorilla/securecookie
refreshToken, err := req.Cookie("refreshToken")
if err != nil {
return nil, err
}
accessToken, err := req.Cookie("accessToken")
if err != nil {
return nil, err
}
return &oauth2.Token{
AccessToken: accessToken.Value,
RefreshToken: refreshToken.Value,
Expiry: refreshToken.Expires,
}, nil
}
func (s HTTPHeaderStore) StoreState(state string, w http.ResponseWriter, req *http.Request) error {
// DO NOT DO THIS IN A PRODUCTION ENVIRONMENT!
// This is just an example.
// Used signed cookies like those provided by https://github.com/gorilla/securecookie
http.SetCookie(
w,
&http.Cookie{
Name: "state",
Value: state,
},
)
return nil
}
func (s HTTPHeaderStore) GetState(req *http.Request) (string, error) {
// DO NOT DO THIS IN A PRODUCTION ENVIRONMENT!
// This is just an example.
// Used signed cookies like those provided by https://github.com/gorilla/securecookie
cookie, err := req.Cookie("state")
if err != nil {
return "", err
}
return cookie.Value, nil
}
type TDHandlers struct {
authenticator *tdameritrade.Authenticator
}
func (h *TDHandlers) Authenticate(w http.ResponseWriter, req *http.Request) {
redirectURL, err := h.authenticator.StartOAuth2Flow(w, req)
if err != nil {
w.Write([]byte(err.Error()))
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, req, redirectURL, http.StatusTemporaryRedirect)
}
func (h *TDHandlers) Callback(w http.ResponseWriter, req *http.Request) {
ctx := context.Background()
_, err := h.authenticator.FinishOAuth2Flow(ctx, w, req)
if err != nil {
w.Write([]byte(err.Error()))
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, req, "/quote?ticker=SPY", http.StatusTemporaryRedirect)
}
func (h *TDHandlers) Quote(w http.ResponseWriter, req *http.Request) {
ctx := context.Background()
client, err := h.authenticator.AuthenticatedClient(ctx, req)
if err != nil {
w.Write([]byte(err.Error()))
w.WriteHeader(http.StatusInternalServerError)
return
}
ticker, ok := req.URL.Query()["ticker"]
if !ok || len(ticker) == 0 {
w.Write([]byte("ticker is required"))
w.WriteHeader(http.StatusBadRequest)
return
}
quote, resp, err := client.Quotes.GetQuotes(ctx, ticker[0])
if err != nil {
w.Write([]byte(err.Error()))
w.WriteHeader(http.StatusInternalServerError)
return
}
body, err := json.Marshal(quote)
if err != nil {
w.Write([]byte(err.Error()))
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(body)
w.WriteHeader(resp.StatusCode)
}
func main() {
clientID := os.Getenv("TDAMERITRADE_CLIENT_ID")
if clientID == "" {
log.Fatal("Unauthorized: No client ID present")
}
authenticator := tdameritrade.NewAuthenticator(
&HTTPHeaderStore{},
oauth2.Config{
ClientID: clientID,
Endpoint: oauth2.Endpoint{
TokenURL: "https://api.tdameritrade.com/v1/oauth2/token",
AuthURL: "https://auth.tdameritrade.com/auth",
},
RedirectURL: "https://localhost:8080/callback",
},
)
handlers := &TDHandlers{authenticator: authenticator}
http.HandleFunc("/authenticate", handlers.Authenticate)
http.HandleFunc("/callback", handlers.Callback)
http.HandleFunc("/quote", handlers.Quote)
log.Fatal(http.ListenAndServe(":8080", nil))
}