Esempio n. 1
0
// NewListBottleContext parses the incoming request URL and body, performs validations and creates the
// context used by the bottle controller list action.
func NewListBottleContext(c *goa.Context) (*ListBottleContext, error) {
	var err error
	ctx := ListBottleContext{Context: c}
	rawAccountID := c.Get("accountID")
	if rawAccountID != "" {
		if accountID, err2 := strconv.Atoi(rawAccountID); err2 == nil {
			ctx.AccountID = int(accountID)
		} else {
			err = goa.InvalidParamTypeError("accountID", rawAccountID, "integer", err)
		}
	}
	rawYears := c.Get("years")
	if rawYears != "" {
		elemsYears := strings.Split(rawYears, ",")
		elemsYears2 := make([]int, len(elemsYears))
		for i, rawElem := range elemsYears {
			if elem, err2 := strconv.Atoi(rawElem); err2 == nil {
				elemsYears2[i] = int(elem)
			} else {
				err = goa.InvalidParamTypeError("elem", rawElem, "integer", err)
			}
		}
		ctx.Years = elemsYears2
	}
	return &ctx, err
}
Esempio n. 2
0
// unmarshalUpdateAccountPayload unmarshals the request body.
func unmarshalUpdateAccountPayload(ctx *goa.Context) error {
	payload := &UpdateAccountPayload{}
	if err := ctx.Service().DecodeRequest(ctx, payload); err != nil {
		return err
	}
	if err := payload.Validate(); err != nil {
		return err
	}
	ctx.SetPayload(payload)
	return nil
}
Esempio n. 3
0
// RequestResource returns the resource targeted by the CORS request defined in ctx.
func (v Specification) RequestResource(ctx *goa.Context, origin string) *ResourceDefinition {
	path := ctx.Request().URL.Path
	var match *ResourceDefinition
	for _, res := range v {
		if res.OriginAllowed(origin) && res.PathMatches(path) {
			if res.Check == nil || res.Check(ctx) {
				match = res
				break
			}
		}
	}
	return match
}
Esempio n. 4
0
// NewShowAccountContext parses the incoming request URL and body, performs validations and creates the
// context used by the account controller show action.
func NewShowAccountContext(c *goa.Context) (*ShowAccountContext, error) {
	var err error
	ctx := ShowAccountContext{Context: c}
	rawAccountID := c.Get("accountID")
	if rawAccountID != "" {
		if accountID, err2 := strconv.Atoi(rawAccountID); err2 == nil {
			ctx.AccountID = int(accountID)
		} else {
			err = goa.InvalidParamTypeError("accountID", rawAccountID, "integer", err)
		}
	}
	return &ctx, err
}
Esempio n. 5
0
func parseBasicAuth(ctx *goa.Context) (username, password string, ok bool) {
	auth := ctx.Request().Header.Get("Authorization")
	if auth == "" {
		return
	}

	if !strings.HasPrefix(auth, basicScheme) {
		return
	}

	c, err := base64.StdEncoding.DecodeString(auth[len(basicScheme):])
	if err != nil {
		return
	}

	cs := string(c)
	s := strings.IndexByte(cs, ':')
	if s < 0 {
		return
	}

	return cs[:s], cs[s+1:], true
}
Esempio n. 6
0
// GetToken extracts the JWT token from the request if there is one.
func GetToken(ctx *goa.Context, spec *Specification) (token *jwt.Token, err error) {
	var found bool
	var tok string
	header := ctx.Request().Header.Get(spec.TokenHeader)

	if header != "" {
		parts := strings.Split(header, " ")
		if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
			err = fmt.Errorf("Malformed token header")
			return
		}
		tok = parts[1]
		found = true
	}
	if !found && spec.AllowParam {
		tok = ctx.Request().URL.Query().Get(spec.TokenParam)
	}
	if tok == "" {
		err = fmt.Errorf("no token")
		return
	}
	token, err = jwt.Parse(tok, keyFuncWrapper(spec.ValidationFunc))
	return
}
Esempio n. 7
0
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/goadesign/goa"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"golang.org/x/net/context"
	"gopkg.in/inconshreveable/log15.v2"
)

var _ = Describe("Context", func() {
	var logger log15.Logger
	var ctx *goa.Context

	BeforeEach(func() {
		gctx := context.Background()
		ctx = goa.NewContext(gctx, goa.New("test"), nil, nil, nil)
		ctx.Logger = logger
	})

	Describe("SetValue", func() {
		key := "answer"
		val := 42

		BeforeEach(func() {
			ctx.SetValue(key, val)
		})
Esempio n. 8
0
				ctrl := s.NewController("test")
				Ω(ctrl.MiddlewareChain()).Should(HaveLen(1))
				Ω(ctrl.MiddlewareChain()[0]).Should(BeAssignableToTypeOf(middleware.RequestID()))
			})
		})
	})

	Describe("HandleFunc", func() {
		const resName = "res"
		const actName = "act"
		var handler, unmarshaler goa.Handler
		const respStatus = 200
		var respContent = []byte("response")

		var handleFunc goa.HandleFunc
		var ctx *goa.Context

		JustBeforeEach(func() {
			ctrl := s.NewController("test")
			handleFunc = ctrl.HandleFunc(actName, handler, unmarshaler)
		})

		BeforeEach(func() {
			handler = func(c *goa.Context) error {
				ctx = c
				c.RespondBytes(respStatus, respContent)
				return nil
			}
			unmarshaler = func(c *goa.Context) error {
				ctx = c
				req := c.Request()
		var goaMiddlewareFunc func(goa.Handler) goa.Handler

		BeforeEach(func() {
			goaMiddlewareFunc = func(h goa.Handler) goa.Handler { return h }
			input = goaMiddlewareFunc
		})

		It("returns the middleware", func() {
			Ω(fmt.Sprintf("%#v", middleware)).Should(Equal(fmt.Sprintf("%#v", goa.Middleware(goaMiddlewareFunc))))
			Ω(mErr).ShouldNot(HaveOccurred())
		})
	})

	Context("with a context", func() {
		var service goa.Service
		var ctx *goa.Context

		BeforeEach(func() {
			service = goa.New("test")
			req, err := http.NewRequest("GET", "/goo", nil)
			Ω(err).ShouldNot(HaveOccurred())
			rw := new(testResponseWriter)
			params := url.Values{"foo": []string{"bar"}}
			ctx = goa.NewContext(nil, service, req, rw, params)
			Ω(ctx.ResponseStatus()).Should(Equal(0))
		})

		Context("using a goa handler", func() {
			BeforeEach(func() {
				var goaHandler goa.Handler = func(ctx *goa.Context) error {
					ctx.Respond(200, "ok")
func (t *TestResponseWriter) Header() http.Header {
	return t.ParentHeader
}

func (t *TestResponseWriter) Write(b []byte) (int, error) {
	t.Body = append(t.Body, b...)
	return len(b), nil
}

func (t *TestResponseWriter) WriteHeader(s int) {
	t.Status = s
}

var _ = Describe("Gzip", func() {
	var handler *testHandler
	var ctx *goa.Context
	var req *http.Request
	var rw *TestResponseWriter
	params := url.Values{"param": []string{"value"}}
	payload := map[string]interface{}{"payload": 42}

	BeforeEach(func() {
		var err error
		req, err = http.NewRequest("POST", "/foo/bar", strings.NewReader(`{"payload":42}`))
		req.Header.Set("Accept-Encoding", "gzip")
		Ω(err).ShouldNot(HaveOccurred())
		rw = &TestResponseWriter{
			ParentHeader: http.Header{},
		}

		ctx = goa.NewContext(nil, goa.New("test"), req, rw, params)
Esempio n. 11
0
package httpauth_test

import (
	"encoding/base64"
	"errors"
	"net/http"

	"github.com/moorereason/httpauth"

	"github.com/goadesign/goa"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Httpauth Middleware", func() {
	var ctx *goa.Context
	var spec *httpauth.Specification
	var req *http.Request
	var rw *TestResponseWriter
	var err error
	var user = "******"
	var pass = "******"
	var authString = "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))

	validFunc := func(ctx *goa.Context, u, p string) error {
		if u == user && p == pass {
			return nil
		}
		return errors.New("failed")
	}
Esempio n. 12
0
// unauthorized sets the appropriate WWW-Authenticate header prior to sending an
// Unauthorized HTTP response.
func unauthorized(ctx *goa.Context, spec *Specification) error {
	ctx.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", spec.Realm))
	// return ctx.Respond(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
	return ctx.Respond(http.StatusUnauthorized, map[string]interface{}{"ID": -1, "Title": "Unauthorized", "Msg": "Unauthorized Request"})
}
Esempio n. 13
0
	jwtg "github.com/dgrijalva/jwt-go"
	"github.com/goadesign/goa"
	"github.com/goadesign/middleware/jwt"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var signingKey = []byte("jwtsecretsauce")

// Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1
var hmacTestKey, _ = ioutil.ReadFile("test/hmacTestKey")
var rsaSampleKey, _ = ioutil.ReadFile("test/sample_key")
var rsaSampleKeyPub, _ = ioutil.ReadFile("test/sample_key.pub")

var _ = Describe("JWT Middleware", func() {
	var ctx *goa.Context
	var spec *jwt.Specification
	var req *http.Request
	var err error
	var token *jwtg.Token
	var tokenString string
	params := url.Values{"param": []string{"value"}, "query": []string{"qvalue"}}
	payload := map[string]interface{}{"payload": 42}
	validFunc := func(token *jwtg.Token) (interface{}, error) {
		return signingKey, nil
	}

	BeforeEach(func() {
		req, err = http.NewRequest("POST", "/goo", strings.NewReader(`{"payload":42}`))
		Ω(err).ShouldNot(HaveOccurred())
		rw := new(TestResponseWriter)
Esempio n. 14
0
		var goaMiddlewareFunc func(goa.Handler) goa.Handler

		BeforeEach(func() {
			goaMiddlewareFunc = func(h goa.Handler) goa.Handler { return h }
			input = goaMiddlewareFunc
		})

		It("returns the middleware", func() {
			Ω(fmt.Sprintf("%#v", middleware)).Should(Equal(fmt.Sprintf("%#v", goa.Middleware(goaMiddlewareFunc))))
			Ω(mErr).ShouldNot(HaveOccurred())
		})
	})

	Context("with a context", func() {
		var service goa.Service
		var ctx *goa.Context

		BeforeEach(func() {
			service = goa.New("test")
			req, err := http.NewRequest("GET", "/goo", nil)
			Ω(err).ShouldNot(HaveOccurred())
			rw := new(TestResponseWriter)
			params := url.Values{"foo": []string{"bar"}}
			ctx = goa.NewContext(nil, service, req, rw, params)
			Ω(ctx.ResponseStatus()).Should(Equal(0))
		})

		Context("using a goa handler", func() {
			BeforeEach(func() {
				var goaHandler goa.Handler = func(ctx *goa.Context) error {
					ctx.Respond(200, "ok")