Example #1
0
func (t *TypesController) GetTypeDataHandler(c *gin.Context) {
	appId := c.Param("appId")
	typeName := c.Param("typeName")

	app := c.MustGet("app").(JSON)
	types := app["types"].([]interface{})
	found := false

	for _, t := range types {
		if value, ok := t.(string); ok && value == typeName {
			found = true
			break
		}
	}

	if !found {
		RestErrorNotFound(c)
		return
	}

	d := db.NewTypeDbService(appId, typeName)

	typeData, err := d.Find(nil, nil)

	if err != nil {
		RestError(c, err)
		return
	}

	c.JSON(http.StatusOK, typeData)
}
Example #2
0
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{},
	})
}
Example #3
0
func DeleteUserInstance(c *gin.Context) {
	db := c.MustGet("db").(gorm.DB)
	consumer := c.MustGet("consumer").(models.User)

	id := c.Params.ByName("id")

	var user models.User

	db.First(&user, id)

	if user.Username == "" {
		response := make(map[string]string)
		response["error"] = "Resource not found."
		c.JSON(404, response)
	} else {
		if (consumer.Admin) || (user.Id == consumer.Id) {
			db.Delete(&user)
			if user.Id != consumer.Id {
				if user.Gravatar == "" {
					user.Gravatar = user.Email
				}
				user.Email = ""
			}
			user.Password = ""
			c.JSON(200, user)
		} else {
			response := make(map[string]string)
			response["error"] = "Invalid credentials."
			c.JSON(401, response)
		}
	}
}
Example #4
0
func WhiskyListR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		user        = GetUser(c)
	)

	// get whiskies
	list, err := whiskyStore.GetAllWhiskies()
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// transform list into alphabet map
	whiskies := map[string][]Whisky{}
	for _, whisky := range list {
		group := strings.ToUpper(whisky.Distillery[0:1])
		whiskies[group] = append(whiskies[group], whisky)
	}

	c.HTML(http.StatusOK, "list.html", gin.H{
		"User":     user,
		"Whiskies": whiskies,
	})
}
Example #5
0
func UserListR(c *gin.Context) {
	// dependency injection
	var (
		userStore = c.MustGet(UserStoreKey).(UserStore)
		user      = GetUser(c)
	)

	// get users
	list, err := userStore.GetAllUser()
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// transform list into alphabet map
	users := map[string][]User{}
	for _, user := range list {
		group := strings.ToUpper(user.Name[0:1])
		users[group] = append(users[group], user)
	}

	c.HTML(http.StatusOK, "users.html", gin.H{
		"User":  user,
		"Users": users,
	})
}
Example #6
0
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)
}
Example #7
0
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()
}
Example #8
0
func (p *Engine) showNote(c *gin.Context) (interface{}, error) {
	u := c.MustGet("user").(*platform.User)
	id := c.Param("id")
	var note Note
	err := p.Db.Where("id = ? AND user_id = ?", id, u.ID).First(&note).Error
	return note, err
}
Example #9
0
func (p *Engine) deleteNote(c *gin.Context) (interface{}, error) {

	u := c.MustGet("user").(*platform.User)
	id := c.Param("id")
	err := p.Db.Where("id = ? AND user_id = ?", id, u.ID).Delete(Note{}).Error
	return web.OK, err
}
Example #10
0
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)
}
Example #11
0
// Status handler for the /status route
func OpenWebsocket(c *gin.Context) {
	userId := c.MustGet("request_user_id").(string)
	noteId := c.Param("note_id")
	in, note, err := db.GetNoteById(noteId)
	if log.Error(err) {
		c.Error(errors.NewISE())
		return
	}
	if !in {
		c.Error(errors.NewHttp(http.StatusNotFound, "The requested note was not found"))
		return
	}
	if userId != note.Owner {
		c.Error(errors.NewHttp(http.StatusUnauthorized, "Only owners can open websockets into their notes"))
		return
	}
	conn, err := websocketUpgrader.Upgrade(c.Writer, c.Request, nil)
	if log.Error(err) {
		c.Error(errors.NewISE())
		return
	}
	log.Info("Opening ws for user %v on %v", userId, note.Id)
	bundle := model.NewContext(userId, noteId)
	WrapWebsocket(conn, bundle)
	ws.ProcessMessages(bundle)
}
Example #12
0
func UserLogin(c *gin.Context) {
	var cookie middleware.CookieManager
	cookie = c.MustGet("CM").(middleware.CookieManager)
	if c.Request.Method == "GET" {
		data := tool.GetTD(c)

		fmt.Println(data)
		c.HTML(http.StatusOK, "login.html", data)
	} else if c.Request.Method == "POST" {

		email := c.PostForm("email")
		password := c.PostForm("password")
		user := model.User{}
		model.T.DB.Debug().Where("email = ? and password = ?", email, password).First(&user)
		if user.Name != "" {
			cookie.Add("user_id", user.ID)
			cookie.WriteCookies()
			c.Redirect(http.StatusMovedPermanently, "/")
		} else {
			cookie.Flash("fail_msg", "login failed :(")
			c.Redirect(http.StatusMovedPermanently, "/user/login")
		}

	}
}
Example #13
0
func UserLogout(c *gin.Context) {
	var cookie middleware.CookieManager
	cookie = c.MustGet("CM").(middleware.CookieManager)
	cookie.Delete("user_id")
	cookie.WriteCookies()
	c.Redirect(http.StatusMovedPermanently, "/")
}
Example #14
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, "")
}
Example #15
0
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()
}
Example #16
0
func DeleteAlbumInstance(c *gin.Context) {
	db := c.MustGet("db").(gorm.DB)
	consumer := c.MustGet("consumer").(models.User)

	id := c.Params.ByName("id")

	var album models.Album

	db.First(&album, id)

	if album.Name == "" {
		response := make(map[string]string)
		response["error"] = "Resource not found."
		c.JSON(404, response)
	} else {
		if consumer.Admin {
			db.Delete(&album)
			c.JSON(200, album)
		} else {
			response := make(map[string]string)
			response["error"] = "Invalid credentials."
			c.JSON(401, response)
		}
	}
}
Example #17
0
func AddTemplate(c *gin.Context) {
	project := c.MustGet("project").(models.Project)

	var template models.Template
	if err := c.Bind(&template); err != nil {
		return
	}

	res, err := database.Mysql.Exec("insert into project__template set ssh_key_id=?, project_id=?, inventory_id=?, repository_id=?, environment_id=?, playbook=?, arguments=?, override_args=?", template.SshKeyID, project.ID, template.InventoryID, template.RepositoryID, template.EnvironmentID, template.Playbook, template.Arguments, template.OverrideArguments)
	if err != nil {
		panic(err)
	}

	insertID, err := res.LastInsertId()
	if err != nil {
		panic(err)
	}

	template.ID = int(insertID)

	objType := "template"
	desc := "Template ID " + strconv.Itoa(template.ID) + " created"
	if err := (models.Event{
		ProjectID:   &project.ID,
		ObjectType:  &objType,
		ObjectID:    &template.ID,
		Description: &desc,
	}.Insert()); err != nil {
		panic(err)
	}

	c.JSON(201, template)
}
Example #18
0
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()
}
Example #19
0
func (ss *schedulerService) CreateOrUpdateShift(c *gin.Context) {
	shift := &wiw.Shift{}

	if err := c.BindJSON(shift); err != nil {
		ss.handleError(c, err)
		return
	}
	if shift.ManagerID == 0 {
		//TODO: should use current user id
	}

	if c.Request.Method == "POST" {
		if err := ss.repository.CreateShift(shift); err != nil {
			ss.handleError(c, err)
			return
		}
	} else {
		shift.ID = uint(c.MustGet("id").(int))
		if err := ss.repository.UpdateOrCreateShift(shift); err != nil {
			ss.handleError(c, err)
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{"shift": shift})
}
Example #20
0
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)
}
Example #21
0
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)
}
// 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)

}
Example #23
0
func EditWhiskyFormR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		user        = GetUser(c)
	)

	// only authenticated users can perform this action
	if !user.Authenticated() {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}

	// fetch whisky to edit
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	whisky, err := whiskyStore.GetWhisky(id)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.HTML(http.StatusOK, "whisky-form.html", gin.H{
		"Action": "Edit",
		"User":   user,
		"Form":   whisky,
		"Errors": map[string]string{},
	})
}
// 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})

}
Example #25
0
func UserR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// parse id
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	// fetch whiksy
	whisky, err := whiskyStore.GetWhisky(id)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// fetch reviews
	reviews, err := reviewStore.GetAllReviews(id, 30)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "whisky.html", gin.H{
		"User":    user,
		"Whisky":  whisky,
		"Reviews": reviews,
	})
}
// Creates datasets from a datafile
func (e EndpointContext) CreateDataSetsEndpoint(c *gin.Context) {

	user := c.MustGet(MIDDLEWARE_KEY_USER).(User)
	db := c.MustGet(MIDDLEWARE_KEY_DB).(couch.Database)
	logg.LogTo("REST", "user: %v db: %v", user, db)

	dataset := NewDataset(e.Configuration)

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

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

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

	// the changes listener will see new datafile and download to cbfs

	// update with urls of training/testing artifacts (which don't exist yet)
	if err := dataset.AddArtifactUrls(); err != nil {
		errMsg := fmt.Sprintf("Error updating dataset: %+v.  Err: %v", dataset, err)
		c.String(500, errMsg)
		return
	}

	c.JSON(201, dataset)

}
Example #27
0
func HomeR(c *gin.Context) {
	// dependency injection
	var (
		whiskyStore = c.MustGet(WhiskyStoreKey).(WhiskyStore)
		reviewStore = c.MustGet(ReviewStoreKey).(ReviewStore)
		user        = GetUser(c)
	)

	// temporary variables
	var (
		activity []Review
		trending []Whisky
		err      error
	)

	// get activity stream for user
	activity, err = reviewStore.GetActivity(user.ID, LIMIT)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// get trending whiskies
	trending, err = whiskyStore.GetTrending(LIMIT)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.HTML(http.StatusOK, "home.html", gin.H{
		"User":     user,
		"Activity": activity,
		"Trending": trending,
	})
}
Example #28
0
func (u *AccountHandler) RegisterHandler(c *gin.Context) {
	player := c.MustGet(gin.BindKey).(*ge.PlayerStruct)

	if err := player.HashPassword(); err != nil {
		c.AbortWithError(http.StatusBadRequest, err)
		return
	}

	// Make sure this email hasn't been used yet
	if u.GE.PlayerData.SafeGetByEmail(player.Email) != nil {
		c.AbortWithError(http.StatusBadRequest, ge.ErrorEmailInUse).SetType(gin.ErrorTypePublic)
		return
	}

	u.GE.PlayerData.SafeAdd(player)

	// We have a player, let's make him a planet!
	planet, err := ge.GenerateNewPlanet(u.GE.Universe, u.GE.BaseData)
	if err != nil {
		u.GE.PlayerData.SafeRemove(player.ID)
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	player.AddPlanet(planet)

	u.sendLoginToken(c, player)
}
Example #29
0
func HomeHandler(c *gin.Context) {
	// "SELECT * FROM posts ORDER BY id DESC LIMIT %s", sp
	// "SELECT count(*) FROM posts"
	var posts []Post
	DB.Order("pid desc").Limit(sp).Find(&posts)

	if len(posts) == 0 {
		c.Redirect(http.StatusFound, "/user/compose")
		return
	}
	var countrows int
	DB.Model(&Post{}).Count(&countrows)

	var sumpage int
	if countrows%sp == 0 {
		sumpage = countrows / sp
	} else {
		sumpage = countrows/sp + 1
	}
	//title and tag
	titles := component.GetTitle()
	tags := component.GetTag()
	c.HTML(http.StatusOK, "home.tmpl", gin.H{
		"home":    "welcome home",
		"posts":   posts,
		"sumpage": sumpage,
		"onpage":  1,
		"current": c.MustGet("current").(bool),
		"titles":  titles,
		"tags":    tags,
	})
}
Example #30
0
func (t *TypesController) DeleteType(c *gin.Context) {
	appId := c.Param("appId")
	typeName := c.Param("typeName")

	app := c.MustGet("app").(JSON)

	d := db.NewAppsDbService(c.MustGet("user").(string))
	d.UpdateId(app["_id"],
		JSON{
			"$pull": JSON{
				"types": typeName,
			},
		},
	)

	database := db.NewTypeDbService(appId, typeName)
	session, collection := database.GetCollection()
	defer session.Close()

	dropError := collection.DropCollection()

	if dropError != nil {
		RestError(c, dropError)
		return
	}
}