110 lines
2.4 KiB
Go
110 lines
2.4 KiB
Go
package etsy
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"ruben/inventory2/internal/domains/platforms/etsy"
|
|
"ruben/inventory2/internal/domains/raw_events"
|
|
)
|
|
|
|
type Config struct {
|
|
OAuthRedirectURIWithAcctIDParam string
|
|
}
|
|
|
|
func NewWebhookHandler(
|
|
db *raw_events.Store,
|
|
platform *etsy.Platform,
|
|
cfg Config,
|
|
) http.Handler {
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("POST /test", func(w http.ResponseWriter, r *http.Request) {
|
|
var body json.RawMessage
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
http.Error(w, "Failed to decode body as json: "+err.Error(), 500)
|
|
return
|
|
}
|
|
|
|
ts := time.Now().UTC()
|
|
|
|
storeID := "test-store-id"
|
|
var payloadObject struct {
|
|
StoreID string
|
|
}
|
|
if err := json.Unmarshal(body, &payloadObject); err == nil && payloadObject.StoreID != "" {
|
|
storeID = payloadObject.StoreID
|
|
}
|
|
|
|
err := db.Save(r.Context(), &raw_events.Event{
|
|
Platform: "etsy",
|
|
StoreID: storeID,
|
|
EventID: fmt.Sprint(ts.Unix()),
|
|
EventTimestamp: ts,
|
|
Payload: body,
|
|
})
|
|
if err != nil {
|
|
http.Error(w, "Error occurred saving the body as the event payload: "+err.Error(), 500)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(201)
|
|
})
|
|
|
|
mux.HandleFunc("GET "+cfg.OAuthRedirectURIWithAcctIDParam, func(w http.ResponseWriter, r *http.Request) {
|
|
// get account id for the request
|
|
|
|
acctID, err := strconv.ParseInt(r.PathValue("acctID"), 10, 64)
|
|
if err != nil || acctID <= 0 {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
ctx := r.Context()
|
|
|
|
q := r.URL.Query()
|
|
state := q.Get("state")
|
|
|
|
// handle failed, potentially non-consenting, request
|
|
|
|
if errCode := q.Get("error"); errCode != "" {
|
|
errDesc := q.Get("error_description")
|
|
errURI := q.Get("error_uri")
|
|
|
|
fmt.Printf(
|
|
"error in obtaining an OAuth Token: error=%s, error_desc=%s, error_uri=%s, account_id=%d\n",
|
|
errCode,
|
|
errDesc,
|
|
errURI,
|
|
acctID,
|
|
)
|
|
|
|
platform.InvalidateState(ctx, state)
|
|
|
|
return
|
|
}
|
|
|
|
// validate the state to prevent CSRF attacks
|
|
|
|
ok, err := platform.HandleNewAuthCode(ctx, acctID, state, q.Get("code"))
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusForbidden)
|
|
fmt.Println("failed to handle new auth code:", err)
|
|
return
|
|
}
|
|
if !ok {
|
|
w.WriteHeader(http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
// TODO: response with a redirect to the user's account page (SUCCESS - new sign up or login)!
|
|
|
|
http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acctID), http.StatusSeeOther)
|
|
})
|
|
|
|
return mux
|
|
}
|