Skip to content

Instantly share code, notes, and snippets.

@yshuman1
Created January 8, 2019 07:19
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/47a383b686dee58bc51d679a191e4f56 to your computer and use it in GitHub Desktop.
Save yshuman1/47a383b686dee58bc51d679a191e4f56 to your computer and use it in GitHub Desktop.
func (u *Users) SqCallback(w http.ResponseWriter, r *http.Request) {
log.Infof("\n****************\ncallback func begun\n****************\n")
r.ParseForm()
state := r.FormValue("state")
cookie, err := r.Cookie("user_id")
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
}
var hashKey = []byte(coCfg.HashKey)
var blockKey = []byte(coCfg.BlockKey)
var s2 = securecookie.New(hashKey, blockKey)
value := make(map[string]string)
if err = s2.Decode("user_id", cookie.Value, &value); err == nil {
fmt.Println("heres the value", value["user_id"])
fmt.Fprintf(w, "The value of userID is %q", value["user_id"])
} else {
fmt.Printf("\n\n*********ERROR************\n\n%#v\n\n*********************************************\n\n\n\n", err)
}
fmt.Printf("%#v", value)
var dbUserID, _ = strconv.ParseUint(value["user_id"], 10, 32)
var userID = uint(dbUserID)
log.Infof("Customer dbID pulled from cookie state: %v\n\n***************", userID)
code := r.FormValue("code")
reqObj := map[string]string{
"client_id": sqOAuth.ClientID,
"client_secret": sqOAuth.ClientSecret,
"redirect_uri": sqOAuth.RedirectURL,
"code": code,
}
jsonValue, _ := json.Marshal(reqObj)
req, err := http.Post(sqOAuth.Endpoint.TokenURL, "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
fmt.Printf("http request failed with error %s\n", err)
} else {
var m map[string]string
_ = json.NewDecoder(req.Body).Decode(&m)
req.Body.Close()
expiresAt, _ := time.Parse(time.RFC3339, m["expires_at"])
token := oauth2.Token{
AccessToken: m["access_token"],
TokenType: m["token_type"],
Expiry: expiresAt,
}
userToken := model.OAuth{
UserID: userID,
Service: "square",
Token: token,
}
u.os.Create(&userToken)
if err != nil {
panic(err)
}
log.Infof("Customer token saved in DB")
http.Redirect(w, r, "/dashboard", http.StatusFound)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment