func (ware Authenticator) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) bool {
	rawToken := ware.getToken(req)

	if rawToken == "" {
		return ware.Error(w, http.StatusUnauthorized, "Authorization header is invalid: missing")
	}

	token, err := jwt.Parse(rawToken, func(t *jwt.Token) (interface{}, error) {
		return []byte(ware.UAAPublicKey), nil
	})
	if err != nil {
		if strings.Contains(err.Error(), "expired") {
			return ware.Error(w, http.StatusUnauthorized, "Authorization header is invalid: expired")
		}
		return ware.Error(w, http.StatusUnauthorized, "Authorization header is invalid: corrupt")
	}

	if !ware.containsATokenScope(w, token) {
		return false
	}

	context.Set("token", token)
	context.Set("client_id", token.Claims["client_id"])

	return true
}
Exemple #2
0
func (m Middleware) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) bool {
	str := fmt.Sprintf("Middleware: %s\n", m.Name)
	context.Set(m.Name, fmt.Sprintf("I'm a middleware %s\n", m.Name))
	w.Header().Add("X-Middleware", m.Name)
	w.Write([]byte(str))
	return true
}
func (ware DatabaseAllocator) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) bool {
	db := models.NewDatabase(ware.DB, models.Config{})

	logger := gorpCompatibleLogger{
		logger: context.Get("logger").(lager.Logger).WithData(lager.Data{
			VCAPRequestIDKey: context.Get(VCAPRequestIDKey),
		}),
	}

	if ware.Trace {
		db.TraceOn("", logger)
	}

	context.Set("database", db)
	return true
}
func (r RequestLogging) ServeHTTP(response http.ResponseWriter, request *http.Request, context stack.Context) bool {
	requestID := request.Header.Get("X-Vcap-Request-Id")
	if requestID == "" {
		requestID = "UNKNOWN"
	}

	logSession := r.logger.Session("request", lager.Data{
		VCAPRequestIDKey: requestID,
	})

	logSession.Info("incoming", lager.Data{
		"method": request.Method,
		"path":   request.URL.Path,
	})

	context.Set("logger", logSession)
	context.Set(VCAPRequestIDKey, requestID)
	context.Set(RequestReceivedTime, time.Now().UTC())

	return true
}
		handler           senders.GetHandler
		sendersCollection *mocks.SendersCollection
		context           stack.Context
		writer            *httptest.ResponseRecorder
		request           *http.Request
		database          *mocks.Database
		conn              *mocks.Connection
	)

	BeforeEach(func() {
		conn = mocks.NewConnection()
		database = mocks.NewDatabase()
		database.ConnectionCall.Returns.Connection = conn

		context = stack.NewContext()
		context.Set("client_id", "some-client-id")
		context.Set("database", database)

		sendersCollection = mocks.NewSendersCollection()
		sendersCollection.GetCall.Returns.Sender = collections.Sender{
			ID:   "some-sender-id",
			Name: "some-sender",
		}

		writer = httptest.NewRecorder()

		var err error
		request, err = http.NewRequest("GET", "/senders/some-sender-id", nil)
		Expect(err).NotTo(HaveOccurred())

		handler = senders.NewGetHandler(sendersCollection)
			"scope":   []string{"notification_preferences.read"},
		}

		request, err = http.NewRequest("GET", "/user_preferences", bytes.NewBuffer(body))
		if err != nil {
			panic(err)
		}

		token, err := jwt.Parse(helpers.BuildToken(tokenHeader, tokenClaims), func(token *jwt.Token) (interface{}, error) {
			return []byte(application.UAAPublicKey), nil
		})

		database = mocks.NewDatabase()

		context = stack.NewContext()
		context.Set("token", token)
		context.Set("database", database)

		builder = services.NewPreferencesBuilder()
		builder.Add(models.Preference{
			ClientID: "raptorClient",
			KindID:   "hungry-kind",
			Email:    false,
		})
		builder.Add(models.Preference{
			ClientID: "starWarsClient",
			KindID:   "vader-kind",
			Email:    true,
		})
		builder.GlobalUnsubscribe = true
			errorWriter *mocks.ErrorWriter
			strategy    *mocks.Strategy
		)

		BeforeEach(func() {
			writer = httptest.NewRecorder()
			request = &http.Request{URL: &url.URL{Path: "/uaa_scopes/great.scope"}}
			strategy = mocks.NewStrategy()
			errorWriter = mocks.NewErrorWriter()

			connection = mocks.NewConnection()
			database := mocks.NewDatabase()
			database.ConnectionCall.Returns.Connection = connection

			context = stack.NewContext()
			context.Set("database", database)
			context.Set(notify.VCAPRequestIDKey, "some-request-id")

			notifyObj = mocks.NewNotify()
			handler = notify.NewUAAScopeHandler(notifyObj, errorWriter, strategy)
		})

		Context("when the notifyObj.Execute returns a successful response", func() {
			It("returns the JSON representation of the response", func() {
				notifyObj.ExecuteCall.Returns.Response = []byte("whatever")

				handler.ServeHTTP(writer, request, context)

				Expect(writer.Code).To(Equal(http.StatusOK))
				Expect(writer.Body.String()).To(Equal("whatever"))
			})
		tokenClaims := map[string]interface{}{
			"client_id": "some-uaa-client-id",
			"exp":       int64(3404281214),
			"scope":     []string{"notifications.write"},
		}
		token, err := jwt.Parse(helpers.BuildToken(tokenHeader, tokenClaims), func(*jwt.Token) (interface{}, error) {
			return []byte(application.UAAPublicKey), nil
		})
		Expect(err).NotTo(HaveOccurred())

		conn = mocks.NewConnection()
		database = mocks.NewDatabase()
		database.ConnectionCall.Returns.Connection = conn

		context = stack.NewContext()
		context.Set("token", token)
		context.Set("database", database)
		context.Set("client_id", "my-client")

		campaignsCollection = mocks.NewCampaignsCollection()
		campaignsCollection.GetCall.Returns.Campaign = collections.Campaign{
			ID:             "some-campaign-id",
			SendTo:         map[string]string{"user": "******"},
			CampaignTypeID: "some-campaign-type-id",
			Text:           "come see our new stuff",
			HTML:           "<h1>New stuff</h1>",
			Subject:        "Cool New Stuff",
			TemplateID:     "random-template-id",
			ReplyTo:        "reply-to-address",
			ClientID:       "my-client",
		}
		var err error
		updater = mocks.NewTemplateUpdater()
		errorWriter = mocks.NewErrorWriter()
		writer = httptest.NewRecorder()
		request, err = http.NewRequest("PUT", "/default_template", strings.NewReader(`{
			"name": "Defaultish Template",
			"subject": "{{.Subject}}",
			"html": "<p>something</p>",
			"text": "something",
			"metadata": {"hello": true}
		}`))
		Expect(err).NotTo(HaveOccurred())

		database = mocks.NewDatabase()
		context = stack.NewContext()
		context.Set("database", database)

		handler = templates.NewUpdateDefaultHandler(updater, errorWriter)
	})

	It("updates the default template", func() {
		handler.ServeHTTP(writer, request, context)

		Expect(writer.Code).To(Equal(http.StatusNoContent))
		Expect(updater.UpdateCall.Receives.Database).To(Equal(database))
		Expect(updater.UpdateCall.Receives.TemplateID).To(Equal(models.DefaultTemplateID))
		Expect(updater.UpdateCall.Receives.Template).To(Equal(models.Template{
			Name:     "Defaultish Template",
			Subject:  "{{.Subject}}",
			HTML:     "<p>something</p>",
			Text:     "something",
	BeforeEach(func() {
		var err error
		sqlDB, err = sqlmock.New()
		Expect(err).NotTo(HaveOccurred())

		ware = middleware.NewDatabaseAllocator(sqlDB, true)

		writer = httptest.NewRecorder()
		request = &http.Request{}

		buffer = bytes.NewBuffer([]byte{})
		logger := lager.NewLogger("notifications")
		logger.RegisterSink(lager.NewWriterSink(buffer, lager.DEBUG))

		context = stack.NewContext()
		context.Set("logger", logger)
		context.Set(middleware.VCAPRequestIDKey, "some-vcap-request-id")
	})

	AfterEach(func() {
		err := sqlDB.Close()
		Expect(err).NotTo(HaveOccurred())
	})

	It("allocates a database that it adds to the context", func() {
		result := ware.ServeHTTP(writer, request, context)
		Expect(result).To(BeTrue())

		database, ok := context.Get("database").(*db.DB)
		Expect(ok).To(BeTrue())
Exemple #11
0
				request, err = http.NewRequest("POST", "/spaces/space-001", bytes.NewBuffer(body))
				if err != nil {
					panic(err)
				}
				request.Header.Set("Authorization", "Bearer "+rawToken)

				token, err := jwt.Parse(rawToken, func(*jwt.Token) (interface{}, error) {
					return []byte(application.UAAPublicKey), nil
				})

				database = mocks.NewDatabase()

				reqReceivedTime, _ = time.Parse(time.RFC3339Nano, "2015-06-08T14:32:11.660762586-07:00")

				context = stack.NewContext()
				context.Set("token", token)
				context.Set("database", database)
				context.Set(notify.RequestReceivedTime, reqReceivedTime)

				vcapRequestID = "some-request-id"

				conn = mocks.NewConnection()
				strategy = mocks.NewStrategy()
				validator = mocks.NewValidator()
				validator.ValidateCall.Returns.Valid = true

				handler = notify.NewNotify(finder, registrar)
			})

			It("delegates to the strategy", func() {
				_, err := handler.Execute(conn, request, context, "space-001", strategy, validator, vcapRequestID)
	var (
		handler                 campaigntypes.UpdateHandler
		campaignTypesCollection *mocks.CampaignTypesCollection
		context                 stack.Context
		writer                  *httptest.ResponseRecorder
		request                 *http.Request
		database                *mocks.Database
		tokenHeader             map[string]interface{}
		tokenClaims             map[string]interface{}
		guid                    string
	)

	BeforeEach(func() {
		context = stack.NewContext()

		context.Set("client_id", "some-client-id")

		database = mocks.NewDatabase()
		context.Set("database", database)

		tokenHeader = map[string]interface{}{
			"alg": "FAST",
		}
		tokenClaims = map[string]interface{}{
			"client_id": "some-uaa-client-id",
			"exp":       int64(3404281214),
			"scope": []string{
				"notifications.write",
				"critical_notifications.write",
			},
		}
		handler           senders.ListHandler
		sendersCollection *mocks.SendersCollection
		context           stack.Context
		writer            *httptest.ResponseRecorder
		request           *http.Request
		conn              *mocks.Connection
		database          *mocks.Database
	)

	BeforeEach(func() {
		conn = mocks.NewConnection()
		database = mocks.NewDatabase()
		database.ConnectionCall.Returns.Connection = conn

		context = stack.NewContext()
		context.Set("client_id", "whatever")
		context.Set("database", database)

		sendersCollection = mocks.NewSendersCollection()

		sendersList := []collections.Sender{
			{
				ID:   "sender-id-one",
				Name: "first sender",
			},
			{
				ID:   "sender-id-two",
				Name: "second sender",
			},
		}
		sendersCollection.ListCall.Returns.SenderList = sendersList