Esempio n. 1
0
func (c *Context) SearchRecipe(rw web.ResponseWriter, req *web.Request) {

	body, err := getPostedBody(req)
	if err != nil {
		panic(err)
		return
	}

	var query models.Query
	err = json.Unmarshal(body, &query)
	if err != nil {
		handleUnmarshalError(rw, err)
		return
	}

	results, err := (*c).api.SearchRecipe(&query)
	if err != nil {
		rw.WriteHeader(http.StatusInternalServerError)
		panic(err)
	} else {
		rw.Header().Set("Content-Type", "application/json")
		json.NewEncoder(rw).Encode(results) // prefaces with {"Offset": 0} ??

	}
}
Esempio n. 2
0
// TODO Should rewrite to send a 'fail' or an 'error'
func ErrorHandler(rw web.ResponseWriter, err error) {
	if rw.Written() {
		panic(fmt.Sprintf("Data already started to be sent to the client and i had an error: %s", err))
	}
	rw.WriteHeader(http.StatusBadRequest)
	fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err)
}
Esempio n. 3
0
func (c *Context) PostRecipe(rw web.ResponseWriter, req *web.Request) {
	var recipe models.Recipe

	body, err := getPostedBody(req)
	if err != nil {
		panic(err)
		return
	}

	err = json.Unmarshal(body, &recipe)
	if err != nil {
		handleUnmarshalError(rw, err)
		return
	}

	id, err := (*c).api.PostRecipe(&recipe)
	if err != nil {
		panic(err)
		return
	}

	var result models.RecipeId
	result.Id = id
	result.Name = recipe.Name

	rw.WriteHeader(http.StatusCreated)
	rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
	json.NewEncoder(rw).Encode(result)

}
Esempio n. 4
0
func (c *Context) UserRequired(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	var userInfo map[string]interface{}
	if req.URL.Path == "/healthcheck" {
		next(rw, req)
		return
	}

	if req.URL.Path == "/signup" {
		next(rw, req)
		return
	}

	auth := req.Header.Get("Authorization")
	if !strings.HasPrefix(strings.ToLower(auth), "bearer ") {
		rw.WriteHeader(http.StatusUnauthorized)
		return
	}

	token := auth[7:]
	client := &http.Client{}
	authReq, err := http.NewRequest("GET", "https://meshblu.octoblu.com/v2/whoami", nil)
	authReq.Header.Add("Authorization", "Bearer "+token)
	resp, err := client.Do(authReq)
	if err != nil {
		panic(err)
		return
	}
	if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
		panic(err)
	}

	c.Token = token
	c.UserInfo = userInfo
	next(rw, req)
}
// Get counter events in a optionally given time range
// Query parameters: start,end
func (c *Context) CounterByCodeEventsHandler(rw web.ResponseWriter, req *web.Request) {

	code := parseStringPathParameter(req, "code")
	var counter orm.Counter
	db.Where(&orm.Counter{Code: code}).First(&counter)

	if counter.ID == 0 {
		rw.WriteHeader(http.StatusNotFound)
		rw.Write([]byte("Counter not found"))
		return
	}

	start, err := c.parseUintQueryParameter(rw, "start")
	if err != nil {
		return
	}

	end, err := c.parseUintQueryParameter(rw, "end")
	if err != nil {
		return
	}

	var counterEvents []orm.CounterEvent
	orm.GetOrderedWindowedQuery(db, "counter_id", counter.ID, start, end).Find(&counterEvents)

	lastEvent := orm.NewLastCounterEvent(counter)
	if lastEvent.Timestamp > end {
		counterEvents = append(counterEvents, lastEvent)
	}

	marshal(rw, counterEvents)
}
Esempio n. 6
0
func (this *RequestHandler) handleRequestWithPossibleErrors(response web.ResponseWriter, request *web.Request, handler func(web.ResponseWriter, *web.Request) error) {
	response.Header().Add("Access-Control-Allow-Origin", "*")
	err := handler(response, request)
	if err != nil {
		response.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(response, err.Error())
	}
}
Esempio n. 7
0
// Format Error to JSON with moreInfo link
func (c *Renderer) RenderError(rw web.ResponseWriter, err error, info string, status int) {
	js, err := json.MarshalIndent(&JSONError{err.Error(), info}, "", "    ")
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		log.Error("RenderError failed to marshall JSONError", err)
		return
	}
	header := rw.Header()
	header.Set("Content-Type", "application/json")
	rw.WriteHeader(status)
	rw.Write(js)
}
Esempio n. 8
0
func (c *ApiContext) ValidateAwsCredentials(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
	if ok := validatePresenceRequest(r, "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"); !ok {
		rw.WriteHeader(http.StatusUnauthorized)
		writeJson(rw, map[string]string{
			"error": "missing credentials",
		})
	} else {
		creds := credentials.NewStaticCredentials(r.FormValue("AWS_ACCESS_KEY_ID"), r.FormValue("AWS_SECRET_ACCESS_KEY"), "")
		c.AwsCredentials = creds
		next(rw, r)
	}
}
Esempio n. 9
0
//SaveTask handles the endpoint POST /todo
func (c *Context) SaveTask(rw web.ResponseWriter, req *web.Request) {
	var task db.Task

	decoder := json.NewDecoder(req.Body)
	if decoder != nil {
		if err := decoder.Decode(&task); err == nil {
			man.Create(&task)
			rw.WriteHeader(http.StatusOK)
		} else {
			fmt.Fprint(rw, jsonError("trying decode, but "+err.Error()))
		}
	}
}
Esempio n. 10
0
File: main.go Progetto: ae6rt/goref
func (c *WidgetContext) MMUInfo(rw web.ResponseWriter, req *web.Request) {
	build := mmu.Build{Name: appName, Version: appVersion}
	git := mmu.Git{Branch: buildCommitBranch, Commit: mmu.Commit{ID: buildCommit, Time: buildCommitTime}}
	mgtEndpoints := mmu.ManagementEndpoints{Info: "/internal/info", Health: "/internal/health"}
	serviceDependencies := []mmu.ServiceDependency{mmu.ServiceDependency{ServiceID: "auth", Version: "2"}}
	info := mmu.Info{Build: build, Git: git, ManagementEndpoints: mgtEndpoints, ServiceDependencies: serviceDependencies, SDK: buildGoSDK}
	if data, err := json.Marshal(&info); err != nil {
		rw.WriteHeader(500)
		return
	} else {
		rw.Write(data)
	}
}
Esempio n. 11
0
func (c *Context) QueryVarsMiddleware(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {

	values, err := parseQueryParams(rw, r)
	if err != nil {
		log.Println(err)
		rw.WriteHeader(http.StatusBadRequest)
		rw.Write([]byte("Malformed URL"))
		return
	}

	c.values = &values
	next(rw, r)
}
// Get specific thermometer by code
func (c *Context) ThermometerByCodeHandler(rw web.ResponseWriter, req *web.Request) {

	code := parseStringPathParameter(req, "code")
	var thermometer orm.Thermometer
	db.Where(&orm.Thermometer{Code: code}).First(&thermometer)

	if thermometer.ID == 0 {
		rw.WriteHeader(http.StatusNotFound)
		rw.Write([]byte("Thermometer not found"))
		return
	}

	marshal(rw, thermometer)
}
Esempio n. 13
0
// GetBlockByNumber returns the data contained within a specific block in the
// blockchain. The genesis block is block zero.
func (s *ServerOpenchainREST) GetBlockByNumber(rw web.ResponseWriter, req *web.Request) {
	// Parse out the Block id
	blockNumber, err := strconv.ParseUint(req.PathParams["id"], 10, 64)

	// Check for proper Block id syntax
	if err != nil {
		// Failure
		rw.WriteHeader(400)
		fmt.Fprintf(rw, "{\"Error\": \"Block id must be an integer (uint64).\"}")
	} else {
		// Retrieve Block from blockchain
		block, err := s.server.GetBlockByNumber(context.Background(), &pb.BlockNumber{Number: blockNumber})

		// Check for error
		if err != nil {
			// Failure
			switch err {
			case oc.ErrNotFound:
				rw.WriteHeader(http.StatusNotFound)
			default:
				rw.WriteHeader(http.StatusInternalServerError)
			}
			fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err)
		} else {
			// Success
			rw.WriteHeader(http.StatusOK)
			encoder := json.NewEncoder(rw)
			encoder.Encode(block)
		}
	}
}
Esempio n. 14
0
// GoSlow waits until you are ready
func GoSlow(response web.ResponseWriter, request *web.Request) {
	rawDelayStr := request.PathParams["delay"]
	delayStr := fmt.Sprintf("%vms", rawDelayStr)
	delay, err := time.ParseDuration(delayStr)
	if err != nil {
		log.Printf("error: %v", err.Error())
		response.WriteHeader(http.StatusNotAcceptable)
		fmt.Fprint(response, `{"error": "'GET /:delay', delay must be an integer"}`)
		return
	}

	time.Sleep(delay)
	response.WriteHeader(http.StatusOK)
	fmt.Fprintf(response, `{"delay": %v}`, rawDelayStr)
}
Esempio n. 15
0
// Renders from struct to JSON
func (a *Renderer) Render(rw web.ResponseWriter, model interface{}, status int) {
	jsonString, err := json.MarshalIndent(&model, "", "    ")
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		log.Error("Render failed to marshall model", err)
		return
	}
	header := rw.Header()
	header.Set("Content-Type", "application/json")
	header.Set("Access-Control-Allow-Origin", "*")
	header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	header.Set("Access-Control-Allow-Headers", "Authorization")
	rw.WriteHeader(status)
	rw.Write(jsonString)
}
// MeshbluAuth checks auth headers and puts them into the context
func (context *AuthContext) MeshbluAuth(response web.ResponseWriter, request *web.Request, next web.NextMiddlewareFunc) {
	if request.URL.Path == "/healthcheck" {
		next(response, request)
		return
	}
	uuid, token, ok := request.BasicAuth()
	if !ok {
		response.WriteHeader(http.StatusForbidden)
		fmt.Fprint(response, `{"error": "Not Authorized"}`)
		return
	}
	context.uuid = uuid
	context.token = token
	next(response, request)
}
Esempio n. 17
0
// GetBlockchainInfo returns information about the blockchain ledger such as
// height, current block hash, and previous block hash.
func (s *ServerOpenchainREST) GetBlockchainInfo(rw web.ResponseWriter, req *web.Request) {
	info, err := s.server.GetBlockchainInfo(context.Background(), &google_protobuf.Empty{})

	encoder := json.NewEncoder(rw)

	// Check for error
	if err != nil {
		// Failure
		rw.WriteHeader(400)
		fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err)
	} else {
		// Success
		rw.WriteHeader(200)
		encoder.Encode(info)
	}
}
Esempio n. 18
0
func marshal(rw web.ResponseWriter, v interface{}) {

	buffer, err := json.Marshal(v)
	if err != nil {
		log.Println("Error marshalling JSON")
		rw.WriteHeader(http.StatusInternalServerError)
		return
	}

	rw.Header().Set("Content-Type", "application/json; charset=utf-8")

	if _, err = rw.Write(buffer); err != nil {
		log.Println("Error writing JSON to buffer")
		rw.WriteHeader(http.StatusInternalServerError)
	}

}
Esempio n. 19
0
func (c *Context) parseUintQueryParameter(rw web.ResponseWriter, name string) (ret uint64, err error) {

	s := c.values.Get(name)
	if s == "" {
		return 0, nil
	}

	ret, err = parseUintFromString(s)
	if err != nil {
		log.Println("Error parsing uint64 " + name + ": " + s)
		log.Println(err)
		rw.WriteHeader(http.StatusBadRequest)
		rw.Write([]byte("Malformed parameter " + name))
	}

	return
}
Esempio n. 20
0
// GetPeers returns a list of all peer nodes currently connected to the target peer.
func (s *ServerOpenchainREST) GetPeers(rw web.ResponseWriter, req *web.Request) {
	peers, err := s.server.GetPeers(context.Background(), &google_protobuf.Empty{})

	encoder := json.NewEncoder(rw)

	// Check for error
	if err != nil {
		// Failure
		rw.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err)
		restLogger.Error(fmt.Sprintf("{\"Error\": \"Querying network peers -- %s\"}", err))
	} else {
		// Success
		rw.WriteHeader(http.StatusOK)
		encoder.Encode(peers)
	}
}
// CreateMessage creates a message
func (context *AuthContext) CreateMessage(response web.ResponseWriter, request *web.Request) {
	buf := new(bytes.Buffer)
	buf.ReadFrom(request.Body)
	body := buf.String()

	currentTime := time.Now().UnixNano() / (1000 * 1000)
	job := fmt.Sprintf(`{"auth":{"uuid":"%v","token":"%v"},"http":%v,"message":%v}`, context.uuid, context.token, currentTime, body)
	conn := context.redis.Get()
	_, err := conn.Do("LPUSH", "meshblu-messages", job)
	if err != nil {
		response.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(response, `{"error": "%v"}`, err.Error())
		return
	}
	conn.Close()

	response.WriteHeader(http.StatusOK)
	fmt.Fprint(response, body)
}
Esempio n. 22
0
func (c *Context) GeneratePresigned(rw web.ResponseWriter, req *web.Request) {
	rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
	rw.WriteHeader(http.StatusOK)
	parts := []string{
		c.CrossyInfo["username"].(string),
		req.PathParams["organization"],
		req.PathParams["project"],
		req.PathParams["packager"],
		req.PathParams["version"],
		req.PathParams["platform"],
		req.PathParams["arch"],
		req.PathParams["file"],
	}
	path := strings.Join(parts, "/")
	presignedURL := GetS3Presigned("contribute-crossy-io", path, 90)
	if err := json.NewEncoder(rw).Encode(presignedURL); err != nil {
		panic(err)
	}
}
Esempio n. 23
0
// DeleteEnrollmentID removes the login token of the specified user from the
// Devops server. Once the login token is removed, the specified user will no
// longer be able to transact without logging in again. On the REST interface,
// this method may be used as a means of logging out an active client.
func (s *ServerOpenchainREST) DeleteEnrollmentID(rw web.ResponseWriter, req *web.Request) {
	// Parse out the user enrollment ID
	enrollmentID := req.PathParams["id"]

	// Retrieve the REST data storage path
	// Returns /var/openchain/production/client/
	localStore := getRESTFilePath()

	// Construct the path to the login token and to the directory containing the
	// cert and key.
	// /var/openchain/production/client/loginToken_username
	loginTok := localStore + "loginToken_" + enrollmentID
	// /var/openchain/production/crypto/client/username
	cryptoDir := viper.GetString("peer.fileSystemPath") + "/crypto/client/" + enrollmentID

	// Stat both paths to determine if the user is currently logged in
	_, err1 := os.Stat(loginTok)
	_, err2 := os.Stat(cryptoDir)

	// If the user is not logged in, nothing to delete. Return OK.
	if os.IsNotExist(err1) && os.IsNotExist(err2) {
		rw.WriteHeader(http.StatusOK)
		fmt.Fprintf(rw, "{\"OK\": \"User %s is not logged in.\"}", enrollmentID)
		restLogger.Info("User '%s' is not logged in.\n", enrollmentID)

		return
	}

	// The user is logged in, delete the user's login token
	if err := os.RemoveAll(loginTok); err != nil {
		rw.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(rw, "{\"Error\": \"Error trying to delete login token for user %s: %s\"}", enrollmentID, err)
		restLogger.Error(fmt.Sprintf("{\"Error\": \"Error trying to delete login token for user %s: %s\"}", enrollmentID, err))

		return
	}

	// The user is logged in, delete the user's cert and key directory
	if err := os.RemoveAll(cryptoDir); err != nil {
		rw.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(rw, "{\"Error\": \"Error trying to delete login directory for user %s: %s\"}", enrollmentID, err)
		restLogger.Error(fmt.Sprintf("{\"Error\": \"Error trying to delete login directory for user %s: %s\"}", enrollmentID, err))

		return
	}

	rw.WriteHeader(http.StatusOK)
	fmt.Fprintf(rw, "{\"OK\": \"Deleted login token and directory for user %s.\"}", enrollmentID)
	restLogger.Info("Deleted login token and directory for user %s.\n", enrollmentID)

	return
}
// Get thermometer readings in a optionally given time range
// Query parameters: start,end
func (c *Context) ThermometerByCodeGetReadingsHandler(rw web.ResponseWriter, req *web.Request) {

	code := parseStringPathParameter(req, "code")
	var thermometer orm.Thermometer
	db.Where(&orm.Thermometer{Code: code}).First(&thermometer)

	if thermometer.ID == 0 {
		rw.WriteHeader(http.StatusNotFound)
		rw.Write([]byte("Thermometer not found"))
		return
	}

	start, err := c.parseUintQueryParameter(rw, "start")
	if err != nil {
		return
	}

	end, err := c.parseUintQueryParameter(rw, "end")
	if err != nil {
		return
	}

	var thermometerReadings []orm.ThermometerReading
	orm.GetOrderedWindowedQuery(db, "thermometer_id", thermometer.ID, start, end).Find(&thermometerReadings)

	startReading := orm.ThermometerReading{
		Reading:       thermometerReadings[0].Reading,
		Timestamp:     start,
		ThermometerID: thermometer.ID,
	}

	endReading := orm.ThermometerReading{
		Reading:       thermometerReadings[len(thermometerReadings)-1].Reading,
		Timestamp:     end,
		ThermometerID: thermometer.ID,
	}

	thermometerReadings = append([]orm.ThermometerReading{startReading}, thermometerReadings...)
	thermometerReadings = append(thermometerReadings, endReading)

	marshal(rw, thermometerReadings)
}
Esempio n. 25
0
// Tick counter by code
func (c *Context) CounterByCodeTickHandler(rw web.ResponseWriter, req *web.Request) {

	code := parseStringPathParameter(req, "code")
	var counter orm.Counter
	db.Where(&orm.Counter{Code: code}).First(&counter)

	if counter.ID == 0 {
		rw.WriteHeader(http.StatusNotFound)
		rw.Write([]byte("Counter not found"))
		return
	}

	counterEvent := orm.NewTickCounterEvent(counter)
	db.Create(&counterEvent)

	counter.Reading = counterEvent.Reading
	counter.LastTick = counterEvent.Timestamp
	db.Save(counter)

	marshal(rw, counterEvent)
}
Esempio n. 26
0
// GetEnrollmentID checks whether a given user has already registered with the
// Devops server.
func (s *ServerOpenchainREST) GetEnrollmentID(rw web.ResponseWriter, req *web.Request) {
	// Parse out the user enrollment ID
	enrollmentID := req.PathParams["id"]

	// Retrieve the REST data storage path
	// Returns /var/openchain/production/client/
	localStore := getRESTFilePath()

	// If the user is already logged in, return OK. Otherwise return error.
	if _, err := os.Stat(localStore + "loginToken_" + enrollmentID); err == nil {
		rw.WriteHeader(http.StatusOK)
		fmt.Fprintf(rw, "{\"OK\": \"User %s is already logged in.\"}", enrollmentID)
		restLogger.Info("User '%s' is already logged in.\n", enrollmentID)
	} else {
		rw.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintf(rw, "{\"Error\": \"User %s must log in.\"}", enrollmentID)
		restLogger.Info("User '%s' must log in.\n", enrollmentID)
	}

	return
}
Esempio n. 27
0
// GetTransactionByUUID returns a transaction matching the specified UUID
func (s *ServerOpenchainREST) GetTransactionByUUID(rw web.ResponseWriter, req *web.Request) {
	// Parse out the transaction UUID
	txUUID := req.PathParams["uuid"]

	// Retrieve the transaction matching the UUID
	tx, err := s.server.GetTransactionByUUID(context.Background(), txUUID)

	// Check for Error
	if err != nil {
		switch err {
		case oc.ErrNotFound:
			rw.WriteHeader(http.StatusNotFound)
			fmt.Fprintf(rw, "{\"Error\": \"Transaction %s is not found.\"}", txUUID)
		default:
			rw.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(rw, "{\"Error\": \"Error retrieving transaction %s: %s.\"}", txUUID, err)
			restLogger.Error(fmt.Sprintf("{\"Error\": \"Error retrieving transaction %s: %s.\"}", txUUID, err))
		}
	} else {
		// Return existing transaction
		rw.WriteHeader(http.StatusOK)
		encoder := json.NewEncoder(rw)
		encoder.Encode(tx)
		restLogger.Info(fmt.Sprintf("Successfully retrieved transaction: %s", txUUID))
	}
}
Esempio n. 28
0
//AuthorizationMiddleware gets the Authorization header and verify if is valid
func (c *Context) AuthorizationMiddleware(rw web.ResponseWriter, r *web.Request,
	next web.NextMiddlewareFunc) {
	authArray := r.Header["Authorization"]
	if len(authArray) > 0 {
		authorization := strings.TrimSpace(authArray[0])
		content := strings.Split(authorization, " ")
		if len(content) > 1 {
			method := content[0]
			token := content[1]

			if method == "Bearer" && token == "testkey123" {
				next(rw, r)
			} else {
				rw.WriteHeader(http.StatusForbidden)
				fmt.Fprint(rw, jsonError("invalid token"))
			}
		} else {
			rw.WriteHeader(http.StatusForbidden)
			fmt.Fprint(rw, jsonError("missing token"))
		}
	} else {
		rw.WriteHeader(http.StatusForbidden)
		fmt.Fprint(rw, jsonError("missing authorization header"))
	}
}
Esempio n. 29
0
//GetTask handles the endpoint GET /todo/1
func (c *Context) GetTask(rw web.ResponseWriter, req *web.Request) {
	id, err := idFromParam(req)
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(rw, jsonError("missing id param"))
		return
	}

	task, err := man.Get(id)
	if err != nil {
		rw.WriteHeader(http.StatusNotFound)
		fmt.Fprint(rw, jsonError("task not found"))
		return
	}

	jsonTask, err := json.Marshal(task)
	if err != nil {
		log.Println(err)
		rw.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(rw, jsonError("error building response"))
		return
	}

	fmt.Fprint(rw, string(jsonTask))
}
Esempio n. 30
0
func (c *Context) Clean(rw web.ResponseWriter, req *web.Request) {
	var msg string
	defer c.WriteResponse(msg)

	var stackDir string
	localComps := engine.LocalComponents()
	for _, comp := range localComps {
		cmd := exec.Command(comp.DeployFilepath, "stop")
		output, err := cmd.CombinedOutput()
		if err != nil {
			rw.WriteHeader(http.StatusInternalServerError)
			msg = fmt.Sprintf("Failed to run command: %s ,error: %v", comp.DeployFilepath+" stop", err)
			return
		}
		log.Debug(output)
		if stackDir == "" {
			stackDir = filepath.Dir(comp.Directory)
		} else if stackDir != filepath.Dir(comp.Directory) {
			rw.WriteHeader(http.StatusInternalServerError)
			msg = "stack directory is different."
			return
		}
	}

	if stackDir != "" {
		err := os.RemoveAll(stackDir)
		if err != nil {
			rw.WriteHeader(http.StatusInternalServerError)
			msg = err.Error()
			return
		}
		msg = "clean ok."
	}
}