Ejemplo n.º 1
9
// create handling the creation of a new character
// curl -H "Content-Type: application/json" -X POST -d '{"name":"asdf"}' http://localhost:8989
func create(c *gin.Context) {

	var newName struct {
		Name string `json:"name"`
	}
	ch := NewCharacter{}

	if err := c.BindJSON(&newName); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{"error while binding newName:" + err.Error()})
		return
	}

	checkSum := sha1.Sum([]byte(newName.Name))
	ch.CharacterID = fmt.Sprintf("%x", checkSum)

	char := createCharacter(ch.CharacterID, newName.Name)

	log.Println("Saving character:", char)
	err := mdb.Save(char)
	if err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{"error while saving character:" + err.Error()})
		return
	}
	c.JSON(http.StatusCreated, char)
}
Ejemplo n.º 2
0
// curl -H "Content-Type: application/json" -X POST -d '{"commentableId":3,"commentableType":"post","body":"the body of a comment"}' http://localhost:9999/comments
// CommentCreate creates a comment, validates that it belongs to something commentable
func CommentCreate(c *gin.Context) {
	var comment models.Comment
	if c.BindJSON(&comment) == nil {
		comment.UserID = 1

		if comment.CommentableType == "post" {
			_, err := models.GetPost(comment.CommentableID)
			if err != nil {
				c.JSON(http.StatusNotFound, gin.H{"status": "not found"})
				return
			}
		} else if comment.CommentableType == "comment" {
			_, err := models.GetComment(comment.CommentableID)
			if err != nil {
				c.JSON(http.StatusNotFound, gin.H{"status": "not found"})
				return
			}
		} else {
			c.JSON(http.StatusBadRequest, gin.H{"status": "bad request"})
			return
		}

		// TODO: userID should come from session, commentable id/type maybe from route?
		err := models.CreateComment(comment)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"status": "bad request"})
		} else {
			// TODO: add location header with new resource url
			c.JSON(http.StatusCreated, gin.H{"status": "created"})
		}
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"status": "bad request"})
	}
}
Ejemplo n.º 3
0
func LoginHandler(c *gin.Context) {
	var code int
	var response gin.H

	var loginData loginForm
	c.BindJSON(&loginData)

	errors := loginData.validate()

	if len(errors) == 0 {
		user, authErrors := authOrRegisterUser(loginData)
		if authErrors["password"] != "" {
			code = 422
			response = gin.H{"success": false, "errors": authErrors}
		} else {
			code = 200
			response = gin.H{
				"success": true,
				"new":     user.RestoreCode != "",
				"auth": gin.H{
					"account": user.Email,
					"token":   createUserToken(user),
					"roles":   user.Roles,
				},
			}
		}
	} else {
		code = 422
		response = gin.H{"success": false, "errors": errors}
	}
	c.JSON(code, response)
}
Ejemplo n.º 4
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})
}
Ejemplo n.º 5
0
func pluginCreate(c *gin.Context) {
	plugin := Plugin{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&plugin); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	cnt := 0
	mydb.Table("plugin").Where("name=?", plugin.Name).Count(&cnt)
	if cnt > 0 {
		response["code"] = http.StatusBadRequest
		response["message"] = "plugin already exists"
		return
	}
	if err := mydb.Set("gorm:save_associations", false).Save(&plugin).Error; err != nil {
		response["code"] = http.StatusInternalServerError
		response["message"] = err.Error()
		return
	}
	mydb.Model(&plugin).Association("Hosts").Replace(plugin.Hosts).Find(&plugin.Hosts)

	response["code"] = http.StatusOK
	response["message"] = "user create successful"
	response["plugin"] = plugin
}
Ejemplo n.º 6
0
func changePassword(c *gin.Context) {
	request := struct {
		ID              int    `json:'id'`
		CurrentPassword string `json:"current_password"`
		NewPassword     string `json:"new_password"`
	}{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&request); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	currentUser := GetUser(c)
	if !currentUser.IsAdmin() && currentUser.ID != request.ID {
		response["code"] = 403
		response["message"] = "You don't have permission to access."
		return
	}
	if request.CurrentPassword == request.NewPassword {
		response["code"] = http.StatusNotModified
		response["message"] = "new password equal current password"
		return
	}
	user := types.User{}
	mydb.Table("user").Where("id = ?", request.ID).Find(&user)
	if user.Password != utils.Md5(request.CurrentPassword) {
		response["code"] = http.StatusNotModified
		response["message"] = "current password is incorrect"
		return
	}
	mydb.Table("user").Where("id = ?", request.ID).Update("password", utils.Md5(request.NewPassword))
	response["code"] = http.StatusOK
	response["message"] = "change password success"
}
Ejemplo n.º 7
0
func groupCreate(c *gin.Context) {
	group := Group{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&group); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	cnt := 0
	mydb.Table("group").Where("name=?", group.Name).Count(&cnt)
	if cnt > 0 {
		response["code"] = http.StatusBadRequest
		response["message"] = "group already exists"
		return
	}
	if err := mydb.Set("gorm:save_associations", false).Save(&group).Error; err != nil {
		response["code"] = http.StatusInternalServerError
		response["message"] = err.Error()
		return
	}
	mydb.Model(&group).Association("Hosts").Replace(group.Hosts).Find(&group.Hosts)

	response["code"] = http.StatusOK
	response["message"] = "group create successful"
	response["group"] = group
}
Ejemplo n.º 8
0
func UpdateConfig(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	data := &updateConfigData{}
	if err := c.BindJSON(data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if err := verifyUpdateConfigData(data); err != nil {
		Error(c, BAD_REQUEST, err.Error())
		return
	}

	oldConfig := memConfRawConfigs[data.Key]
	if oldConfig.K == data.K && oldConfig.V == data.V && oldConfig.VType == data.VType && oldConfig.Des == data.Des && oldConfig.Status == data.Status {
		Success(c, nil)
		return
	}

	config, err := updateConfigWithUpdateData(data, getOpUserKey(c))
	if err != nil {
		Error(c, SERVER_ERROR, err)
		return
	}

	failedNodes := syncData2SlaveIfNeed(config, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
Ejemplo n.º 9
0
func InitUser(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	if len(memConfUsers) > 0 {
		Error(c, BAD_REQUEST, "users already exists")
		return
	}

	data := &newUserData{}
	if err := c.BindJSON(data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if err := verifyNewUserData(data); err != nil {
		Error(c, BAD_REQUEST, err.Error())
		return
	}

	key := utils.GenerateKey()
	user, err := newUserWithNewUserData(data, key, key)
	if err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	failedNodes := syncData2SlaveIfNeed(user, key)
	setUserKeyCookie(c, user.Key, user.PassCode)
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
Ejemplo n.º 10
0
func Login(c *gin.Context) {
	var data struct {
		Name     string `json:"name" binding:"required"`
		PassCode string `json:"pass_code" binding:"required"`
	}
	if err := c.BindJSON(&data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	memConfMux.RLock()
	user := memConfUsersByName[data.Name]
	memConfMux.RUnlock()

	if user == nil {
		Error(c, USER_NOT_EXIST)
		return
	}
	if user.PassCode != encryptUserPassCode(data.PassCode) {
		Error(c, PASS_CODE_ERROR)
		return
	}

	if user.Status == models.USER_STATUS_INACTIVE {
		Error(c, USER_INACTIVE)
		return
	}

	setUserKeyCookie(c, user.Key, user.PassCode)
	Success(c, nil)
}
Ejemplo n.º 11
0
func NewConfig(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	data := &newConfigData{}
	if err := c.BindJSON(data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if err := verifyNewConfigData(data); err != nil {
		Error(c, BAD_REQUEST, err.Error())
		return
	}

	config, err := newConfigWithNewConfigData(data, getOpUserKey(c))
	if err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	failedNodes := syncData2SlaveIfNeed(config, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
Ejemplo n.º 12
0
func UpdateApp(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	var data struct {
		Key     string `json:"key" binding:"required"`
		Name    string `json:"name" binding:"required"`
		Type    string `json:"type" binding:"required"`
		AuxInfo string `json:"aux_info"`
	}
	if err := c.BindJSON(&data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if !models.IsValidAppType(data.Type) {
		Error(c, BAD_REQUEST, "unknown app type: "+data.Type)
		return
	}

	oldApp := memConfApps[data.Key]
	if oldApp == nil {
		Error(c, BAD_REQUEST, "app key not exists: "+data.Key)
		return
	}

	if oldApp.Name == data.Name && oldApp.AuxInfo == data.AuxInfo && oldApp.Type == data.Type {
		Success(c, nil)
		return
	}

	if oldApp.Type == models.APP_TYPE_TEMPLATE && oldApp.Type != data.Type {
		Error(c, BAD_REQUEST, "can not change template app to real app")
		return
	}

	if memConfApps[data.Key].Name != data.Name {
		for _, app := range memConfApps {
			if app.Name == data.Name {
				Error(c, BAD_REQUEST, "appname already exists: "+data.Name)
				return
			}
		}
	}

	app := *oldApp
	app.Name = data.Name
	app.AuxInfo = data.AuxInfo
	if _, err := updateApp(&app, nil, nil); err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	failedNodes := syncData2SlaveIfNeed(&app, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
Ejemplo n.º 13
0
func UpdateUserPassCode(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	var data struct {
		PassCode string `json:"pass_code" binding:"required"`
	}
	if err := c.BindJSON(&data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	user := *memConfUsers[getOpUserKey(c)]
	user.PassCode = encryptUserPassCode(data.PassCode)

	if _, err := updateUser(&user, nil); err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	setUserKeyCookie(c, user.Key, user.PassCode)
	failedNodes := syncData2SlaveIfNeed(&user, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
Ejemplo n.º 14
0
func UpdateUser(c *gin.Context) {
	confWriteMux.Lock()
	defer confWriteMux.Unlock()

	data := &updateUserData{}
	if err := c.BindJSON(data); err != nil {
		Error(c, BAD_POST_DATA, err.Error())
		return
	}

	if err := verifyUpdateUserData(data, getOpUserKey(c)); err != nil {
		Error(c, BAD_REQUEST, err.Error())
		return
	}

	oldUser := memConfUsers[getOpUserKey(c)]
	if oldUser.AuxInfo == data.AuxInfo && oldUser.Name == data.Name {
		Success(c, nil)
		return
	}

	user, err := updateUserWithUpdateData(data, getOpUserKey(c))
	if err != nil {
		Error(c, SERVER_ERROR, err.Error())
		return
	}

	failedNodes := syncData2SlaveIfNeed(user, getOpUserKey(c))
	if len(failedNodes) > 0 {
		Success(c, map[string]interface{}{"failed_nodes": failedNodes})
	} else {
		Success(c, nil)
	}
}
Ejemplo n.º 15
0
//DownloadPacket starts the download of a packet
func (dc *DownloadsController) startDirectDownload(c *gin.Context) {
	var download models.DirectDownload
	c.BindJSON(&download)

	dc.IrcClient.AddDirectDownload(&download)
	OK(c)
}
Ejemplo n.º 16
0
//TaskCreate serves the route POST /tasks
func TaskCreate(c *gin.Context) {
	models.InTx(func(txn *gorm.DB) bool {
		var task models.Task
		if err := c.BindJSON(&task); err != nil {
			c.JSON(http.StatusBadRequest, err)
			return false
		}
		if valid, errMap := models.ValidStruct(&task); !valid {
			c.JSON(http.StatusConflict, errMap)
			return false
		}
		var taskExistent models.Task
		models.Gdb.Where("id like ?", task.ID).First(&taskExistent)
		var err error
		if task.ID != "" && taskExistent.ID != "" {
			taskExistent.Periodicity = task.Periodicity
			taskExistent.Command = task.Command
			err = txn.Save(&taskExistent).Error
		} else {
			err = txn.Create(&task).Error
		}
		if err != nil {
			c.JSON(http.StatusBadRequest, "Couldn't create the task")
			return false
		}
		c.JSON(http.StatusOK, task)
		return true
	})
}
Ejemplo n.º 17
0
func userUpdate(c *gin.Context) {
	user := User{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)

	if err := c.BindJSON(&user); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	currentUser := GetUser(c)
	if !currentUser.IsAdmin() && currentUser.ID != user.ID {
		response["code"] = 403
		response["message"] = "You don't have permission to access."
		return
	}
	if err := mydb.Set("gorm:save_associations", false).Table("user").
		Select("username", "role", "phone", "mail", "weixin", "status").Save(&user).
		Association("Groups").Replace(user.Groups).Error; err != nil {
		response["code"] = http.StatusInternalServerError
		response["message"] = err.Error()
		return
	}
	response["code"] = http.StatusOK
	response["message"] = "user update successful"
}
Ejemplo n.º 18
0
func (service *metricsService) createMetric(c *gin.Context) {
	var entry common.MetricEntry

	if err := c.BindJSON(&entry); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err})
		c.Abort()
		return
	}

	entry.Time = time.Now().UTC()

	b, err := json.Marshal(entry)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err})
		c.Abort()
		return
	}

	if err := service.connector.Publish(b); err != nil {
		log.Println("error", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": err})
		c.Abort()
		return
	}

	c.JSON(http.StatusOK, entry)
}
Ejemplo n.º 19
0
func userCreate(c *gin.Context) {
	user := User{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&user); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	if user.Username == "" || user.Phone == "" {
		response["code"] = http.StatusBadRequest
		response["message"] = "The username and phone number are not allowed to be empty"
		return
	}
	cnt := 0
	mydb.Table("user").Where("username=?", user.Username).Count(&cnt)
	if cnt > 0 {
		response["code"] = http.StatusBadRequest
		response["message"] = "username already exists"
		return
	}
	user.Password = utils.Md5(user.Username)
	if err := mydb.Set("gorm:save_associations", false).Save(&user).Error; err != nil {
		response["code"] = http.StatusInternalServerError
		response["message"] = err.Error()
		return
	}
	mydb.Model(&user).Association("Groups").Replace(user.Groups).Find(&user.Groups)

	response["code"] = http.StatusOK
	response["message"] = "user create successful"
	response["user"] = user
}
Ejemplo n.º 20
0
func panelCreate(c *gin.Context) {
	panel := types.Panel{}
	response := gin.H{"code": http.StatusOK}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&panel); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return
	}
	if !mydb.Table("panel").Where("user_id = ? and name = ?", GetUser(c).ID, panel.Name).First(&panel).RecordNotFound() {
		response["code"] = http.StatusBadRequest
		response["message"] = "panel already exists"
		return
	}
	panel.UserID = GetUser(c).ID
	if err := mydb.Select("name", "thumbnail", "user_id").Save(&panel).Error; err != nil {
		response["code"] = http.StatusInternalServerError
		response["message"] = err.Error()
		return
	}
	mydb.Model(&panel).Association("Charts").Replace(panel.Charts)
	mydb.Model(&panel).Find(&panel)
	for _, chart := range panel.Charts {
		mydb.Model(&chart).Related(&chart.Elements)
	}
	response["panel"] = panel
}
Ejemplo n.º 21
0
func RegisterUser(c *gin.Context) {

	var login Login

	if c.BindJSON(&login) == nil {
		user, err := models.FindUserByEmail(login.Email)

		if err != nil && err.Error() != "not found" {
			fmt.Printf("Error looking up user %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{"status": "Error Looking Up User."})
			return
		}
		if user.ID.Valid() {
			fmt.Printf("User already exists %v ", user)
			c.JSON(http.StatusConflict, gin.H{"status": "User Already Exists."})
			return
		}

		salt := makeSalt()

		user = models.User{Email: login.Email, Salt: salt, UserName: login.Email, HashedPassword: ComputeHmac256(login.Password, getSecret(salt))}
		newUser, err := models.CreateUser(user)
		if err != nil || !newUser.ID.Valid() {
			fmt.Printf("Error creating user account %v %v ", newUser, err)
			c.JSON(http.StatusInternalServerError, gin.H{"status": "Error Creating New User Record."})

		}
		c.JSON(http.StatusOK, gin.H{"status": "New Subscription Successful"})
		return

	} else {
		c.JSON(http.StatusNotFound, gin.H{"status": "Invalid Registration Information"})
	}

}
Ejemplo n.º 22
0
func panelUpdate(c *gin.Context) {
	panel := types.Panel{}
	response := gin.H{}
	defer c.JSON(http.StatusOK, response)
	if err := c.BindJSON(&panel); err != nil {
		response["code"] = http.StatusBadRequest
		response["message"] = err.Error()
		return

	}
	if mydb.Table("panel").Where("id = ? and user_id = ?", panel.ID, GetUser(c).ID).Find(&types.Panel{}).RecordNotFound() {
		response["code"] = http.StatusNotFound
		response["message"] = "The panel not found"
		return
	}
	if err := mydb.Model(&panel).Select("name", "thumbnail").Updates(&panel).Error; err != nil {
		response["code"] = http.StatusInternalServerError
		response["message"] = err.Error()
		return
	}
	mydb.Model(&panel).Association("Charts").Replace(panel.Charts)
	for _, chart := range panel.Charts {
		mydb.Model(&chart).Related(&chart.Elements)
	}
	response["code"] = http.StatusOK
	response["message"] = "panel update successful"
	response["panel"] = panel
}
Ejemplo n.º 23
0
func UpdateProfileHandler(c *gin.Context) {
	user := ContextAuthUser(c)
	profile := &ProfileModel{}
	DB.C(USERS).FindId(user.Id).One(&profile)

	var data profileForm
	c.BindJSON(&data)

	errors := data.validate()
	if len(errors) == 0 {
		profile.Name = data.Name
		profile.Phone = data.Phone
		DB.C(USERS).UpdateId(user.Id, bson.M{"$set": profile})
		c.JSON(200, gin.H{
			"success": true,
			"object":  profile,
		})
	} else {
		c.JSON(422, gin.H{
			"success": false,
			"errors":  errors,
		})
	}

}
Ejemplo n.º 24
0
// StopAdventure Stop adventuring
func stopAdventure(c *gin.Context) {
	//signal channel to stop fight.
	var adventurer struct {
		Name string `json:"name"`
	}

	if err := c.BindJSON(&adventurer); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{"error while binding adventurer:" + err.Error()})
		return
	}

	char, err := mdb.Load(adventurer.Name)
	if err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{"Error occured while loading character:" + err.Error()})
		return
	}

	log.Println("Loaded adventurer:", char)

	adventurersOnQuest.RLock()
	adv := adventurersOnQuest.m[char.Name]
	adventurersOnQuest.RUnlock()
	if !adv {
		c.JSON(http.StatusBadRequest, ErrorResponse{"Error occured, adventurer is not adventuring!"})
		return
	}
	select {
	case adventureSignal <- true:
	default:
	}

	m := Message{}
	m.Message = "Stop adventuring for character: " + char.Name
	c.JSON(http.StatusOK, m)
}
Ejemplo n.º 25
0
func parse(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Headers", "origin, content-type, accept")

	var json Request
	err := c.BindJSON(&json)
	if err != nil || json.Link == "" {
		c.JSON(http.StatusBadRequest, gin.H{"message": "Incrorrect request"})
		return
	}

	link := json.Link

	u, err := url.Parse(link)
	if err != nil {
		c.JSON(400, gin.H{"message": "Broken link", "link": link})
		return
	}

	id := insertUrl(u.String())

	go grab(u, id)

	c.JSON(http.StatusCreated, gin.H{"message": "processing", "id": id, "link": link})
}
Ejemplo n.º 26
0
// StartAdventure starts and adventure in an endless for loop, until a channel signals otherwise
func startAdventure(c *gin.Context) {

	var adventurer struct {
		Name string `json:"name"`
	}

	if err := c.BindJSON(&adventurer); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{"error while binding adventurer:" + err.Error()})
		return
	}

	char, err := mdb.Load(adventurer.Name)
	if err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{"Error occured while loading character:" + err.Error()})
		return
	}

	adventurersOnQuest.RLock()
	adv := adventurersOnQuest.m[char.Name]
	adventurersOnQuest.RUnlock()

	if adv {
		c.JSON(http.StatusBadRequest, ErrorResponse{"Error occured, adventurer is already adventuring!"})
		return
	}

	go adventuring(char.Name)

	m := Message{}
	m.Message = "Started adventuring for character: " + char.Name
	c.JSON(http.StatusOK, m)
}
Ejemplo n.º 27
0
// DeleteLog deletes a device based on the identifier.
func DeleteLog(c *gin.Context) {
	id := c.Params.ByName("id")

	if id != "" {
		var log models.Log
		err := c.BindJSON(&log)

		if err == nil {
			uid, err := authentication.GetUserID(c)

			if err == nil {
				log.UserID = uid
				count, err := configuration.Dbmap.Delete(&log)

				if err == nil && count == 1 {
					showSucces(c, fmt.Sprintf("log entry with id %s is deleted", id))
					return
				}
			}
		}

		showError(c, 400, fmt.Errorf("deleting log entry failed"))
		return
	}

	showError(c, 400, fmt.Errorf("deleting log entry failed due to missing identifier"))
}
Ejemplo n.º 28
0
//ExecutionCreate serves the route POST /tasks/:task_id/executions
func ExecutionCreate(c *gin.Context) {
	models.InTx(func(txn *gorm.DB) bool {
		var task models.Task
		if txn.Where("id like ? ", c.Param("task_id")).First(&task); task.ID == "" {
			c.JSON(http.StatusNotFound, "")
			return false
		}
		var execution models.Execution
		if err := c.BindJSON(&execution); err != nil {
			c.JSON(http.StatusBadRequest, err)
			return false
		}
		execution.TaskID = task.ID
		if valid, errMap := models.ValidStruct(&execution); !valid {
			c.JSON(http.StatusConflict, errMap)
			return false
		}
		if txn.Create(&execution).Error != nil {
			c.JSON(http.StatusBadRequest, "Execution can't be saved")
			return false
		}
		c.JSON(http.StatusOK, execution)
		return true
	})
}
Ejemplo n.º 29
0
// disable user
func (u *User) Active(c *gin.Context) {
	if !isGranted(c, "user.active") {
		c.JSON(403, utils.NewNoAccessPermissionError(""))
		return
	}

	id := paramInt64(c, "id")
	var user models.User
	var data models.User
	if err := c.BindJSON(&data); err != nil {
		c.JSON(400, utils.NewInvalidJsonError())
		return
	}

	if err := models.GetById(id, &user); err != nil {
		c.JSON(400, utils.NewNotFoundError())
		return
	}

	fmt.Println("is active", data.IsActive)
	user.IsActive = data.IsActive
	if err := models.UpdateById(id, &user, "is_active"); err != nil {
		c.JSON(400, utils.NewError("update database failed - %s", err.Error()))
		return
	}

	c.JSON(200, gin.H{
		"success": true,
	})

}
Ejemplo n.º 30
0
func SetUserSchool(c *gin.Context) {
	userId := c.Param("user_id")
	if userId != c.MustGet("request_user_id").(string) {
		c.Error(errors.NewHttp(http.StatusUnauthorized, "Users can only modify themselves"))
		return
	}
	var request model.ModifySchoolRequest
	err := c.BindJSON(&request)
	if log.Error(err) {
		c.Error(err)
		return
	}
	_, user, err := db.GetUserById(userId)
	if log.Error(err) {
		c.Error(err)
		return
	}
	user.School = sql.NullString{
		String: request.SchoolId,
		Valid:  true,
	}
	err = db.UpdateUser(user)
	if log.Error(err) {
		c.Error(err)
		return
	}
	c.JSON(http.StatusOK, user)
}