Skip to content

Instantly share code, notes, and snippets.

@yshuman1
Created December 25, 2018 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yshuman1/b3c472978a4b1b73d6668dfe583f440f to your computer and use it in GitHub Desktop.
Save yshuman1/b3c472978a4b1b73d6668dfe583f440f to your computer and use it in GitHub Desktop.
oauth gist
sqOAuth := &oauth2.Config{
ClientID: sqCfg.ID,
ClientSecret: sqCfg.Secret,
RedirectURL: sqCfg.RedirectURL,
Scopes: []string{"MERCHANT_PROFILE_READ", "ORDERS_READ"},
Endpoint: oauth2.Endpoint{
AuthURL: sqCfg.AuthURL,
TokenURL: sqCfg.TokenURL,
},
}
sqRedirect := func(w http.ResponseWriter, r *http.Request) {
//TODO: randomize state string
// rand.Seed(time.Now().UnixNano())
// state := strconv.FormatUint(rand.Uint64(), 10)
state := "random"
cookie := http.Cookie{
Name: "oauth_state",
Value: state,
HttpOnly: true,
}
http.SetCookie(w, &cookie)
url := sqOAuth.AuthCodeURL(state)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
sqCallback := func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
state := r.FormValue("state")
cookie, err := r.Cookie("oauth_state")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
} else if cookie == nil || cookie.Value != state {
http.Error(w, "invalid state provided", http.StatusBadRequest)
return
}
cookie.Value = ""
cookie.Expires = time.Now()
http.SetCookie(w, cookie)
code := r.FormValue("code")
token, err := sqOAuth.Exchange(context.TODO(), code)
if err != nil {
fmt.Println("breaking when trying to get token")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "%+v", token)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment