Ejemplo 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} ??

	}
}
Ejemplo n.º 2
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)

}
Ejemplo n.º 3
0
// creatKeyValue creates a new book in the collection
func (c *Context) createKeyValue(w web.ResponseWriter, r *web.Request) {

	document, result, err := validateRequestData(
		"file://"+schemaDir+"/keyvalue.post.body.json",
		r,
	)

	// lazy output & not setting headers

	if err != nil || !result.Valid() {
		w.Header()
		fmt.Fprintf(w, "The document is not valid. see errors :\n")

		if result != nil {
			for _, desc := range result.Errors() {
				fmt.Fprintf(w, "- %s\n", desc)
			}
		} else {
			fmt.Fprint(w, "The document wasn't valid JSON.")
		}
		return

	}

	fmt.Fprint(w, "success", "\n")
	fmt.Fprint(w, document, "\n")
	fmt.Fprint(w, result, "\n")

}
Ejemplo n.º 4
0
func (c *context) generateToken(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {

	if req.Header.Get("X-Docker-Token") == "true" {

		a, ok := accessMap[req.Method]

		if !ok {
			http.Error(rw, "", http.StatusMethodNotAllowed)
			return
		}

		sig, err := runningContext.TokenAuth.CreateToken(&handler.AuthRequest{
			Name:    fmt.Sprintf("%v/%v", c.namespace, c.repo),
			Actions: []string{a.name},
			Service: runningContext.TokenAuth.Service,
		})

		if !ok {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		t := fmt.Sprintf(`signature=%v,repository="%v/%v",access=%v`, sig, c.namespace, c.repo, a.name)

		rw.Header().Set("X-Docker-Endpoints", runningContext.Endpoints)
		rw.Header().Set("WWW-Authenticate", "Token "+t)
		rw.Header().Set("X-Docker-Token", t)
	}

	next(rw, req)
}
Ejemplo n.º 5
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())
	}
}
Ejemplo n.º 6
0
//CorsMiddleware add the header Access-Control-Allow-Origin to the OPTIONS req.
func (c *Context) CorsMiddleware(rw web.ResponseWriter, r *web.Request,
	next web.NextMiddlewareFunc) {
	if r.Method != "OPTIONS" {
		next(rw, r)
		return
	}

	rw.Header().Set("Access-Control-Allow-Origin", "*")
}
Ejemplo n.º 7
0
// SetResponseType is a middleware function that sets the appropriate response
// headers. Currently, it is setting the "Content-Type" to "application/json" as
// well as the necessary headers in order to enable CORS for Swagger usage.
func (s *ServerOpenchainREST) SetResponseType(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	rw.Header().Set("Content-Type", "application/json")

	// Enable CORS
	rw.Header().Set("Access-Control-Allow-Origin", "*")
	rw.Header().Set("Access-Control-Allow-Headers", "accept, content-type")

	next(rw, req)
}
Ejemplo n.º 8
0
func (c *Context) RetrieveStats(rw web.ResponseWriter, req *web.Request) {
	rw.Header().Set("Content-Type", "application/json")

	stats := Stats.Data()

	b, _ := json.Marshal(stats)

	rw.Write(b)
}
Ejemplo n.º 9
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)
}
Ejemplo n.º 10
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)
}
Ejemplo n.º 11
0
func (c *Context) ResourceConfigMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	var err error
	c.Resource, err = c.Config.FindResourceByRequest(req.Request)
	if err != nil {
		if err.Error() == "Method" {
			rw.Header().Set("Allow", strings.Join(c.Resource.Methods, ", "))
			c.RenderError(rw, errors.New("Method Not Allowed"), "", http.StatusMethodNotAllowed)
		} else {
			c.RenderError(rw, errors.New("Access Forbidden"), "", http.StatusForbidden)
		}

	} else {
		c.Params = core.Params(req.URL.Path, c.Resource.Regex, c.Resource.Keys)
		next(rw, req)
	}
}
Ejemplo n.º 12
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)
	}

}
Ejemplo n.º 13
0
func (c *context) getImages(rw web.ResponseWriter, req *web.Request) {

	rw.Header().Set("Content-Type", "application/json")

	m, err := runningContext.Index.GetIndexImages(c.namespace, c.repo)

	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
	}

	b, err := json.Marshal(m)

	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
	}

	rw.Write(b)
}
Ejemplo n.º 14
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)
	}
}
Ejemplo n.º 15
0
func (c *context) writeToken(rw web.ResponseWriter, req *web.Request) {

	token, err := runningContext.TokenAuth.CreateToken(&c.authReq)

	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	rw.Header().Set("Content-Type", "application/json")

	result, err := json.Marshal(&map[string]string{"token": token})

	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	rw.Write(result)
}
Ejemplo n.º 16
0
func (c *Context) GetUserInfo(rw web.ResponseWriter, req *web.Request) {
	rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
	session, err := mgo.Dial(os.Getenv("MONGODB_URI"))
	if err != nil {
		panic(err)
		return
	}
	collection := session.DB("crossyio-main").C("users")
	query := make(map[string]interface{})
	query["uuid"] = c.UserInfo["uuid"]
	result := User{}
	merr := collection.Find(query).One(&result)
	if merr != nil {
		panic(merr)
		return
	}
	fmt.Println(result)
	if err := json.NewEncoder(rw).Encode(result); err != nil {
		panic(err)
	}
}
Ejemplo n.º 17
0
// LoginRequired is a middleware that requires a valid toker or redirects to the handshake page.
func (c *Context) LoginRequired(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {

	// If there is no request just continue
	if r == nil {
		next(rw, r)
		return
	}

	// Don't cache anything
	// right now, there's a problem where when you initially logout and then
	// revisit the server, you will get a bad view due to a caching issue.
	// for now, we clear the cache for everything.
	// TODO: revist and cache static assets.
	rw.Header().Set("cache-control", "no-cache, no-store, must-revalidate, private")
	rw.Header().Set("pragma", "no-cache")
	rw.Header().Set("expires", "-1")

	token := helpers.GetValidToken(r.Request, c.Settings)
	tokenPresent := token != nil
	publicUrls := map[string]struct{}{
		"/handshake":      {},
		"/oauth2callback": {},
		"/ping":           {},
		"/assets/img/dashboard-uaa-icon.jpg": {},
	}
	// Check if URL is public so we skip validation
	_, public := publicUrls[r.URL.EscapedPath()]
	if public || tokenPresent {
		next(rw, r)
	} else {
		err := c.redirect(rw, r)
		if err != nil {
			fmt.Println("Error on oauth redirect: ", err.Error())
		}
	}
}
Ejemplo n.º 18
0
func (c *Context) Root(rw web.ResponseWriter, req *web.Request) {
	rw.Header().Set("Content-Type", "application/json")
	rw.Write([]byte("{\"hello\": \"world\"}"))
}
Ejemplo n.º 19
0
func (c *context) commonHeader(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	rw.Header().Set("Docker-Distribution-Api-Version", "registry/2.0")
	next(rw, req)
}
Ejemplo n.º 20
0
func CorsMiddleware(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
	rw.Header().Set("Access-Control-Allow-Origin", "*")
	next(rw, r)
}
Ejemplo n.º 21
0
func (c *Context) OutputJson(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	next(rw, req)
	rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
	resultJson, _ := json.Marshal(c.response)
	rw.Write(resultJson)
}
Ejemplo n.º 22
0
func (c *Context) RedirectOauth(rw web.ResponseWriter, req *web.Request) {
	rw.Header().Set("Location", "https://oauth.crossy.io/?callbackUrl=https://info.crossy.io/oauth/callback")
	rw.WriteHeader(http.StatusFound)
}
Ejemplo n.º 23
0
func (c *Context) SetContentType(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
	header := rw.Header()
	header.Set("Content-Type", "application/json; charset=utf-8")
	next(rw, r)
}
Ejemplo n.º 24
0
func (c *Context) Cors(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
	header := rw.Header()
	header.Set("Access-Control-Allow-Origin", "*")
	next(rw, r)
}
Ejemplo n.º 25
0
func (c *context) commonHeader(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
	rw.Header().Set("X-Docker-Registry-Version", "0.9.1")
	next(rw, req)
}
Ejemplo n.º 26
0
func (c *context) ping(rw web.ResponseWriter, req *web.Request) {
	rw.Header().Set("X-Docker-Registry-Standalone", "false")
	http.Error(rw, "true", http.StatusOK)
}
Ejemplo n.º 27
0
func (c *Context) GetRecipe(rw web.ResponseWriter, req *web.Request) {
	id := req.PathParams["id"]
	r, _ := (*c).api.GetRecipe(id)
	rw.Header().Set("Content-Type", "application/json")
	json.NewEncoder(rw).Encode(r)
}