func AddRepository(c *gin.Context) { project := c.MustGet("project").(models.Project) var repository struct { Name string `json:"name" binding:"required"` GitUrl string `json:"git_url" binding:"required"` SshKeyID int `json:"ssh_key_id" binding:"required"` } if err := c.Bind(&repository); err != nil { return } res, err := database.Mysql.Exec("insert into project__repository set project_id=?, git_url=?, ssh_key_id=?, name=?", project.ID, repository.GitUrl, repository.SshKeyID, repository.Name) if err != nil { panic(err) } insertID, _ := res.LastInsertId() insertIDInt := int(insertID) objType := "repository" desc := "Repository (" + repository.GitUrl + ") created" if err := (models.Event{ ProjectID: &project.ID, ObjectType: &objType, ObjectID: &insertIDInt, Description: &desc, }.Insert()); err != nil { panic(err) } c.AbortWithStatus(204) }
func EnvironmentMiddleware(c *gin.Context) { project := c.MustGet("project").(models.Project) envID, err := util.GetIntParam("environment_id", c) if err != nil { return } query, args, _ := squirrel.Select("*"). From("project__environment"). Where("project_id=?", project.ID). Where("id=?", envID). ToSql() var env models.Environment if err := database.Mysql.SelectOne(&env, query, args...); err != nil { if err == sql.ErrNoRows { c.AbortWithStatus(404) return } panic(err) } c.Set("environment", env) c.Next() }
func EditReviewFormR(c *gin.Context) { // dependency injection var ( reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore) user = GetUser(c) ) // only authenticated users can perform this action if !user.Authenticated() { c.AbortWithStatus(http.StatusUnauthorized) return } // fetch review id, err := strconv.Atoi(c.Param("id")) if err != nil { c.AbortWithError(http.StatusBadRequest, err) return } review, err := reviewStore.GetReview(id) if err != nil { c.AbortWithError(http.StatusInternalServerError, err) return } c.HTML(http.StatusOK, "review-form.html", gin.H{ "Action": "Edit", "User": user, "Form": review, "Errors": map[string]string{}, }) }
// openVPNHandler generate the openvpn config func (r *openvpnAuthd) openVPNHandler(cx *gin.Context) { // step: grab the authentication headers emailAddress := cx.Request.Header.Get(r.config.AuthHeader) if emailAddress == "" { cx.AbortWithStatus(http.StatusForbidden) return } // step: generate a certificate for them cert, err := r.vault.GetCertificate(emailAddress, r.config.VaultPath, r.config.SessionDuration) if err != nil { glog.Errorf("failed to generate the certificate for openvpn account, reason: %s", err) cx.AbortWithStatus(http.StatusInternalServerError) return } // step: template out the config cx.HTML(http.StatusOK, "openvpn.html", gin.H{ "openvpn_servers": r.config.servers, "ttl": cert.TTL, "expires_in": time.Now().Add(cert.TTL), "certificate": cert.Certificate, "private_key": cert.PrivateKey, "issuing_ca": cert.IssuingCA, "email": emailAddress, }) }
func InventoryMiddleware(c *gin.Context) { project := c.MustGet("project").(models.Project) inventoryID, err := util.GetIntParam("inventory_id", c) if err != nil { return } query, args, _ := squirrel.Select("*"). From("project__inventory"). Where("project_id=?", project.ID). Where("id=?", inventoryID). ToSql() var inventory models.Inventory if err := database.Mysql.SelectOne(&inventory, query, args...); err != nil { if err == sql.ErrNoRows { c.AbortWithStatus(404) return } panic(err) } c.Set("inventory", inventory) c.Next() }
func AddUser(c *gin.Context) { project := c.MustGet("project").(models.Project) var user struct { UserID int `json:"user_id" binding:"required"` Admin bool `json:"admin"` } if err := c.Bind(&user); err != nil { return } if _, err := database.Mysql.Exec("insert into project__user set user_id=?, project_id=?, admin=?", user.UserID, project.ID, user.Admin); err != nil { panic(err) } objType := "user" desc := "User ID " + strconv.Itoa(user.UserID) + " added to team" if err := (models.Event{ ProjectID: &project.ID, ObjectType: &objType, ObjectID: &user.UserID, Description: &desc, }.Insert()); err != nil { panic(err) } c.AbortWithStatus(204) }
func ProjectMiddleware(c *gin.Context) { user := c.MustGet("user").(*models.User) projectID, err := util.GetIntParam("project_id", c) if err != nil { return } query, args, _ := squirrel.Select("p.*"). From("project as p"). Join("project__user as pu on pu.project_id=p.id"). Where("p.id=?", projectID). Where("pu.user_id=?", user.ID). ToSql() var project models.Project if err := database.Mysql.SelectOne(&project, query, args...); err != nil { if err == sql.ErrNoRows { c.AbortWithStatus(404) return } panic(err) } c.Set("project", project) c.Next() }
// CreateC handles the multipart form upload and creates an encrypted file func CreateC(c *gin.Context) { var err error var duration time.Duration var once bool c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, conf.C.SizeLimit*utils.MegaByte) once = c.PostForm("once") != "" d := c.DefaultPostForm("duration", "1d") if val, ok := models.DurationMap[d]; ok { duration = val } else { logger.ErrC(c, "server", "Invalid duration", d) c.String(http.StatusBadRequest, "Invalid duration\n") c.AbortWithStatus(http.StatusBadRequest) return } fd, h, err := c.Request.FormFile("file") if err != nil { logger.ErrC(c, "server", "Couldn't read file", err) c.String(http.StatusRequestEntityTooLarge, "Entity is too large (Max : %v MB)\n", conf.C.SizeLimit) c.AbortWithStatus(http.StatusRequestEntityTooLarge) return } defer fd.Close() res := models.NewResourceFromForm(h, once, duration) k, err := res.WriteEncrypted(fd) if err != nil { logger.ErrC(c, "server", "Couldn't write file", err) c.String(http.StatusInternalServerError, "Something went wrong on the server. Try again later.") c.AbortWithStatus(http.StatusInternalServerError) return } if conf.C.DiskQuota > 0 { if models.S.CurrentSize+uint64(res.Size) > uint64(conf.C.DiskQuota*utils.GigaByte) { logger.ErrC(c, "server", "Quota exceeded") c.String(http.StatusBadRequest, "Insufficient disk space. Try again later.") c.AbortWithStatus(http.StatusBadRequest) os.Remove(path.Join(conf.C.UploadDir, res.Key)) return } } if err = res.Save(); err != nil { logger.ErrC(c, "server", "Couldn't save in the database", err) c.String(http.StatusInternalServerError, "Something went wrong on the server. Try again later.") c.AbortWithStatus(http.StatusInternalServerError) return } res.LogCreated(c) ns := conf.C.NameServer if conf.C.AppendPort { ns = fmt.Sprintf("%s:%d", conf.C.NameServer, conf.C.Port) } c.String(http.StatusCreated, "%v://%s/v/%s/%s\n", utils.DetectScheme(c), ns, res.Key, k) }
func (C *AuthController) Login(c *gin.Context) { var form forms.AuthForm err := c.Bind(&form) if err != nil { C.logger.Error(err) c.AbortWithStatus(http.StatusBadRequest) } err = form.IsValid() if err != nil { C.logger.Error(err) c.JSON(http.StatusBadRequest, err) return } token, err := C.service.Authenticate(&form) if err != nil { C.logger.Error(err) c.AbortWithStatus(http.StatusUnauthorized) return } c.JSON(http.StatusOK, struct { Token string `json:"token"` }{token}) }
func (ctl *AlertController) postAddAlertsPolicyAction(c *gin.Context) { var form models.AlertPolicyForm if err := c.Bind(&form); err != nil { c.AbortWithStatus(http.StatusBadRequest) return } if err := form.Validate(); err != nil { c.HTML(http.StatusOK, "alert_policy_add.html", map[string]interface{}{ "NagiosPlugins": models.NagiosPlugins, "errors": err.Errors, "form": form, }) return } ap := models.AlertPolicyMapper.Create(&form) if err := models.AlertPolicyMapper.Save(ap); err != nil { panic(err) } c.Redirect(http.StatusFound, "/alerts-policies") }
func (ctl *AlertController) postEditAlertsGroupAction(c *gin.Context) { var form models.AlertGroupUpdateForm if err := c.Bind(&form); err != nil { c.AbortWithStatus(http.StatusBadRequest) return } ag, err := models.AlertGroupMapper.FetchOne(c.Param("id")) if err != nil { panic(err) } if ag == nil { c.Redirect(http.StatusFound, "/alerts-groups") return } if err := form.Validate(ag); err != nil { c.HTML(http.StatusOK, "alert_group_edit.html", map[string]interface{}{ "errors": err.Errors, "form": form, "ag": ag, }) return } ag.Update(&form) if err := models.AlertGroupMapper.Update(ag); err != nil { panic(err) } c.Redirect(http.StatusFound, "/alerts-groups") }
func CallRpcServiceWithContext(c *gin.Context, env Env, name, method string, req interface{}, res rpcResponse) bool { // Get the service TCP client client, err := getEnvTcpClient(name, env) if goutils.HasErrorAndPrintStack(err) { c.AbortWithError(http.StatusInternalServerError, err) return true } err = client.Call(method, req, res) if err != nil { // Check if it is not found error if err.Error() == "not found" { c.AbortWithStatus(http.StatusNotFound) } else { goutils.PrintStackAndError(err) c.AbortWithError(http.StatusInternalServerError, err) } return true } if res.HasError() { c.JSON(http.StatusBadRequest, res.ReturnErrorMap()) return true } return false }
func PostUploadDone(c *gin.Context) { sessionID := c.Param("sessionid") repo := session.Repo(c) state := checker.FromContext(c) if pkgs, ok := sessions[sessionID]; ok { delete(sessions, sessionID) err := repo.Add(pkgs) if err != nil { log.Errorf("failed to add packages '%s' to repository '%s': %s", strings.Join(pkgs, ", "), repo.Name, err) c.AbortWithStatus(http.StatusInternalServerError) return } // clear packages from checker state // TODO: check pkg name (maybe it's the full path here?) for _, pkg := range pkgs { state.ClearPkg(pkg, repo.Owner, repo.Name) } c.Writer.WriteHeader(http.StatusOK) return } c.AbortWithStatus(http.StatusNotFound) }
func UpdateRepository(c *gin.Context) { oldRepo := c.MustGet("repository").(models.Repository) var repository struct { Name string `json:"name" binding:"required"` GitUrl string `json:"git_url" binding:"required"` SshKeyID int `json:"ssh_key_id" binding:"required"` } if err := c.Bind(&repository); err != nil { return } if _, err := database.Mysql.Exec("update project__repository set name=?, git_url=?, ssh_key_id=? where id=?", repository.Name, repository.GitUrl, repository.SshKeyID, oldRepo.ID); err != nil { panic(err) } if oldRepo.GitUrl != repository.GitUrl { clearRepositoryCache(oldRepo) } desc := "Repository (" + repository.GitUrl + ") updated" objType := "inventory" if err := (models.Event{ ProjectID: &oldRepo.ProjectID, Description: &desc, ObjectID: &oldRepo.ID, ObjectType: &objType, }.Insert()); err != nil { panic(err) } c.AbortWithStatus(204) }
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_) }
func (C *AuthController) Reset(c *gin.Context) { var ( form forms.ResetForm err error ) err = c.Bind(&form) if err != nil { C.logger.Error(err) c.AbortWithStatus(http.StatusBadRequest) return } err = form.IsValid() if err != nil { C.logger.Error(err) c.JSON(http.StatusBadRequest, err) return } err = C.service.Reset(&form) if err != nil { C.logger.Error(err) } c.JSON(http.StatusOK, []byte(nil)) }
func SetUser(c *gin.Context) { var user *model.User // authenticates the user via an authentication cookie // or an auth token. t, err := token.ParseRequest(c.Request, func(t *token.Token) (string, error) { var err error user, err = store.GetUserLogin(c, t.Text) return user.Secret, err }) if err == nil { c.Set("user", user) // if this is a session token (ie not the API token) // this means the user is accessing with a web browser, // so we should implement CSRF protection measures. if t.Kind == token.SessToken { err = token.CheckCsrf(c.Request, func(t *token.Token) (string, error) { return user.Secret, nil }) // if csrf token validation fails, exit immediately // with a not authorized error. if err != nil { c.AbortWithStatus(http.StatusUnauthorized) return } } } c.Next() }
func (C *DriverController) UpdateStatus(c *gin.Context) { var form forms.DriverStatusForm err := c.Bind(&form) if err != nil { C.logger.Error(err) c.AbortWithStatus(http.StatusBadRequest) return } err = form.IsValid() if err != nil { C.logger.Error(err) c.JSON(http.StatusBadRequest, err) return } driver := c.MustGet(DRIVER_ATTRIBUTE).(*models.Driver) if err := C.service.UpdateStatus(driver.ID, form); err != nil { c.AbortWithStatus(http.StatusInternalServerError) return } c.JSON(http.StatusOK, []byte(nil)) }
// View handles the file views func View(c *gin.Context) { var err error id := c.Param("uniuri") re := models.Resource{} if err = re.Get(id); err != nil || re.Key == "" { logger.InfoC(c, "server", "Not found", id) c.AbortWithStatus(http.StatusNotFound) return } re.LogFetched(c) f, err := os.Open(path.Join(conf.C.UploadDir, re.Key)) if err != nil { logger.ErrC(c, "server", fmt.Sprintf("Couldn't open %s", re.Key), err) c.AbortWithStatus(http.StatusInternalServerError) return } if conf.C.AlwaysDownload { c.Header("Content-Type", "application/octet-stream") } c.Header("Content-Disposition", "filename=\""+re.Name+"\"") io.Copy(c.Writer, f) if re.Once { re.Delete() re.LogDeleted(c) } }
func (C *DriverController) Create(c *gin.Context) { var form forms.DriverForm err := c.Bind(&form) if err != nil { C.logger.Error(err) c.AbortWithStatus(http.StatusBadRequest) return } err = form.IsValid() if err != nil { C.logger.Error(err) c.JSON(http.StatusBadRequest, err) return } if err := C.service.New(form); err != nil { if mgo.IsDup(err) { c.JSON(http.StatusConflict, []byte(nil)) } else { c.AbortWithStatus(http.StatusInternalServerError) } return } c.JSON(http.StatusOK, []byte(nil)) }
func DeleteProject(c *gin.Context) { project := c.MustGet("project").(models.Project) tx, err := database.Mysql.Begin() if err != nil { panic(err) } statements := []string{ "delete tao from task__output as tao join task as t on t.id=tao.task_id join project__template as pt on pt.id=t.template_id where pt.project_id=?", "delete t from task as t join project__template as pt on pt.id=t.template_id where pt.project_id=?", "delete from project__template where project_id=?", "delete from project__user where project_id=?", "delete from project__repository where project_id=?", "delete from project__inventory where project_id=?", "delete from access_key where project_id=?", "delete from project where id=?", } for _, statement := range statements { _, err := tx.Exec(statement, project.ID) if err != nil { tx.Rollback() panic(err) } } if err := tx.Commit(); err != nil { panic(err) } c.AbortWithStatus(204) }
func GetCommit(c *gin.Context) { repo := session.Repo(c) parsed, err := token.ParseRequest(c.Request, func(t *token.Token) (string, error) { return repo.Hash, nil }) if err != nil { c.AbortWithError(http.StatusBadRequest, err) return } if parsed.Text != repo.FullName { c.AbortWithStatus(http.StatusUnauthorized) return } commit := c.Param("sha") branch := c.Query("branch") if len(branch) == 0 { branch = repo.Branch } build, err := store.GetBuildCommit(c, repo, commit, branch) if err != nil { c.AbortWithError(http.StatusNotFound, err) return } c.JSON(http.StatusOK, build) }
func MustPush(c *gin.Context) { user := User(c) perm := Perm(c) // if the user has push access, immediately proceed // the middleware execution chain. if perm.Push { c.Next() return } // debugging if user != nil { c.AbortWithStatus(http.StatusNotFound) log.Debugf("User %s denied write access to %s", user.Login, c.Request.URL.Path) } else { c.AbortWithStatus(http.StatusUnauthorized) log.Debugf("Guest denied write access to %s %s", c.Request.Method, c.Request.URL.Path, ) } }
// handlePods handles the changes made to pods func (r *KubeCover) handlePods(cx *gin.Context) { context, err := r.deriveContext(cx) if err != nil { glog.Errorf("unable to retrieve the request content") cx.AbortWithStatus(http.StatusBadRequest) return } // step: decode the pod spec pod := new(api.PodTemplateSpec) content, err := r.decodeInput(cx.Request, pod) if err != nil { glog.Errorf("unable to decode the request body, error: %s", err) cx.AbortWithStatus(http.StatusBadRequest) return } glog.V(10).Infof("authorizating pod, namespace: %s, name: %s", context.Namespace, pod.Name) // step: validate against the policy if err := r.acl.Authorized(context, &pod.Spec); err != nil { r.unauthorizedRequest(cx, content, err.Error()) return } }
func UpdateTemplate(c *gin.Context) { oldTemplate := c.MustGet("template").(models.Template) var template models.Template if err := c.Bind(&template); err != nil { return } if _, err := database.Mysql.Exec("update project__template set ssh_key_id=?, inventory_id=?, repository_id=?, environment_id=?, playbook=?, arguments=?, override_args=? where id=?", template.SshKeyID, template.InventoryID, template.RepositoryID, template.EnvironmentID, template.Playbook, template.Arguments, template.OverrideArguments, oldTemplate.ID); err != nil { panic(err) } desc := "Template ID " + strconv.Itoa(template.ID) + " updated" objType := "template" if err := (models.Event{ ProjectID: &oldTemplate.ProjectID, Description: &desc, ObjectID: &oldTemplate.ID, ObjectType: &objType, }.Insert()); err != nil { panic(err) } c.AbortWithStatus(204) }
func ApiV1GetPlaylist(c *gin.Context) { // get a playlist requestId := c.Param("plid") plid := "" // check if the plid is a contributor ID, substitute in the contributor handle for the ID res, _ := redisClient.HGet("contributor_to_playlist", requestId).Result() if res != "" { log.Printf("Contributor key %s maps to master playlist %s", requestId, res) plid = res } else { // no contributor key known, so this must be the master key plid = requestId } if !redisClient.Exists("playlist:" + plid).Val() { c.AbortWithStatus(http.StatusNotFound) return } m, err := redisClient.HGetAllMap("playlist:" + plid).Result() if err != nil { ApiError(c, 500, GetPlaylistError, fmt.Errorf("Unable to fetch playlist %s: %s", plid, err)) return } p := models.LoadPlaylistFromMap(m) log.Printf("Loaded playlist %+v", p) // replace master key with contributor key if necessary if p.ContributorKey == requestId { p.Id = requestId } c.JSON(http.StatusOK, p) }
func AddEnvironment(c *gin.Context) { project := c.MustGet("project").(models.Project) var env models.Environment if err := c.Bind(&env); err != nil { return } res, err := database.Mysql.Exec("insert into project__environment set project_id=?, name=?, json=?, password=?", project.ID, env.Name, env.JSON, env.Password) if err != nil { panic(err) } insertID, _ := res.LastInsertId() insertIDInt := int(insertID) objType := "environment" desc := "Environment " + env.Name + " created" if err := (models.Event{ ProjectID: &project.ID, ObjectType: &objType, ObjectID: &insertIDInt, Description: &desc, }.Insert()); err != nil { panic(err) } c.AbortWithStatus(204) }
// GetMaintainer gets the MAINTAINER configuration file and returns // a subset of the file with members belonging to the specified organization. func GetMaintainerOrg(c *gin.Context) { var ( owner = c.Param("owner") name = c.Param("repo") team = c.Param("org") user = session.User(c) ) repo, err := store.GetRepoOwnerName(c, owner, name) if err != nil { log.Errorf("Error getting repository %s. %s", name, err) c.AbortWithStatus(404) return } file, err := remote.GetContents(c, user, repo, "MAINTAINERS") if err != nil { log.Errorf("Error getting repository %s. %s", repo.Slug, err) c.String(404, "MAINTAINERS file not found. %s", err) return } maintainer, err := model.ParseMaintainer(file) if err != nil { log.Errorf("Error parsing MAINTAINERS file for %s. %s", repo.Slug, err) c.String(500, "Error parsing MAINTAINERS file. %s.", err) return } subset, err := model.FromOrg(maintainer, team) if err != nil { log.Errorf("Error getting subset of MAINTAINERS file for %s/%s. %s", repo.Slug, team, err) c.String(500, "Error getting subset of MAINTAINERS file. %s.", err) return } c.JSON(200, subset) }
func (pc *NodeController) postNodeAction(c *gin.Context) { id := c.Param("id") var form models.NodeUpdateForm if err := c.Bind(&form); err != nil { c.AbortWithStatus(http.StatusBadRequest) return } node, err := models.NodeMapper.FetchOneById(id) if err != nil { c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{ "error": err, }) return } if node == nil { c.HTML(http.StatusNotFound, "error_404.html", map[string]interface{}{ "text": "Node not found", }) return } node.Tags = form.Tags node.Description = form.Description models.NodeMapper.Update(node) c.Redirect(http.StatusFound, "/nodes") }
func PatientEmrAttachments(r *gin.Context) { id := r.Param("id") if id == "" { r.AbortWithStatus(http.StatusBadRequest) return } var query string var err error var o []patientEmrAttachmentsResult module := r.Param("module") if module == "" { query = "SELECT p.patient AS patient, p.module AS module, p.oid AS oid, p.annotation AS annotation, p.summary AS summary, p.stamp AS stamp, DATE_FORMAT(p.stamp, '%m/%d/%Y') AS date_mdy, m.module_name AS type, m.module_class AS module_namespace, p.locked AS locked, p.id AS id FROM patient_emr p LEFT OUTER JOIN modules m ON m.module_table = p.module WHERE p.patient = ? AND m.module_hidden = 0" _, err = model.DbMap.Select(&o, query, id) } else { query = "SELECT p.patient AS patient, p.module AS module, p.oid AS oid, p.annotation AS annotation, p.summary AS summary, p.stamp AS stamp, DATE_FORMAT(p.stamp, '%m/%d/%Y') AS date_mdy, m.module_name AS type, m.module_class AS module_namespace, p.locked AS locked, p.id AS id FROM patient_emr p LEFT OUTER JOIN modules m ON m.module_table = p.module WHERE p.patient = ? AND p.module = ? AND m.module_hidden = 0" _, err = model.DbMap.Select(&o, query, id, module) } if err != nil { log.Print(err.Error()) r.AbortWithError(http.StatusInternalServerError, err) return } r.JSON(http.StatusOK, o) return }