Example #1
0
// WithContextMustService creates a new StoreService wrapped in a context.Background().
// Panics on error.
func WithContextMustService(so scope.Option, opts ...func(ms *Storage)) context.Context {
	sm, err := NewService(so, opts...)
	if err != nil {
		panic(err)
	}
	return store.WithContextReader(context.Background(), sm)
}
Example #2
0
// Benchmark_WithInitStoreByFormCookie-4	    3000	    481881 ns/op	  189103 B/op	     232 allocs/op => with debug enabled
// Benchmark_WithInitStoreByFormCookie-4	  300000	      4797 ns/op	    1016 B/op	      16 allocs/op => debug disabled
func Benchmark_WithInitStoreByFormCookie(b *testing.B) {
	store.PkgLog.SetLevel(log.StdLevelInfo)
	b.ReportAllocs()

	wantStoreCode := "nz"
	ctx := store.WithContextReader(context.Background(), getInitializedStoreService(scope.Option{Website: scope.MockID(2)}))

	mw := store.WithInitStoreByFormCookie()(benchValidationHandler(b, wantStoreCode))

	rec := httptest.NewRecorder()
	req, err := http.NewRequest(httputil.MethodGet, "https://corestore.io/store/list/", nil)
	if err != nil {
		b.Fatal(err)
	}

	req.AddCookie(&http.Cookie{
		Name:  store.ParamName,
		Value: wantStoreCode,
	})

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if err := mw.ServeHTTPContext(ctx, rec, req); err != nil {
			b.Error(err)
		}
	}
}
Example #3
0
func newStoreServiceWithTokenCtx(initO scope.Option, tokenStoreCode string) context.Context {
	ctx := store.WithContextReader(context.Background(), getInitializedStoreService(initO))
	tok := jwt.New(jwt.SigningMethodHS256)
	tok.Claims[store.ParamName] = tokenStoreCode
	ctx = ctxjwt.WithContext(ctx, tok)
	return ctx
}
Example #4
0
func TestWithInitStoreByToken(t *testing.T) {

	var newReq = func(i int) *http.Request {
		req, err := http.NewRequest(httputil.MethodGet, fmt.Sprintf("https://corestore.io/store/list/%d", i), nil)
		if err != nil {
			t.Fatal(err)
		}
		return req
	}

	tests := []struct {
		ctx           context.Context
		wantStoreCode string
		wantErr       error
	}{
		{store.WithContextReader(context.Background(), nil), "de", store.ErrContextServiceNotFound},
		{store.WithContextReader(context.Background(), getInitializedStoreService(scope.Option{Store: scope.MockCode("de")})), "de", ctxjwt.ErrContextJWTNotFound},
		{newStoreServiceWithTokenCtx(scope.Option{Store: scope.MockCode("de")}, "de"), "de", nil},
		{newStoreServiceWithTokenCtx(scope.Option{Store: scope.MockCode("at")}, "ch"), "at", store.ErrStoreNotActive},
		{newStoreServiceWithTokenCtx(scope.Option{Store: scope.MockCode("de")}, "at"), "at", nil},
		{newStoreServiceWithTokenCtx(scope.Option{Store: scope.MockCode("de")}, "a$t"), "de", store.ErrStoreCodeInvalid},
		{newStoreServiceWithTokenCtx(scope.Option{Store: scope.MockCode("at")}, ""), "at", store.ErrStoreCodeInvalid},

		{newStoreServiceWithTokenCtx(scope.Option{Group: scope.MockID(1)}, "de"), "de", nil},
		{newStoreServiceWithTokenCtx(scope.Option{Group: scope.MockID(1)}, "ch"), "at", store.ErrStoreNotActive},
		{newStoreServiceWithTokenCtx(scope.Option{Group: scope.MockID(1)}, " ch"), "at", store.ErrStoreCodeInvalid},
		{newStoreServiceWithTokenCtx(scope.Option{Group: scope.MockID(1)}, "uk"), "at", store.ErrStoreChangeNotAllowed},

		{newStoreServiceWithTokenCtx(scope.Option{Website: scope.MockID(2)}, "uk"), "au", store.ErrStoreChangeNotAllowed},
		{newStoreServiceWithTokenCtx(scope.Option{Website: scope.MockID(2)}, "nz"), "nz", nil},
		{newStoreServiceWithTokenCtx(scope.Option{Website: scope.MockID(2)}, "n z"), "au", store.ErrStoreCodeInvalid},
		{newStoreServiceWithTokenCtx(scope.Option{Website: scope.MockID(2)}, "au"), "au", nil},
		{newStoreServiceWithTokenCtx(scope.Option{Website: scope.MockID(2)}, ""), "au", store.ErrStoreCodeInvalid},
	}
	for i, test := range tests {

		mw := store.WithInitStoreByToken()(finalInitStoreHandler(t, test.wantStoreCode))
		rec := httptest.NewRecorder()
		surfErr := mw.ServeHTTPContext(test.ctx, rec, newReq(i))
		if test.wantErr != nil {
			assert.EqualError(t, surfErr, test.wantErr.Error(), "Index %d", i)
			continue
		}
		assert.NoError(t, surfErr, "Index %d", i)
	}
}
Example #5
0
func TestWithInitStoreByFormCookie(t *testing.T) {
	errLogBuf.Reset()
	defer errLogBuf.Reset()

	for i, test := range testsMWInitByFormCookie {

		ctx := store.WithContextReader(context.Background(), getInitializedStoreService(test.haveSO))

		mw := store.WithInitStoreByFormCookie()(finalInitStoreHandler(t, test.wantStoreCode))

		rec := httptest.NewRecorder()
		surfErr := mw.ServeHTTPContext(ctx, rec, test.req)
		if test.wantErr != nil {
			var loc string
			if l, ok := surfErr.(errgo.Locationer); ok {
				loc = l.Location().String()
			}

			assert.EqualError(t, surfErr, test.wantErr.Error(), "\nIndex %d\n%s", i, loc)
			errLogBuf.Reset()
			continue
		}

		if test.wantLog != "" {
			assert.Contains(t, errLogBuf.String(), test.wantLog, "\nIndex %d\n", i)
			errLogBuf.Reset()
			continue
		} else {
			assert.Empty(t, errLogBuf.String(), "\nIndex %d\n", i)
		}

		assert.NoError(t, surfErr, "Index %d", i)

		newKeks := rec.HeaderMap.Get("Set-Cookie")
		if test.wantCookie != "" {
			assert.Contains(t, newKeks, test.wantCookie, "\nIndex %d\n", i)
		} else {
			assert.Empty(t, newKeks, "%#v", test)
		}
		errLogBuf.Reset()
	}
}
func ExampleWithInitStoreByToken() {
	initStore()
	ctx := store.WithContextReader(context.Background(), testStoreService)

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

	finalHandler := ctxhttp.Chain(
		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
		}, //
		jwtService.WithParseAndValidate(),
		store.WithInitStoreByToken(),
	)

	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:
}