Example #1
0
func (h DeleteHandler) ServeHTTP(w http.ResponseWriter, request *http.Request, context stack.Context) {
	splitURL := strings.Split(request.URL.Path, "/")
	templateID := splitURL[len(splitURL)-1]

	database := context.Get("database").(collections.DatabaseInterface)
	clientID := context.Get("client_id").(string)

	_, err := h.deleter.Get(database.Connection(), templateID, clientID)
	if err != nil {
		switch err.(type) {
		case collections.NotFoundError:
			w.WriteHeader(http.StatusNotFound)
		default:
			w.WriteHeader(http.StatusInternalServerError)
		}

		fmt.Fprintf(w, `{"errors": [%q]}`, err)
		return
	}

	err = h.deleter.Delete(database.Connection(), templateID)
	if err != nil {
		switch err.(type) {
		case collections.NotFoundError:
			w.WriteHeader(http.StatusNotFound)
		default:
			w.WriteHeader(http.StatusInternalServerError)
		}

		fmt.Fprintf(w, `{"errors": [%q]}`, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #2
0
func (h GetHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	templateID := strings.Split(req.URL.Path, "/templates/")[1]

	template, err := h.finder.FindByID(context.Get("database").(DatabaseInterface), templateID)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	var metadata map[string]interface{}
	err = json.Unmarshal([]byte(template.Metadata), &metadata)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	templateOutput := TemplateOutput{
		Name:     template.Name,
		Subject:  template.Subject,
		HTML:     template.HTML,
		Text:     template.Text,
		Metadata: metadata,
	}

	writeJSON(w, http.StatusOK, templateOutput)
}
Example #3
0
func (h ListHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request, context stack.Context) {
	clientID := context.Get("client_id").(string)
	database := context.Get("database").(DatabaseInterface)

	senderList, err := h.collection.List(database.Connection(), clientID)
	if err != nil {
		writer.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(writer, `{ "errors": [ %q ] }`, err)
		return
	}

	responseList := []interface{}{}

	for _, sender := range senderList {
		responseList = append(responseList, map[string]interface{}{
			"id":   sender.ID,
			"name": sender.Name,
		})
	}

	listResponse, _ := json.Marshal(map[string]interface{}{
		"senders": responseList,
	})

	writer.Write(listResponse)
}
Example #4
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
}
Example #5
0
func (h GetHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	splitURL := strings.Split(req.URL.Path, "/")
	senderID := splitURL[len(splitURL)-3]
	campaignID := splitURL[len(splitURL)-1]

	clientID := context.Get("client_id").(string)
	database := context.Get("database").(collections.DatabaseInterface)

	campaign, err := h.campaigns.Get(database.Connection(), campaignID, senderID, clientID)
	if err != nil {
		switch err.(type) {
		case collections.NotFoundError:
			w.WriteHeader(http.StatusNotFound)
		default:
			w.WriteHeader(http.StatusInternalServerError)
		}
		fmt.Fprintf(w, `{ "errors": [%q] }`, err)
		return
	}

	getResponse, _ := json.Marshal(map[string]interface{}{
		"id":               campaign.ID,
		"send_to":          campaign.SendTo,
		"campaign_type_id": campaign.CampaignTypeID,
		"text":             campaign.Text,
		"html":             campaign.HTML,
		"subject":          campaign.Subject,
		"template_id":      campaign.TemplateID,
		"reply_to":         campaign.ReplyTo,
	})
	w.Write(getResponse)
}
Example #6
0
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
}
Example #7
0
func (h ListHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	templates, err := h.lister.List(context.Get("database").(DatabaseInterface))
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	writeJSON(w, http.StatusOK, templates)
}
func (h RegistrationHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	database := context.Get("database").(DatabaseInterface)
	connection := database.Connection()

	parameters, err := NewRegistrationParams(req.Body)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	err = parameters.Validate()
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	token := context.Get("token").(*jwt.Token)
	clientID := token.Claims["client_id"].(string)

	client := models.Client{
		ID:          clientID,
		Description: parameters.SourceDescription,
	}

	kinds, err := h.ValidateCriticalScopes(token.Claims["scope"], parameters.Kinds, client)

	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	transaction := connection.Transaction()
	transaction.Begin()

	err = h.registrar.Register(transaction, client, kinds)
	if err != nil {
		transaction.Rollback()
		h.errorWriter.Write(w, err)
		return
	}

	if parameters.IncludesKinds {
		err = h.registrar.Prune(transaction, client, kinds)
		if err != nil {
			transaction.Rollback()
			h.errorWriter.Write(w, err)
			return
		}
	}

	err = transaction.Commit()
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}
}
Example #9
0
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	var output string
	for _, key := range context.Keys() {
		output += context.Get(key).(string)
	}
	output += fmt.Sprintf("Handler\n")

	w.Header().Add("X-Handler", "my-handler")
	w.Write([]byte(output))
}
Example #10
0
func (h DeleteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	templateID := strings.Split(req.URL.Path, "/templates/")[1]

	err := h.deleter.Delete(context.Get("database").(DatabaseInterface), templateID)
	if err != nil {
		h.errorWriter.Write(w, err)
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #11
0
func (h ShowHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request, context stack.Context) {
	splitURL := strings.Split(request.URL.Path, "/")
	campaignTypeID := splitURL[len(splitURL)-1]
	senderID := splitURL[len(splitURL)-3]

	if senderID == "" {
		writer.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(writer, `{"errors": [%q]}`, "missing sender id")
		return
	}

	if campaignTypeID == "" {
		headers := writer.Header()
		headers.Set("Location", fmt.Sprintf("/senders/%s/campaign_types", senderID))
		writer.WriteHeader(http.StatusMovedPermanently)
		return
	}

	clientID := context.Get("client_id")
	if clientID == "" {
		writer.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintf(writer, `{"errors": [%q]}`, "missing client id")
		return
	}

	database := context.Get("database").(DatabaseInterface)
	campaignType, err := h.collection.Get(database.Connection(), campaignTypeID, senderID, context.Get("client_id").(string))
	if err != nil {
		switch err.(type) {
		case collections.NotFoundError:
			writer.WriteHeader(http.StatusNotFound)
		default:
			writer.WriteHeader(http.StatusInternalServerError)
		}

		fmt.Fprintf(writer, `{"errors": [%q]}`, err)
		return
	}

	jsonMap := map[string]interface{}{
		"id":          campaignType.ID,
		"name":        campaignType.Name,
		"description": campaignType.Description,
		"critical":    campaignType.Critical,
		"template_id": campaignType.TemplateID,
	}

	jsonBody, err := json.Marshal(jsonMap)
	if err != nil {
		panic(err)
	}

	writer.Write([]byte(jsonBody))
}
func (h GetUserPreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	userGUID := strings.TrimPrefix(req.URL.Path, "/user_preferences/")

	parsed, err := h.preferences.Find(context.Get("database").(DatabaseInterface), userGUID)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	writeJSON(w, http.StatusOK, parsed)
}
func (h ListAssociationsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	templateID := h.parseTemplateID(req.URL.Path)
	associations, err := h.lister.List(context.Get("database").(DatabaseInterface), templateID)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	templateAssociationsDocument := h.mapToJSON(associations)
	writeJSON(w, http.StatusOK, templateAssociationsDocument)
}
Example #14
0
func (h ListHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	clients, notifications, err := h.finder.AllClientsAndNotifications(context.Get("database").(DatabaseInterface))
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	notificationsByClient := h.constructNotifications(clients, notifications)

	writeJSON(w, http.StatusOK, notificationsByClient)
}
Example #15
0
func (h UpdateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	splitURL := strings.Split(req.URL.Path, "/")
	senderID := splitURL[len(splitURL)-1]

	var updateRequest struct {
		Name string `json:"name"`
	}

	err := json.NewDecoder(req.Body).Decode(&updateRequest)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(`{"errors": ["invalid json body"]}`))
		return
	}

	database := context.Get("database").(DatabaseInterface)
	clientID := context.Get("client_id").(string)

	_, err = h.senders.Get(database.Connection(), senderID, clientID)
	if err != nil {
		switch err.(type) {
		case collections.NotFoundError:
			w.WriteHeader(http.StatusNotFound)
		default:
			w.WriteHeader(http.StatusInternalServerError)
		}
		w.Write([]byte(fmt.Sprintf(`{ "errors": [ %q ]}`, err)))
		return
	}

	sender, err := h.senders.Set(database.Connection(), collections.Sender{
		ID:       senderID,
		Name:     updateRequest.Name,
		ClientID: clientID,
	})
	if err != nil {
		switch err.(type) {
		case collections.DuplicateRecordError:
			w.WriteHeader(422)
		default:
			w.WriteHeader(http.StatusInternalServerError)
		}
		w.Write([]byte(fmt.Sprintf(`{ "errors": [ %q ]}`, err)))
		return
	}

	updateResponse, _ := json.Marshal(map[string]string{
		"id":   sender.ID,
		"name": sender.Name,
	})

	w.Write(updateResponse)
}
Example #16
0
func (h EveryoneHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	connection := context.Get("database").(DatabaseInterface).Connection()
	vcapRequestID := context.Get(VCAPRequestIDKey).(string)

	output, err := h.notify.Execute(connection, req, context, "", h.strategy, GUIDValidator{}, vcapRequestID)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write(output)
}
func (h UpdatePreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	database := context.Get("database").(DatabaseInterface)
	connection := database.Connection()

	token := context.Get("token").(*jwt.Token)

	if _, ok := token.Claims["user_id"]; !ok {
		h.errorWriter.Write(w, webutil.MissingUserTokenError("Missing user_id from token claims."))
		return
	}

	userID := token.Claims["user_id"].(string)

	builder := services.NewPreferencesBuilder()
	validator := valiant.NewValidator(req.Body)
	err := validator.Validate(&builder)
	if err != nil {
		h.errorWriter.Write(w, webutil.ValidationError([]string{err.Error()}))
		return
	}

	preferences, err := builder.ToPreferences()
	if err != nil {
		h.errorWriter.Write(w, webutil.ValidationError([]string{err.Error()}))
		return
	}

	transaction := connection.Transaction()
	transaction.Begin()
	err = h.preferences.Update(transaction, preferences, builder.GlobalUnsubscribe, userID)
	if err != nil {
		transaction.Rollback()

		switch err.(type) {
		case services.MissingKindOrClientError, services.CriticalKindError:
			h.errorWriter.Write(w, webutil.ValidationError([]string{err.Error()}))
		default:
			h.errorWriter.Write(w, err)
		}
		return
	}

	err = transaction.Commit()
	if err != nil {
		h.errorWriter.Write(w, models.NewTransactionCommitError(err.Error()))
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
func (h UAAScopeHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	conn := context.Get("database").(DatabaseInterface).Connection()
	scope := strings.TrimPrefix(req.URL.Path, "/uaa_scopes/")
	vcapRequestID := context.Get(VCAPRequestIDKey).(string)

	output, err := h.notify.Execute(conn, req, context, scope, h.strategy, GUIDValidator{}, vcapRequestID)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write(output)
}
func (h UpdateDefaultHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	template, err := NewTemplateParams(req.Body)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	err = h.updater.Update(context.Get("database").(DatabaseInterface), models.DefaultTemplateID, template.ToModel())
	if err != nil {
		h.errorWriter.Write(w, err)
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #20
0
func (h GetHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	messageID := strings.Split(req.URL.Path, "/messages/")[1]

	message, err := h.finder.Find(context.Get("database").(DatabaseInterface), messageID)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	var document struct {
		Status string `json:"status"`
	}
	document.Status = message.Status

	writeJSON(w, http.StatusOK, document)
}
Example #21
0
func (h UpdateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	templateID := strings.Split(req.URL.String(), "/templates/")[1]

	templateParams, err := NewTemplateParams(req.Body)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	err = h.updater.Update(context.Get("database").(DatabaseInterface), templateID, templateParams.ToModel())
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #22
0
func (h CreateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	templateParams, err := NewTemplateParams(req.Body)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	template := templateParams.ToModel()

	templateID, err := h.creator.Create(context.Get("database").(DatabaseInterface), template)
	if err != nil {
		h.errorWriter.Write(w, webutil.TemplateCreateError{})
		return
	}

	w.WriteHeader(http.StatusCreated)
	w.Write([]byte(`{"template_id":"` + templateID + `"}`))
}
func (h GetPreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	token := context.Get("token").(*jwt.Token)

	if _, ok := token.Claims["user_id"]; !ok {
		h.errorWriter.Write(w, webutil.MissingUserTokenError("Missing user_id from token claims."))
		return
	}

	userID := token.Claims["user_id"].(string)

	parsed, err := h.preferences.Find(context.Get("database").(DatabaseInterface), userID)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	writeJSON(w, http.StatusOK, parsed)
}
func (h AssignTemplateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	clientID, notificationID := h.parseURL(req.URL.Path)

	var templateAssignment TemplateAssignment
	err := json.NewDecoder(req.Body).Decode(&templateAssignment)
	if err != nil {
		h.errorWriter.Write(w, webutil.ParseError{})
		return
	}

	database := context.Get("database").(DatabaseInterface)
	err = h.templateAssigner.AssignToNotification(database, clientID, notificationID, templateAssignment.Template)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
func (h UpdateUserPreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	database := context.Get("database").(DatabaseInterface)
	connection := database.Connection()

	userGUID := regexp.MustCompile(".*/user_preferences/(.*)").FindStringSubmatch(req.URL.Path)[1]

	builder := services.NewPreferencesBuilder()
	validator := valiant.NewValidator(req.Body)
	err := validator.Validate(&builder)
	if err != nil {
		h.errorWriter.Write(w, webutil.ValidationError([]string{err.Error()}))
		return
	}

	preferences, err := builder.ToPreferences()
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	transaction := connection.Transaction()
	transaction.Begin()
	err = h.preferences.Update(transaction, preferences, builder.GlobalUnsubscribe, userGUID)
	if err != nil {
		transaction.Rollback()

		switch err.(type) {
		case services.MissingKindOrClientError, services.CriticalKindError:
			h.errorWriter.Write(w, webutil.ValidationError([]string{err.Error()}))
		default:
			h.errorWriter.Write(w, err)
		}
		return
	}

	err = transaction.Commit()
	if err != nil {
		h.errorWriter.Write(w, models.NewTransactionCommitError(err.Error()))
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
func (h AssignTemplateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	routeRegex := regexp.MustCompile("/clients/(.*)/template")
	clientID := routeRegex.FindStringSubmatch(req.URL.Path)[1]

	var templateAssignment TemplateAssignment
	err := json.NewDecoder(req.Body).Decode(&templateAssignment)
	if err != nil {
		h.errorWriter.Write(w, webutil.ParseError{})
		return
	}

	database := context.Get("database").(DatabaseInterface)
	err = h.templateAssigner.AssignToClient(database, clientID, templateAssignment.Template)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #27
0
func (h UpdateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	var updateParams NotificationUpdateParams

	updateParams, err := NewNotificationParams(req.Body)
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	regex := regexp.MustCompile("/clients/(.*)/notifications/(.*)")
	matches := regex.FindStringSubmatch(req.URL.Path)
	clientID, notificationID := matches[1], matches[2]

	err = h.updater.Update(context.Get("database").(DatabaseInterface), updateParams.ToModel(clientID, notificationID))
	if err != nil {
		h.errorWriter.Write(w, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #28
0
func (h DeleteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	splitURL := strings.Split(req.URL.Path, "/")
	senderID := splitURL[len(splitURL)-1]

	conn := context.Get("database").(collections.DatabaseInterface).Connection()
	clientID := context.Get("client_id").(string)

	err := h.senders.Delete(conn, senderID, clientID)
	if err != nil {
		switch err.(type) {
		case collections.NotFoundError:
			w.WriteHeader(http.StatusNotFound)
		default:
			w.WriteHeader(http.StatusInternalServerError)
		}
		w.Write([]byte(fmt.Sprintf(`{ "errors": [ %q ]}`, err)))
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #29
0
func (h DeleteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	splitURL := strings.Split(req.URL.Path, "/")
	campaignTypeID := splitURL[len(splitURL)-1]
	senderID := splitURL[len(splitURL)-3]

	database := context.Get("database").(DatabaseInterface)
	if err := h.collection.Delete(database.Connection(), campaignTypeID, senderID, context.Get("client_id").(string)); err != nil {
		switch err.(type) {
		case collections.NotFoundError:
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprintf(w, `{"errors": [%q]}`, err)
			return
		default:
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(w, `{"errors": ["Delete failed with error: %s"]}`, err)
			return
		}
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #30
0
func (h ListHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
	connection := context.Get("database").(collections.DatabaseInterface).Connection()

	clientID := context.Get("client_id").(string)

	templates, err := h.templates.List(connection, clientID)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, `{"errors": [ %q ] }`, err)
		return
	}

	responseList := []interface{}{}

	for _, template := range templates {
		var metadata map[string]interface{}

		err = json.Unmarshal([]byte(template.Metadata), &metadata)
		if err != nil {
			panic(err)
		}

		responseList = append(responseList, map[string]interface{}{
			"id":       template.ID,
			"name":     template.Name,
			"text":     template.Text,
			"html":     template.HTML,
			"subject":  template.Subject,
			"metadata": metadata,
		})
	}

	listResponse, _ := json.Marshal(map[string]interface{}{
		"templates": responseList,
	})

	w.Write(listResponse)

}