func mapCart(c martini.Context, res http.ResponseWriter, r *http.Request) error { qs := r.URL.Query() var shopId string if qsId := qs.Get("shop"); qsId != "" { shopId = qsId } else if formId := r.FormValue("shop"); formId != "" { shopId = formId } else if headerId := r.Header.Get("shop"); headerId != "" { shopId = headerId } if shopId == "" { return fmt.Errorf("error: %s", "you must provide a shop identifier") } if !bson.IsObjectIdHex(shopId) { return fmt.Errorf("error: %s", "invalid shop identifier") } shop := cart.Shop{ Id: bson.ObjectIdHex(shopId), } if shop.Id.Hex() == "" { return fmt.Errorf("error: %s", "invalid shop identifier") } if err := shop.Get(); err != nil { return err } if shop.Id.Hex() == "" { return fmt.Errorf("error: %s", "invalid shop identifier") } c.Map(&shop) return nil }
func mapCartAccount(c martini.Context, res http.ResponseWriter, r *http.Request) error { auth := r.Header.Get("Authorization") token := strings.Replace(auth, "Bearer ", "", 1) cust, err := cart.AuthenticateAccount(token) if err != nil { return err } shop := cart.Shop{ Id: cust.ShopId, } if shop.Id.Hex() == "" { return fmt.Errorf("error: %s", "invalid shop identifier") } if err := shop.Get(); err != nil { return err } if shop.Id.Hex() == "" { return fmt.Errorf("error: %s", "invalid shop identifier") } c.Map(&shop) c.Map(token) return nil }
func Meddler() martini.Handler { return func(res http.ResponseWriter, r *http.Request, c martini.Context) { res.Header().Add("Access-Control-Allow-Origin", "*") if strings.ToLower(r.Method) == "options" { return } if strings.Contains(r.URL.String(), "favicon") { res.Write([]byte("")) return } start := time.Now() excused := false for _, route := range ExcusedRoutes { if strings.Contains(r.URL.String(), route) { excused = true } } // check if we need to make a call // to the shopping cart middleware if strings.Contains(strings.ToLower(r.URL.Path), "/shopify/account") { // account perms if strings.ToLower(r.URL.Path) == "/shopify/account/login" || (strings.ToLower(r.Method) == "post" && strings.ToLower(r.URL.Path) == "/shopify/account") { shopID := r.URL.Query().Get("shop") var crt cart.Shop if bson.IsObjectIdHex(shopID) { crt.Id = bson.ObjectIdHex(shopID) } c.Map(&crt) } else if err := mapCartAccount(c, res, r); err != nil { apierror.GenerateError("", err, res, r) return } excused = true } else if strings.Contains(strings.ToLower(r.URL.Path), "/shopify") { // shop perms if err := mapCart(c, res, r); err != nil { apierror.GenerateError("", err, res, r) return } excused = true } if !excused { dataContext, err := processDataContext(r, c) if err != nil { apierror.GenerateError("Trouble processing the data context", err, res, r, http.StatusUnauthorized) return } c.Map(dataContext) } c.Next() go logRequest(r, time.Since(start)) } }