Esempio n. 1
1
func UpdatePetWithFormHandler(c *gin.Context) {
	queryValues := c.Request.URL.Query()

	petId := queryValues.Get("petId")
	if petId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"missing": "petId"})
		return
	}

	name := c.Request.PostFormValue("name")
	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"missing": "name"})
		return
	}

	status := c.Request.PostFormValue("status")
	if status == "" {
		c.JSON(http.StatusBadRequest, gin.H{"missing": "status"})
		return
	}

	if err := operations.UpdatePetWithForm(petId, name, status); err == nil {
		c.String(http.StatusOK, "Success")
	} else {
		c.JSON(http.StatusBadRequest, err)
	}
}
Esempio n. 2
0
func (s *Server) upload(c *gin.Context) {
	hash := c.Param("hash")
	filepath := s.hashFilepath(hash)

	stat, err := os.Stat(filepath)
	if err != nil && stat != nil {
		c.String(200, "already exists")
		return
	}

	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		c.AbortWithError(500, err)
		return
	}
	body_hash := fmt.Sprintf("%x", md5.Sum(body))

	if hash != body_hash {
		c.AbortWithError(500, fmt.Errorf("invalid data hash %s", body_hash))
		return
	}

	err = ioutil.WriteFile(filepath, body, 0666)
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	c.String(200, "created")
}
Esempio n. 3
0
func (sr *StreamsResource) Show(c *gin.Context) {
	buildID := c.Params.ByName("id")
	streamType := c.Params.ByName("type")

	build, err := sr.buildRepo.Find(buildID)
	if err == builds.ErrNotFound {
		c.String(http.StatusNotFound, "")
		return
	} else if err != nil {
		c.String(http.StatusInternalServerError, "")
		return
	}

	stream, err := sr.streamRepo.Find(build.ID)
	if err == streams.ErrNotFound {
		c.String(http.StatusNotFound, "")
		return
	} else if err != nil {
		c.String(http.StatusInternalServerError, "")
		return
	}

	switch streamType {
	case "build":
		streamOutput(c, stream.BuildOutput, true)
	case "push":
		streamOutput(c, stream.PushOutput, false)
	default:
		c.String(http.StatusNotFound, "")
	}
}
func UserHandler(g *gin.Context) {

	// ->/user/{name}/{city}
	name := g.Params.ByName("name")
	city := g.Params.ByName("city")
	g.String(200, "%s, welcome to %s!", name, city)
}
Esempio n. 5
0
func EditSex(c *gin.Context) {
	Mng = c.MustGet("db").(db.Database)
	rnd = c.MustGet("rnd").(*render.Render)
	name := c.Param("name")
	token := csrf.GetToken(c)

	sexes, err := Mng.Collection("sexes")
	if err != nil {
		c.String(http.StatusInternalServerError, "Нет связи с бд")
	}

	res := sexes.Find(db.Cond{"name": name})
	if res != nil {
		var sex models.Sex
		res.One(&sex)

		rnd.HTML(c.Writer, http.StatusOK, "common/edit", gin.H{
			"_csrf":    token,
			"TypeName": "sex",
			"data":     sex,
		})
	} else {
		c.String(http.StatusInternalServerError, "Не удалось найти пол")
	}

}
Esempio n. 6
0
// commandRefreshSettings precesses request to refresh settings
func (s *DefaultServer) commandRefreshSettings(c *gin.Context, args Args) {
	if err := s.refreshSettings(); err != nil {
		c.String(http.StatusOK, "false")
		return
	}
	c.String(http.StatusOK, "true")
}
func handler(c *gin.Context) {
	URL := c.PostForm("URL")
	name := c.PostForm("Name")
	status := c.PostForm("Status")
	slack := SlackParams{
		Attachments: []SlackAttachments{
			SlackAttachments{
				Color:    color(status),
				Fallback: fallback(name, status),
				Title:    title(name, status),
				Text:     text(URL),
			},
		},
		Username:  "******",
		Mrkdwn:    true,
		IconEmoji: ":cake:",
	}
	url_slack := fmt.Sprintf("https://hooks.slack.com/%s", c.Param("url"))
	b, err := json.Marshal(slack)
	if err != nil {
		c.String(400, "fail")
		return
	}
	http.PostForm(url_slack, url.Values{"payload": {string(b)}})
	c.String(200, "ok")
}
Esempio n. 8
0
func PostRepoKey(c *gin.Context) {
	repo := session.Repo(c)
	keys, err := store.GetKey(c, repo)
	if err != nil {
		c.String(404, "Error fetching repository key")
		return
	}
	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		c.String(500, "Error reading private key from body. %s", err)
		return
	}
	pkey := crypto.UnmarshalPrivateKey(body)
	if pkey == nil {
		c.String(500, "Cannot unmarshal private key. Invalid format.")
		return
	}

	keys.Public = string(crypto.MarshalPublicKey(&pkey.PublicKey))
	keys.Private = string(crypto.MarshalPrivateKey(pkey))

	err = store.UpdateKey(c, keys)
	if err != nil {
		c.String(500, "Error updating repository key")
		return
	}
	c.String(201, keys.Public)
}
Esempio n. 9
0
func directaccessHandler(ctx *gin.Context) {
	db := ctx.Params.ByName("database")
	path := ctx.Params.ByName("path")
	layer := ctx.Params.ByName("layer")

	cmd := bytengine.Command{
		Name:    "directaccess",
		IsAdmin: false,
		Args:    make(map[string]interface{}),
		Options: make(map[string]interface{}),
	}
	cmd.Args["database"] = db
	cmd.Args["path"] = path
	cmd.Args["layer"] = layer
	cmd.Args["writer"] = ctx.Writer

	if layer == "json" {
		ctx.Writer.Header().Set("Content-Type", "application/json")
	} else {
		ctx.Writer.Header().Set("Content-Type", "application/octet-stream")
	}

	req := EngineRequest{
		Token:        "",
		Command:      &cmd,
		ResponseChan: make(chan EngineResponse),
	}
	EngineRequestChan <- &req
	rep := <-req.ResponseChan
	if rep.Error != nil {
		data := errorResponse(rep.Error)
		ctx.String(404, string(data))
		return
	}
}
Esempio n. 10
0
// Handles the simple successful return status
func HandleSucces(c *gin.Context, status int, message gin.H) {
	if status == 204 {
		c.String(status, "")
	} else {
		c.JSON(status, message)
	}
}
Esempio n. 11
0
func handler(c *gin.Context) {
	if !gConfig.UI.DisableUI {
		c.Redirect(http.StatusTemporaryRedirect, gConfig.Repos.Path)
	} else {
		c.String(200, "nothing to see here\n")
	}
}
Esempio n. 12
0
func processPRHook(c *gin.Context, prHook *model.PRHook) {
	repo, user, err := getRepoAndUser(c, prHook.Repo.Slug)
	if err != nil {
		return
	}

	err = remote.SetStatus(c, user, repo, prHook.Number, false)
	if err != nil {
		log.Errorf("Error setting status. %s", err)
		c.String(500, "Error setting status. %s", err)
		return
	}

	config, _, err := getConfigAndMaintainers(c, user, repo)
	if err != nil {
		return
	}

	if prHook.Update && config.DoComment {
		err = remote.WriteComment(c, user, repo, prHook.Number, "The Pull Request has been updated. No comments before this one will count for approval.")
		if err != nil {
			log.Errorf("Error writing comment for status. %s", err)
			c.String(500, "Error writing comment for status. %s", err)
			return
		}
	}

	c.IndentedJSON(200, gin.H{
		"number":   prHook.Number,
		"approved": false,
	})
}
Esempio n. 13
0
func ProviderCheck(ctx *gin.Context) {
	addonId := ctx.Params.ByName("provider")
	failures := xbmc.AddonCheck(addonId)
	translated := xbmc.GetLocalizedString(30243)
	xbmc.Notify("Quasar", fmt.Sprintf("%s: %d", translated, failures), config.AddonIcon())
	ctx.String(200, "")
}
Esempio n. 14
0
func (r *LogsResource) Show(c *gin.Context) {
	buildID := c.Params.ByName("id")
	logType := c.Params.ByName("type")

	build, err := r.buildRepo.Find(buildID)
	if err == builds.ErrNotFound {
		c.String(http.StatusNotFound, "")
		return
	} else if err != nil {
		c.String(http.StatusInternalServerError, "")
		return
	}

	buildLog, err := r.logRepo.FindByBuildID(build.ID, logType)
	if err == builds.ErrNotFound {
		c.String(http.StatusNotFound, "")
		return
	} else if err != nil {
		c.String(http.StatusInternalServerError, err.Error())
		return
	}

	c.Writer.WriteHeader(http.StatusOK)
	c.Writer.Header().Set("Content-Type", "text/plain")

	c.String(http.StatusOK, buildLog.Data)
}
Esempio n. 15
0
func GetMyDashboards(data gin.H, c *gin.Context) func(c *gin.Context) {
	handler := func(c *gin.Context) func(c *gin.Context) {
		token_id, user_id, err := GetTokenFromCookies(c)
		if err != nil {
			return func(c *gin.Context) { c.JSON(401, gin.H{"status": "login_failed"}) }
		} else {
			user, err_db := database.GetUserById(user_id)
			_, err_marshal := json.Marshal(user)
			if err_db == nil && err_marshal == nil {
				dashboard_list, err_dash := database.GetMyDashboardList(user_id, token_id)
				dgroup_list, err_dgroup := database.GetMyDashboardGroupList(user_id, token_id)
				if err_dash == nil && err_dgroup == nil {
					return func(c *gin.Context) {
						c.JSON(200, gin.H{"status": "success", "dashboard_list": dashboard_list, "dashboard_group_list": dgroup_list})
						//c.JSON(200, dashboard_list_json)
					}
				} else {
					return func(c *gin.Context) { c.JSON(401, gin.H{"status": "failed"}) }
				}
			} else {
				return func(c *gin.Context) {
					errors := CombineErrors(err_db, err_marshal)
					e, _ := json.Marshal(errors)
					c.String(200, string(e))
				}
			}
		}
	}
	return handler(c)
}
Esempio n. 16
0
func (ar *APIResource) Index(c *gin.Context) {
	if c.Request.Header.Get("Authorization") == "authenticated" {
		c.String(http.StatusOK, "Index")
	} else {
		c.String(http.StatusForbidden, "forbidden")
	}
}
Esempio n. 17
0
func UpdateUserHandler(c *gin.Context) {
	queryValues := c.Request.URL.Query()

	username := queryValues.Get("username")
	if username == "" {
		c.JSON(http.StatusBadRequest, gin.H{"missing": "username"})
		return
	}

	var body models.User

	if err := c.BindJSON(&body); err != nil {
		return
	}

	if err := body.Validate(); err != nil {
		c.JSON(http.StatusBadRequest, err)
		return
	}

	if err := operations.UpdateUser(username, &body); err == nil {
		c.String(http.StatusOK, "Success")
	} else {
		c.JSON(http.StatusBadRequest, err)
	}
}
// Create Training Job
func (e EndpointContext) CreateTrainingJob(c *gin.Context) {

	// bind to json
	user := c.MustGet(MIDDLEWARE_KEY_USER).(User)
	db := c.MustGet(MIDDLEWARE_KEY_DB).(couch.Database)

	trainingJob := NewTrainingJob(e.Configuration)
	trainingJob.UserID = user.Id

	// bind the input struct to the JSON request
	if ok := c.Bind(trainingJob); !ok {
		errMsg := fmt.Sprintf("Invalid input")
		c.String(400, errMsg)
		return
	}

	logg.LogTo("REST", "Create new TrainingJob: %+v", trainingJob)

	// save training job in db
	trainingJob, err := trainingJob.Insert(db)
	if err != nil {
		c.String(500, err.Error())
		return
	}

	// job will get kicked off by changes listener

	// return solver object
	c.JSON(201, *trainingJob)

}
// Creates a datafile
func (e EndpointContext) CreateDataFileEndpoint(c *gin.Context) {

	user := c.MustGet(MIDDLEWARE_KEY_USER).(User)
	db := c.MustGet(MIDDLEWARE_KEY_DB).(couch.Database)

	datafile := NewDatafile(e.Configuration)
	datafile.UserID = user.DocId()

	// bind the Datafile to the JSON request, which will bind the
	// url field or throw an error.
	if ok := c.Bind(&datafile); !ok {
		errMsg := fmt.Sprintf("Invalid datafile")
		c.String(400, errMsg)
		return
	}

	logg.LogTo("REST", "datafile: %+v", datafile)

	// create a new Datafile object in db
	datafile, err := datafile.Save(db)
	if err != nil {
		errMsg := fmt.Sprintf("Error creating new datafile: %v", err)
		c.String(500, errMsg)
		return
	}

	c.JSON(201, gin.H{"id": datafile.Id})

}
Esempio n. 20
0
func GetFeed(c *gin.Context) {
	user := session.User(c)
	remote := remote.FromContext(c)
	var repos []*model.RepoLite

	// get the repository list from the cache
	reposv, ok := c.Get("repos")
	if ok {
		repos = reposv.([]*model.RepoLite)
	} else {
		var err error
		repos, err = remote.Repos(user)
		if err != nil {
			c.String(400, err.Error())
			return
		}
	}

	feed, err := store.GetUserFeed(c, repos)
	if err != nil {
		c.String(400, err.Error())
		return
	}
	c.JSON(200, feed)
}
func apiDB(c *gin.Context) {
	userId := c.Query("user")

	db, err := sql.Open("mysql", "root@/test")
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()

	stmt, err := db.Prepare("SELECT content FROM testtable WHERE idtesttable = ?")

	res, err := stmt.Query(userId)

	if err != nil {
		panic(err.Error())
	}

	var col1 string
	res.Next()
	err = res.Scan(&col1)

	if err != nil {
		panic(err.Error())
	}
	defer res.Close()

	c.String(http.StatusOK, "Response: %s", col1)
}
Esempio n. 22
0
func (rc *ResourceController) GetResources(ctx *gin.Context) {
	req := ctx.Request
	resourceType := getResourceType(req.URL)

	logger.Log.WithFields(
		logrus.Fields{"resource type": resourceType}).Info("GetResources")

	resources := ptm_models.NewSliceForResourceName(resourceType, 0, 0)
	c := rc.Database().C(ptm_models.GetCollectionName(resourceType))
	// retrieve all documents in the collection
	// TODO Restrict this to resource type, just to be extra safe
	query := buildSearchQuery(resourceType, ctx)
	logger.Log.WithFields(
		logrus.Fields{"query": query}).Info("GetResources")
	err := c.Find(query).All(resources)
	if err != nil {
		if err == mgo.ErrNotFound {
			ctx.String(http.StatusNotFound, "Not Found")
			ctx.Abort()
			return
		} else {
			ctx.AbortWithError(http.StatusBadRequest, err)
			return
		}
	}

	ctx.JSON(http.StatusOK, resources)
}
Esempio n. 23
0
func updateGoogleGet(c *gin.Context) {
	db := c.MustGet("db").(*database.Database)

	params := utils.ParseParams(c.Request)

	usr := params.GetByName("user")
	license := params.GetByName("license")

	valid, err := user.CheckLicense(db, license)
	if err != nil {
		switch err.(type) {
		case *database.NotFoundError:
			c.AbortWithError(404, err)
		default:
			c.AbortWithError(500, err)
		}
		return
	}

	if !valid {
		c.AbortWithError(401, err)
		return
	}

	err = google.Update(db, usr)
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	c.String(200, "")
}
Esempio n. 24
0
func apiGetSiteInfo(g *gin.Context) {
	url, ok := g.GetQuery("url")
	if !ok {
		g.String(500, "missing parameter url")
		return
	}
	_, inclBody := g.GetQuery("body")

	cw := crawlbase.NewCrawler()
	cw.Header.Add("User-Agent", userAgentHeader)
	tags, _ := crawlbase.LoadTagsFromFile("tags.json")
	cw.Validator.AddValidTags(tags)

	page, err := cw.GetPage(url, "GET")

	if err != nil {
		g.String(500, err.Error())
	}

	// first check

	if !inclBody {
		page.RespInfo.Body = ""
	}

	g.JSON(200, page)
}
Esempio n. 25
0
func (rc *ResourceController) GetResource(ctx *gin.Context) {
	var id bson.ObjectId
	req := ctx.Request
	resourceType := getResourceType(req.URL)

	// Validate id as a bson Object ID
	id, err := toBsonObjectID(ctx.Param("id"))
	if err != nil {
		ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	logger.Log.WithFields(
		logrus.Fields{"resource type": resourceType, "id": id}).Info("GetResource")

	resource, err := rc.LoadResource(resourceType, id)
	if err != nil {
		if err == mgo.ErrNotFound {
			ctx.String(http.StatusNotFound, "Not Found")
			ctx.Abort()
			return
		} else {
			ctx.AbortWithError(http.StatusBadRequest, err)
			return
		}
	}

	logger.Log.WithFields(logrus.Fields{"resource": resource}).Info("GetResource")

	ctx.JSON(http.StatusOK, resource)
}
Esempio n. 26
0
func view(c *gin.Context) {
	id := c.Param("uniuri")
	key := c.Param("key")
	re := models.ResourceEntry{}
	remote := c.ClientIP()

	db.Where(&models.ResourceEntry{Key: id}).First(&re)
	if re.Key == "" {
		log.Printf("[INFO][%s]\tNot found : %s", remote, id)
		c.AbortWithStatus(http.StatusNotFound)
		return
	}
	log.Printf("[INFO][%s]\tFetched %s file and entry\n", remote, id)
	f, err := os.Open(path.Join(conf.C.UploadDir, re.Key))
	if err != nil {
		log.Printf("[ERROR][%s]\tWhile opening %s file\n", remote, id)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	var iv [aes.BlockSize]byte
	stream := cipher.NewCFBDecrypter(block, iv[:])
	reader := &cipher.StreamReader{S: stream, R: f}
	c.Header("Content-Disposition", "filename=\""+re.Name+"\"")
	io.Copy(c.Writer, reader)
}
Esempio n. 27
0
func ShowIndex(c *gin.Context) {
	user := session.User(c)
	if user == nil {
		c.Redirect(http.StatusSeeOther, "/login")
		return
	}

	// get the repository list from the cache
	repos, err := cache.GetRepos(c, user)
	if err != nil {
		c.String(400, err.Error())
		return
	}

	// filter to only show the currently active ones
	activeRepos, err := store.GetRepoListOf(c, repos)
	if err != nil {
		c.String(400, err.Error())
		return
	}

	c.HTML(200, "index.html", gin.H{
		"User":  user,
		"Repos": activeRepos,
	})
}
Esempio n. 28
0
// Execute command, intercepts stdout and print info
func commandWrapper(c *gin.Context, command string, args []string) {
	old_stdout := os.Stdout // keep backup of the real stdout
	old_stderr := os.Stderr // keep backup of the real stdout
	r, w, _ := os.Pipe()
	os.Stdout = w
	os.Stderr = w

	err := lxclib.RunCommand(config, command, args)
	if err != nil {
		c.String(400, err.Error())
		c.Error(err)
	}

	outC := make(chan string)
	// copy the output in a separate goroutine so printing can't block indefinitely
	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf.String()
	}()

	// back to normal state
	w.Close()
	os.Stdout = old_stdout // restoring the real stdout
	os.Stderr = old_stderr // restoring the real stdout
	out := <-outC

	c.String(200, out)
}
Esempio n. 29
0
// update an object from its change form
func changeUpdate(c *gin.Context) {
	log.Println("hitting changeUpdate")
	action := c.DefaultPostForm("action", "save")
	delete(c.Request.Form, "action") // don't keep this as part of the object
	modelAdmin, exists := modelAdmins[strings.ToLower(c.Param("model"))]
	if !exists {
		c.String(http.StatusNotFound, "Not found.")
		return
	}
	if !hasPermissions(c, modelAdmin.ModelName, "write", nil) { // TODO: add in the ID(s)
		return
	}
	switch action {
	case "save":
		saveFromForm(c)
		c.Request.Method = "GET"
		c.Redirect(http.StatusFound, fmt.Sprintf("../%v", strings.ToLower(c.Param("model"))))
	case "save-continue":
		saveFromForm(c)
		change(c)
	case "delete":
		modelAdmin.Accessor.DeletePK(c.Param("pk"))
		c.Request.Method = "GET"
		c.Redirect(http.StatusFound, fmt.Sprintf("../%v", strings.ToLower(c.Param("model"))))
	}
}
Esempio n. 30
-1
func DeleteSex(c *gin.Context) {
	Mng = c.MustGet("db").(db.Database)
	rnd = c.MustGet("rnd").(*render.Render)
	name := c.Param("name")

	sexes, err := Mng.Collection("sexes")
	if err != nil {
		c.String(http.StatusInternalServerError, "Нет связи с бд")
	}

	res := sexes.Find(db.Cond{"name": name})
	if res != nil {
		var sex models.Sex
		res.One(&sex)
		err = res.Remove()

		if err == nil {
			rnd.Data(c.Writer, 200, []byte(fmt.Sprintf("%v", sex)))
		} else {
			rnd.JSON(c.Writer, 200, gin.H{"err": err.Error()})
		}
	} else {
		rnd.JSON(c.Writer, 404, gin.H{"err": fmt.Sprint("Не удалось найти ", name)})
	}
}