Ejemplo n.º 1
1
func PatchUser(c *gin.Context) {
	me := session.User(c)
	in := &model.User{}
	err := c.Bind(in)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	user, err := store.GetUserLogin(c, c.Param("login"))
	if err != nil {
		c.AbortWithStatus(http.StatusNotFound)
		return
	}
	user.Admin = in.Admin
	user.Active = in.Active

	// cannot update self
	if me.ID == user.ID {
		c.AbortWithStatus(http.StatusForbidden)
		return
	}

	err = store.UpdateUser(c, user)
	if err != nil {
		c.AbortWithStatus(http.StatusConflict)
		return
	}

	c.IndentedJSON(http.StatusOK, user)
}
Ejemplo n.º 2
1
// Handler is a route handler for '/movie.:format' route
func Handler(c *gin.Context) {
	requestType := c.Param("format")
	term := c.Request.PostFormValue("text")

	log.Printf("Movie Query: %s", term)

	movie, err := lookupMovie(term)

	switch requestType {
	case "json":
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"Response": err.Error()})
		} else {
			c.IndentedJSON(http.StatusOK, movie)
		}
	case "slack":
		text, err := formatSlackResp(movie)
		if err != nil {
			c.String(http.StatusNotFound, "Not Found")
		}

		c.String(http.StatusOK, text)
	default:
		c.JSON(http.StatusUnsupportedMediaType, nil)
	}
}
Ejemplo n.º 3
0
func processCommentHook(c *gin.Context, hook *model.Hook) {
	repo, user, err := getRepoAndUser(c, hook.Repo.Slug)
	if err != nil {
		return
	}

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

	approvers, err := buildApprovers(c, user, repo, config, maintainer, hook.Issue)
	if err != nil {
		return
	}

	approved := len(approvers) >= config.Approvals
	err = remote.SetStatus(c, user, repo, hook.Issue.Number, approved)
	if err != nil {
		log.Errorf("Error setting status for %s pr %d. %s", repo.Slug, hook.Issue.Number, err)
		c.String(500, "Error setting status. %s.", err)
		return
	}

	log.Debugf("processed comment for %s. received %d of %d approvals", repo.Slug, len(approvers), config.Approvals)

	c.IndentedJSON(200, gin.H{
		"approvers":   maintainer.People,
		"settings":    config,
		"approved":    approved,
		"approved_by": approvers,
	})
}
Ejemplo n.º 4
0
func GetBuild(c *gin.Context) {
	if c.Param("number") == "latest" {
		GetBuildLast(c)
		return
	}

	repo := session.Repo(c)
	num, err := strconv.Atoi(c.Param("number"))
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	build, err := store.GetBuildNumber(c, repo, num)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	jobs, _ := store.GetJobList(c, build)

	out := struct {
		*model.Build
		Jobs []*model.Job `json:"jobs"`
	}{build, jobs}

	c.IndentedJSON(http.StatusOK, &out)
}
Ejemplo n.º 5
0
func GetRepos(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.AbortWithStatus(http.StatusInternalServerError)
			return
		}
	}

	// for each repository in the remote system we get
	// the intersection of those repostiories in Drone
	repos_, err := store.GetRepoListOf(c, repos)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.Set("repos", repos)
	c.IndentedJSON(http.StatusOK, repos_)
}
Ejemplo n.º 6
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,
	})
}
Ejemplo n.º 7
0
// PostsHandler is a route handler for '/producthunt/posts.:format' route
func PostsHandler(c *gin.Context) {
	requestType := c.Param("format")
	daysAgo, err := strconv.Atoi(c.Request.PostFormValue("text"))
	if err != nil {
		daysAgo = 0
	}

	log.Printf("Days Ago: %d", daysAgo)

	posts, err := getPosts(daysAgo)

	switch requestType {
	case "json":
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"Response": err.Error()})
		} else {
			c.IndentedJSON(http.StatusOK, posts)
		}
	case "slack":
		text, err := formatPostsSlackResp(posts)
		if err != nil {
			c.String(http.StatusNotFound, "Not Found")
		}

		c.String(http.StatusOK, text)
	default:
		c.JSON(http.StatusUnsupportedMediaType, nil)
	}
}
Ejemplo n.º 8
0
func GetLoginToken(c *gin.Context) {
	remote := remote.FromContext(c)

	in := &tokenPayload{}
	err := c.Bind(in)
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	login, err := remote.Auth(in.Access, in.Refresh)
	if err != nil {
		c.AbortWithError(http.StatusUnauthorized, err)
		return
	}

	user, err := store.GetUserLogin(c, login)
	if err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}

	exp := time.Now().Add(time.Hour * 72).Unix()
	token := token.New(token.SessToken, user.Login)
	tokenstr, err := token.SignExpires(user.Hash, exp)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.IndentedJSON(http.StatusOK, &tokenPayload{
		Access:  tokenstr,
		Expires: exp - time.Now().Unix(),
	})
}
Ejemplo n.º 9
0
// return data from a sensor in json format
// This function call reduceData!
func (s *Sensorserver) GetSensorData(c *gin.Context) {
	// maximum Timestamp is MaxInt32
	// fetchLastData return all records, if duration is
	// also MaxInt32
	//  -> MaxInt32 - MaxInt32 = 0 -> get all data since 01.0.1.1970
	const duration int = math.MaxInt32

	pretty := c.Request.URL.Query().Get("pretty")

	sensor := c.Param("name")
	data, err := s.fetchLastData(sensor, duration)

	if err != nil {
		if pretty == "true" {
			c.IndentedJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		}
	} else {
		if pretty == "true" {
			c.IndentedJSON(http.StatusOK, s.reduceData(data))
		} else {
			c.JSON(http.StatusOK, s.reduceData(data))
		}
	}

}
Ejemplo n.º 10
0
func DeleteRequest(c *gin.Context) {
	message := "success"
	// if err := RequestCollection.Remove(bson.M{"_id": bson.ObjectIdHex(c.Param("id"))}); err != nil {
	if err := RequestCollection.RemoveId(bson.ObjectIdHex(c.Param("id"))); err != nil {
		message = PrepareMessage(err)
	}
	c.IndentedJSON(200, gin.H{"message": message})
}
Ejemplo n.º 11
0
func GetUsers(c *gin.Context) {
	users, err := store.GetUserList(c)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.IndentedJSON(http.StatusOK, users)
}
Ejemplo n.º 12
0
func GetUser(c *gin.Context) {
	user, err := store.GetUserLogin(c, c.Param("login"))
	if err != nil {
		c.AbortWithStatus(http.StatusNotFound)
		return
	}

	c.IndentedJSON(http.StatusOK, user)
}
Ejemplo n.º 13
0
Archivo: build.go Proyecto: elia/drone
func GetBuilds(c *gin.Context) {
	repo := session.Repo(c)
	builds, err := store.GetBuildList(c, repo)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	c.IndentedJSON(http.StatusOK, builds)
}
Ejemplo n.º 14
0
func GetRequest(c *gin.Context) {
	request := &Request{}
	httpCode := 200
	message := ""
	if err := RequestCollection.FindId(bson.ObjectIdHex(c.Param("id"))).One(request); err != nil {
		request = nil
		httpCode = 404
		message = PrepareMessage(err)
	}
	c.IndentedJSON(httpCode, gin.H{"data": request, "message": message})
}
Ejemplo n.º 15
0
func GetRemoteRepos(c *gin.Context) {
	user := session.User(c)

	repos, err := cache.GetRepos(c, user)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.IndentedJSON(http.StatusOK, repos)
}
Ejemplo n.º 16
0
func (s *Sensorserver) Stats(c *gin.Context) {
	prev := s.boltdb.Stats()

	pretty := c.Request.URL.Query().Get("pretty")

	if pretty == "true" {
		c.IndentedJSON(http.StatusOK, prev)
	} else {
		c.JSON(http.StatusOK, prev)
	}
}
Ejemplo n.º 17
0
func CreateRequest(c *gin.Context) {
	request := &Request{}
	message := "success"
	httpCode := 200
	c.Bind(request)
	if err := request.Create(); err != nil {
		message = PrepareMessage(err)
		request = nil
		httpCode = 500
	}
	c.IndentedJSON(httpCode, gin.H{"message": message, "data": request})
}
Ejemplo n.º 18
0
func JSONResponse(ctx *gin.Context, statusCode int, obj ...interface{}) {
	if len(obj) == 1 {
		if gin.Mode() == "debug" {
			ctx.IndentedJSON(statusCode, obj[0])
		} else {
			ctx.JSON(statusCode, obj[0])
		}
	} else {
		if gin.Mode() == "debug" {
			ctx.IndentedJSON(statusCode, obj)
		} else {
			ctx.JSON(statusCode, obj)
		}
	}
}
Ejemplo n.º 19
0
// CreateToken procedure generates both tokens, sends them to ms-auth, and returns them to client
func CreateToken(c *gin.Context, host *url.URL, cid string) (err error) {
	//create token
	if aToken, rToken, err := KeyInstance().GenerateAccessToken(cid, true); err == nil {
		//post refresh to ms-auth
		PostRefresh(host, cid, rToken)

		//return both to Client
		data := map[string]string{
			"access_token":  aToken,
			"refresh_token": rToken,
		}
		c.IndentedJSON(200, data)
		return nil
	}
	return err //TODO: Figure out what error would mean for client logging in and handle in functions calling this one
}
Ejemplo n.º 20
0
func GetBuildLast(c *gin.Context) {
	repo := session.Repo(c)
	branch := c.DefaultQuery("branch", repo.Branch)

	build, err := store.GetBuildLast(c, repo, branch)
	if err != nil {
		c.String(http.StatusInternalServerError, err.Error())
		return
	}
	jobs, _ := store.GetJobList(c, build)

	out := struct {
		*model.Build
		Jobs []*model.Job `json:"jobs"`
	}{build, jobs}

	c.IndentedJSON(http.StatusOK, &out)
}
Ejemplo n.º 21
0
func PatchRepo(c *gin.Context) {
	repo := session.Repo(c)
	user := session.User(c)

	in := &struct {
		IsTrusted   *bool  `json:"trusted,omitempty"`
		Timeout     *int64 `json:"timeout,omitempty"`
		AllowPull   *bool  `json:"allow_pr,omitempty"`
		AllowPush   *bool  `json:"allow_push,omitempty"`
		AllowDeploy *bool  `json:"allow_deploy,omitempty"`
		AllowTag    *bool  `json:"allow_tag,omitempty"`
	}{}
	if err := c.Bind(in); err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	if in.AllowPush != nil {
		repo.AllowPush = *in.AllowPush
	}
	if in.AllowPull != nil {
		repo.AllowPull = *in.AllowPull
	}
	if in.AllowDeploy != nil {
		repo.AllowDeploy = *in.AllowDeploy
	}
	if in.AllowTag != nil {
		repo.AllowTag = *in.AllowTag
	}
	if in.IsTrusted != nil && user.Admin {
		repo.IsTrusted = *in.IsTrusted
	}
	if in.Timeout != nil && user.Admin {
		repo.Timeout = *in.Timeout
	}

	err := store.UpdateRepo(c, repo)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.IndentedJSON(http.StatusOK, repo)
}
Ejemplo n.º 22
0
func GetRepos(c *gin.Context) {
	user := session.User(c)

	repos, err := cache.GetRepos(c, user)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	// for each repository in the remote system we get
	// the intersection of those repostiories in Drone
	repos_, err := store.GetRepoListOf(c, repos)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.IndentedJSON(http.StatusOK, repos_)
}
Ejemplo n.º 23
0
func GetRemoteRepos(c *gin.Context) {
	user := session.User(c)
	remote := remote.FromContext(c)

	reposv, ok := c.Get("repos")
	if ok {
		c.IndentedJSON(http.StatusOK, reposv)
		return
	}

	repos, err := remote.Repos(user)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.Set("repos", repos)
	c.IndentedJSON(http.StatusOK, repos)
}
Ejemplo n.º 24
0
func GetUser(c *gin.Context) {
	user, err := store.GetUserLogin(c, c.Param("login"))
	if err != nil {
		c.AbortWithStatus(http.StatusNotFound)
		return
	}

	token := token.New(token.UserToken, user.Login)
	tokenstr, err := token.Sign(user.Hash)
	if err != nil {
		tokenstr = ""
	}
	userWithToken := struct {
		*model.User
		Token string `json:"token,omitempty"`
	}{user, tokenstr}

	c.IndentedJSON(http.StatusOK, userWithToken)
}
Ejemplo n.º 25
0
// Handler is a route handler for '/excuse.:format' route
func Handler(c *gin.Context) {
	requestType := c.Param("format")
	excuse, err := getAnExcuse()

	switch requestType {
	case "json":
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"Response": err.Error()})
		} else {
			c.IndentedJSON(http.StatusOK, excuse)
		}
	case "slack":
		if err != nil {
			c.String(http.StatusNotFound, "> I am not feeling well\n")
		}

		c.String(http.StatusOK, "\n> "+excuse.Text+"\n")
	default:
		c.String(http.StatusUnsupportedMediaType, "")
	}
}
Ejemplo n.º 26
0
func EditRequest(c *gin.Context) {
	message := "success"
	request := &Request{}
	httpCode := 200
	err := RequestCollection.FindId(bson.ObjectIdHex(c.Param("id"))).One(request)
	if err != nil {
		message = PrepareMessage(err)
		httpCode = 404
	} else {
		c.Bind(request)
		if err = request.Check(); err != nil {
			message = PrepareMessage(err)
			httpCode = 400
		} else if err = RequestCollection.UpdateId(bson.ObjectIdHex(c.Param("id")), bson.M{"$set": request}); err != nil {
			request = nil
			message = PrepareMessage(err)
			httpCode = 500
		}
	}
	c.IndentedJSON(httpCode, gin.H{"message": message, "data": request})
}
Ejemplo n.º 27
0
func PostUser(c *gin.Context) {
	in := &struct {
		model.User
		Token string `json:"oauth_token"`
	}{}
	err := c.Bind(in)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	user := &model.User{}
	user.Login = in.Login
	user.Email = in.Email
	user.Admin = in.Admin
	user.Token = in.Token
	user.Avatar = in.Avatar
	user.Active = true
	user.Hash = crypto.Rand()

	err = store.CreateUser(c, user)
	if err != nil {
		c.String(http.StatusInternalServerError, err.Error())
		return
	}

	token := token.New(token.UserToken, user.Login)
	tokenstr, err := token.Sign(user.Hash)
	if err != nil {
		tokenstr = ""
	}
	userWithToken := struct {
		*model.User
		Token string `json:"token,omitempty"`
	}{user, tokenstr}

	c.IndentedJSON(http.StatusOK, userWithToken)
}
Ejemplo n.º 28
0
func PostNode(c *gin.Context) {
	engine := context.Engine(c)

	in := struct {
		Addr string `json:"address"`
		Arch string `json:"architecture"`
		Cert string `json:"cert"`
		Key  string `json:"key"`
		CA   string `json:"ca"`
	}{}
	err := c.Bind(&in)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	node := &model.Node{}
	node.Addr = in.Addr
	node.Cert = in.Cert
	node.Key = in.Key
	node.CA = in.CA
	node.Arch = "linux_amd64"

	err = engine.Allocate(node)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	err = store.CreateNode(c, node)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.IndentedJSON(http.StatusOK, node)
}
Ejemplo n.º 29
0
func PostUser(c *gin.Context) {
	in := &model.User{}
	err := c.Bind(in)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	user := &model.User{}
	user.Login = in.Login
	user.Email = in.Email
	user.Admin = in.Admin
	user.Avatar = in.Avatar
	user.Active = true
	user.Hash = crypto.Rand()

	err = store.CreateUser(c, user)
	if err != nil {
		c.String(http.StatusInternalServerError, err.Error())
		return
	}

	c.IndentedJSON(http.StatusOK, user)
}
Ejemplo n.º 30
0
Archivo: login.go Proyecto: lgtmco/lgtm
// LoginToken authenticates a user with their GitHub token and
// returns an LGTM API token in the response.
func LoginToken(c *gin.Context) {
	access := c.Query("access_token")
	login, err := remote.GetUserToken(c, access)
	if err != nil {
		c.String(403, "Unable to authenticate user. %s", err)
		return
	}
	user, err := store.GetUserLogin(c, login)
	if err != nil {
		c.String(404, "Unable to authenticate user %s. Not registered.", user.Login)
		return
	}
	exp := time.Now().Add(time.Hour * 72).Unix()
	token := token.New(token.UserToken, user.Login)
	tokenstr, err := token.SignExpires(user.Secret, exp)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	c.IndentedJSON(http.StatusOK, &tokenPayload{
		Access:  tokenstr,
		Expires: exp - time.Now().Unix(),
	})
}