Esempio n. 1
0
// WithIsCountryAllowedByIP a more advanced function. It expects from the context
// the store.ManagerReader ...
func (s *Service) WithIsCountryAllowedByIP() ctxhttp.Middleware {
	return func(h ctxhttp.Handler) ctxhttp.Handler {
		return ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {

			_, requestedStore, err := store.FromContextReader(ctx)
			if err != nil {
				if PkgLog.IsDebug() {
					PkgLog.Debug("geoip.WithCountryByIP.FromContextManagerReader", "err", err)
				}
				return errgo.Mask(err)
			}

			var ipCountry *IPCountry
			ctx, ipCountry, err = s.newContextCountryByIP(ctx, r)
			if err != nil {
				ctx = NewContextWithError(ctx, err)
				return h.ServeHTTPContext(ctx, w, r)
			}

			allowedCountries, err := directory.AllowedCountries(requestedStore.Config)
			if err != nil {
				if PkgLog.IsDebug() {
					PkgLog.Debug("geoip.WithCountryByIP.directory.AllowedCountries", "err", err, "st.Config", requestedStore.Config)
				}
				return errgo.Mask(err)
			}

			if false == s.IsAllowed(requestedStore, ipCountry, allowedCountries, r) {
				h = s.altHandlerByID(requestedStore)
			}

			return h.ServeHTTPContext(ctx, w, r)
		})
	}
}
Esempio n. 2
0
func finalInitStoreHandler(t *testing.T, wantStoreCode string) ctxhttp.Handler {
	return ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		_, haveReqStore, err := store.FromContextReader(ctx)
		if err != nil {
			return err
		}
		assert.Exactly(t, wantStoreCode, haveReqStore.StoreCode())
		return nil
	})
}
Esempio n. 3
0
func benchValidationHandler(b *testing.B, wantStoreCode string) ctxhttp.Handler {
	return ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		_, haveReqStore, err := store.FromContextReader(ctx)
		if err != nil {
			return err
		}

		if wantStoreCode != haveReqStore.StoreCode() {
			b.Errorf("Want: %s\nHave: %s", wantStoreCode, haveReqStore.StoreCode())
		}
		return nil
	})
}
Esempio n. 4
0
func jsonStores(ctx context.Context, w http.ResponseWriter, r *http.Request) error {

	storeReader, _, err := store.FromContextReader(ctx)
	if err != nil {
		return err // default StatusInternalServerError
	}

	stores, err := storeReader.Stores()
	if err != nil {
		return ctxhttp.NewErrorFromErrors(http.StatusInternalServerError, err)
	}
	return httputil.NewPrinter(w, r).JSON(http.StatusOK, stores)
}
Esempio n. 5
0
func TestContextReaderError(t *testing.T) {
	haveMr, s, err := store.FromContextReader(context.Background())
	assert.Nil(t, haveMr)
	assert.Nil(t, s)
	assert.EqualError(t, err, store.ErrContextServiceNotFound.Error())

	ctx := store.NewContextReader(context.Background(), nil)
	assert.NotNil(t, ctx)
	haveMr, s, err = store.FromContextReader(ctx)
	assert.Nil(t, haveMr)
	assert.Nil(t, s)
	assert.EqualError(t, err, store.ErrContextServiceNotFound.Error())

	mr := storemock.NewNullService()
	ctx = store.NewContextReader(context.Background(), mr)
	assert.NotNil(t, ctx)
	haveMr, s, err = store.FromContextReader(ctx)
	assert.EqualError(t, err, store.ErrStoreNotFound.Error())
	assert.Nil(t, haveMr)
	assert.Nil(t, s)

}
Esempio n. 6
0
func TestWithInitStoreByToken_EqualPointers(t *testing.T) {
	// this Test is related to Benchmark_WithInitStoreByToken
	// The returned pointers from store.FromContextReader must be the
	// same for each request with the same request pattern.

	ctx := newStoreServiceWithTokenCtx(scope.Option{Website: scope.MockID(2)}, "nz")
	rec := httptest.NewRecorder()
	req, err := http.NewRequest(httputils.MethodGet, "https://corestore.io/store/list", nil)
	if err != nil {
		t.Fatal(err)
	}

	var equalStorePointer *store.Store
	mw := store.WithInitStoreByToken()(ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		_, haveReqStore, err := store.FromContextReader(ctx)
		if err != nil {
			return err
		}

		if equalStorePointer == nil {
			equalStorePointer = haveReqStore
		}

		if "nz" != haveReqStore.StoreCode() {
			t.Errorf("Have: %s\nWant: nz", haveReqStore.StoreCode())
		}

		wantP := reflect.ValueOf(equalStorePointer)
		haveP := reflect.ValueOf(haveReqStore)

		if wantP.Pointer() != haveP.Pointer() {
			t.Errorf("Expecting equal pointers for each request.\nWant: %p\nHave: %p", equalStorePointer, haveReqStore)
		}

		return nil
	}))

	for i := 0; i < 10; i++ {
		if err := mw.ServeHTTPContext(ctx, rec, req); err != nil {
			t.Error(err)
		}
	}
}
Esempio n. 7
0
// current returns a non-nil pointer to a Cors. current is used within a request.
func (c *Cors) current(csc *corsScopeCache, ctx context.Context) *Cors {
	if c.config == nil || csc == nil {
		return c
	}

	_, st, err := store.FromContextReader(ctx)
	if err != nil {
		if c.Log.IsInfo() {
			c.Log.Info("ctxcors.Cors.current.store.FromContextReader", "err", err)
		}
		return c
	}

	var cc *Cors // cc == current CORS config the current request
	if cc = csc.get(st.WebsiteID()); cc == nil {
		cc = csc.insert(st.WebsiteID())
	}
	// todo: run a defer or goroutine to check if config changes
	// and if so delete the entry from the map
	return cc
}
Esempio n. 8
0
func TestContextReaderSuccess(t *testing.T) {
	ctx := storemock.NewContextService(scope.Option{},
		func(ms *storemock.Storage) {
			ms.MockStore = func() (*store.Store, error) {
				return store.NewStore(
					&store.TableStore{StoreID: 6, Code: dbr.NewNullString("de"), WebsiteID: 1, GroupID: 1, Name: "Germany", SortOrder: 10, IsActive: true},
					&store.TableWebsite{WebsiteID: 1, Code: dbr.NewNullString("euro"), Name: dbr.NewNullString("Europe"), SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NewNullBool(true)},
					&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "DACH Group", RootCategoryID: 2, DefaultStoreID: 6},
				)
			}
		},
	)

	haveMr, s, err := store.FromContextReader(ctx)
	assert.NoError(t, err)
	assert.Exactly(t, int64(6), s.StoreID())

	s2, err2 := haveMr.Store()
	assert.NoError(t, err2)
	assert.Exactly(t, int64(6), s2.StoreID())

}
func ExampleWithInitStoreByToken() {
	initStore()
	ctx := store.NewContextReader(context.Background(), testStoreService)

	jwtService, err := ctxjwt.NewService(ctxjwt.WithPassword([]byte(`GÒph3r`)))

	finalHandler := ctxhttp.Chain(
		ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
			_, haveReqStore, err := store.FromContextReader(ctx)
			if err != nil {
				return err
			}
			// now we know that the current request depends on the store view DE.
			fmt.Fprintf(w, "StoreCode: %s\n", haveReqStore.StoreCode())
			return nil
		}), // 								  executed 3rd
		store.WithInitStoreByToken(),      // executed 2nd
		jwtService.WithParseAndValidate(), // executed 1st
	)

	ts := httptest.NewServer(ctxhttp.NewAdapter(ctx, finalHandler))
	defer ts.Close()

	// Setup GET request
	token, _, err := jwtService.GenerateToken(
		map[string]interface{}{
			// Despite default store for Website ID 1 is AT we are currently
			// in the store context of DE.
			store.ParamName: "de",
		},
	)
	if err != nil {
		log.Fatal("jwtService.GenerateToken", "err", err)
	}

	req, err := http.NewRequest("GET", ts.URL, nil)
	if err != nil {
		log.Fatal("http.Get", "err", err)
	}
	ctxjwt.SetHeaderAuthorization(req, token)

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal("http.DefaultClient.Do", "err", err)
	}

	response, err := ioutil.ReadAll(res.Body)
	if errC := res.Body.Close(); errC != nil {
		log.Fatal("res.Body.Close", "err", errC)
	}

	if err != nil {
		log.Fatal("ioutil.ReadAll", "err", err)
	}

	fmt.Printf("Response: %s\n", response)
	fmt.Printf("Log: %s\n", testDebugLogBuf.String())
	// Output:
	// Response: StoreCode: de
	//
	// Log:
}