示例#1
0
func (u *AccountHandler) sendLoginToken(c *gin.Context, player *ge.PlayerStruct) {
	if token, err := u.createLoginToken(player); err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
	} else {
		c.JSON(http.StatusOK, gin.H{"Token": token})
	}
}
示例#2
0
// ProfileToken displays the users token.
func ProfileToken(c *gin.Context) {
	record := session.Current(c)

	token := token.New(token.UserToken, record.Username)
	result, err := token.SignUnlimited(record.Hash)

	if err != nil {
		logrus.Warnf("Failed to generate token. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to generate token",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		result,
	)
}
示例#3
0
// UserOrgIndex retrieves all orgs related to a user.
func UserOrgIndex(c *gin.Context) {
	records, err := store.GetUserOrgs(
		c,
		&model.UserOrgParams{
			User: c.Param("user"),
		},
	)

	if err != nil {
		logrus.Warnf("Failed to fetch user orgs. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to fetch orgs",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		records,
	)
}
示例#4
0
文件: messages.go 项目: vmalguy/tat
func (m *MessagesController) addOrRemoveTag(ctx *gin.Context, messageIn *messageJSON, message models.Message, user models.User) {

	if !user.IsSystem {
		ctx.JSON(http.StatusForbidden, gin.H{"error": "Invalid Action for non-system user"})
		return
	}

	if messageIn.Text == "" {
		ctx.AbortWithError(http.StatusBadRequest, errors.New("Invalid Text for tag"))
		return
	}

	if messageIn.Action == "tag" {
		err := message.AddTag(messageIn.Text)
		if err != nil {
			log.Errorf("Error while adding a tag to a message %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
	} else if messageIn.Action == "untag" {
		err := message.RemoveTag(messageIn.Text)
		if err != nil {
			log.Errorf("Error while remove a tag from a message %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
	} else {
		ctx.AbortWithError(http.StatusBadRequest, errors.New("Invalid action : "+messageIn.Action))
		return
	}
	go models.WSMessage(&models.WSMessageJSON{Action: messageIn.Action, Username: user.Username, Message: message})
	ctx.JSON(http.StatusCreated, "")
}
示例#5
0
文件: users.go 项目: zannet/karousel
func GetUserInstance(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 user.Id != consumer.Id {
			if user.Gravatar == "" {
				user.Gravatar = user.Email
			}
			user.Email = ""
		}
		user.Password = ""
		c.JSON(200, user)
	}
}
示例#6
0
文件: tenant.go 项目: hefju/RentPro
func (page *Tenant) Get(c *gin.Context) {
	fmt.Println("Tenant.Get")
	tenants := make([]model.Tenant, 0)
	idstr := c.Query("id")
	//id:=c.Param("id")
	//fmt.Println("Params:",idstr)
	id, err := strconv.Atoi(idstr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"status": "Params err"})
	}
	where := ""
	if id > 0 {
		where = "Id=" + idstr
	} else {
		where = "Id>0"
	}

	err = vars.Db.Where(where).Find(&tenants)
	if err != nil {
		log.Println(err)
	}
	//fmt.Println(tenants)
	//  tenant:=model.Tenant{Id:10,Name:"hefju520",Phone:"13929961332",Desc:"测试返回json"}
	c.JSON(http.StatusOK, tenants)
}
示例#7
0
文件: messages.go 项目: vmalguy/tat
func (m *MessagesController) likeOrUnlike(ctx *gin.Context, action string, message models.Message, topic models.Topic, user models.User) {
	isReadAccess := topic.IsUserReadAccess(user)
	if !isReadAccess {
		ctx.AbortWithError(http.StatusInternalServerError, errors.New("No Read Access to topic "+message.Topics[0]))
		return
	}

	info := ""
	if action == "like" {
		err := message.Like(user)
		if err != nil {
			log.Errorf("Error while like a message %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		info = "like added"
	} else if action == "unlike" {
		err := message.Unlike(user)
		if err != nil {
			log.Errorf("Error while like a message %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		info = "like removed"
	} else {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Invalid action : " + action)})
		return
	}
	go models.WSMessage(&models.WSMessageJSON{Action: action, Username: user.Username, Message: message})
	ctx.JSON(http.StatusCreated, gin.H{"info": info})
}
示例#8
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)
}
示例#9
0
文件: repos.go 项目: smira/aptly
// POST /api/repos
func apiReposCreate(c *gin.Context) {
	var b struct {
		Name                string `binding:"required"`
		Comment             string
		DefaultDistribution string
		DefaultComponent    string
	}

	if !c.Bind(&b) {
		return
	}

	repo := deb.NewLocalRepo(b.Name, b.Comment)
	repo.DefaultComponent = b.DefaultComponent
	repo.DefaultDistribution = b.DefaultDistribution

	collection := context.CollectionFactory().LocalRepoCollection()
	collection.Lock()
	defer collection.Unlock()

	err := context.CollectionFactory().LocalRepoCollection().Add(repo)
	if err != nil {
		c.Fail(400, err)
		return
	}

	c.JSON(201, repo)
}
示例#10
0
func QueryData(c *gin.Context) {
	result := QDataGet(c)
	c.JSON(200, gin.H{
		"status": "ok",
		"data":   result,
	})
}
示例#11
0
func usersDetail(c *gin.Context) {
	user_id := c.Params.ByName("id")
	a_id, _ := strconv.Atoi(user_id)
	user := getuser(a_id)
	content := gin.H{"Name": user.Name, "content": user.Address}
	c.JSON(200, content)
}
示例#12
0
文件: spec.go 项目: servozl/gongfu-1
func GetUsers(c *gin.Context) {
	m := Msg{
		Message: "This is GetUsers",
		Status:  200,
	}
	c.JSON(200, m)
}
示例#13
0
func PostUser(c *gin.Context) {
	var user User
	c.Bind(&user)

	if user.Firstname != "" && user.Lastname != "" {
		db, _ := sql.Open("postgres", "user=cshutchinson dbname=godb sslmode=disable")
		// checkErr(err)
		var lastInsertId int64
		_ = db.QueryRow("INSERT INTO users(firstname,lastname, id) VALUES($1,$2, Default) returning id;", user.Firstname, user.Lastname).Scan(&lastInsertId)
		content := &User{
			Id:        lastInsertId,
			Firstname: user.Firstname,
			Lastname:  user.Lastname,
		}
		c.JSON(201, content)
		// if insert, _ := dbmap.Exec(`INSERT INTO users (firstname, lastname) VALUES (?, ?) returning id;`, user.Firstname, user.Lastname).Scan(&lastInsertId); insert != nil {
		//   user_id, err := insert.LastInsertId()
		//   if err == nil {
		//     content := &User{
		//       Id: user_id,
		//       Firstname: user.Firstname,
		//       Lastname: user.Lastname,
		//     }
		//     c.JSON(201, content)
		//   } else {
		//     checkErr(err, "Insert failed")
		//   }
		// }
	} else {
		c.JSON(422, gin.H{"error": "fields are empty"})
	}
	// curl -i -X POST -H "Content-Type: application/json" -d "{ \"firstname\": \"Thea\", \"lastname\": \"Queen\" }" http://localhost:8080/api/v1/users
}
示例#14
0
func gettingAll(c *gin.Context) {

	//serve http://localhost:8080/allGet

	c.JSON(200, Dogs)

}
示例#15
0
文件: api.go 项目: mavencode01/pgweb
func HandleQuery(query string, c *gin.Context) {
	rawQuery, err := base64.StdEncoding.DecodeString(query)
	if err == nil {
		query = string(rawQuery)
	}

	result, err := DB(c).Query(query)
	if err != nil {
		c.JSON(400, NewError(err))
		return
	}

	format := getQueryParam(c, "format")
	filename := getQueryParam(c, "filename")

	if filename == "" {
		filename = fmt.Sprintf("pgweb-%v.%v", time.Now().Unix(), format)
	}

	if format != "" {
		c.Writer.Header().Set("Content-disposition", "attachment;filename="+filename)
	}

	switch format {
	case "csv":
		c.Data(200, "text/csv", result.CSV())
	case "json":
		c.Data(200, "applicaiton/json", result.JSON())
	case "xml":
		c.XML(200, result)
	default:
		c.JSON(200, result)
	}
}
示例#16
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})
}
示例#17
0
func (rest *RestInterface) logs(c *gin.Context) {

	agentID := agentInformation(c)

	db := rest.pool.Get()
	defer db.Close()

	log.Printf("[+] gin: log (gid: %s, nid: %s)\n", agentID.GID, agentID.NID)

	// read body
	content, err := ioutil.ReadAll(c.Request.Body)

	if err != nil {
		log.Println("[-] cannot read body:", err)
		c.JSON(http.StatusInternalServerError, "error")
		return
	}

	// push body to redis
	id := fmt.Sprintf("%s:%s:log", agentID.GID, agentID.NID)
	log.Printf("[+] message destination [%s]\n", id)

	// push message to client queue
	_, err = db.Do("RPUSH", id, content)

	c.JSON(http.StatusOK, "ok")
}
示例#18
0
func lobbyInitializeEndPoin(c *gin.Context) {
	roomIDs, _ := getNewRoomIDs(0, 10)

	roomList := make([]interface{}, len(roomIDs))
	for i, roomID := range roomIDs {
		raw, _ := getRoomRaw(roomID)
		username, err := getUsername(raw.OwnerID)
		if err != nil {
			continue
		}
		roomList[i] = struct {
			ID             int
			Name           string
			Description    string
			CreationTime   string
			LastUpdateTime string
			IsPrivate      bool
			Members        int
			OwnerName      string
		}{
			ID:             raw.ID,
			Name:           raw.Name,
			Description:    raw.Description,
			CreationTime:   time.Unix(raw.CreationTime, 0).Format(TIME_LAYOUT),
			LastUpdateTime: time.Unix(raw.LastUpdateTime, 0).Format(TIME_LAYOUT),
			IsPrivate:      raw.IsPrivate,
			Members:        raw.Members,
			OwnerName:      username,
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"roomList": roomList,
	})
}
示例#19
0
文件: user.go 项目: VincentYu/server
// 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,
	})

}
示例#20
0
func GetTableRows(c *gin.Context) {
	limit := 1000 // Number of rows to fetch
	limitVal := c.Request.FormValue("limit")

	if limitVal != "" {
		num, err := strconv.Atoi(limitVal)

		if err != nil {
			c.JSON(400, Error{"Invalid limit value"})
			return
		}

		if num <= 0 {
			c.JSON(400, Error{"Limit should be greater than 0"})
			return
		}

		limit = num
	}

	opts := client.RowsOptions{
		Limit:      limit,
		SortColumn: c.Request.FormValue("sort_column"),
		SortOrder:  c.Request.FormValue("sort_order"),
	}

	res, err := DbClient.TableRows(c.Params.ByName("table"), opts)
	serveResult(res, err, c)
}
示例#21
0
文件: messages.go 项目: vmalguy/tat
func (m *MessagesController) addOrRemoveLabel(ctx *gin.Context, messageIn *messageJSON, message models.Message, user models.User) {
	if messageIn.Text == "" {
		ctx.AbortWithError(http.StatusBadRequest, errors.New("Invalid Text for label"))
		return
	}
	info := gin.H{}
	if messageIn.Action == "label" {
		addedLabel, err := message.AddLabel(messageIn.Text, messageIn.Option)
		if err != nil {
			log.Errorf("Error while adding a label to a message %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		info = gin.H{"info": fmt.Sprintf("label %s added to message", addedLabel.Text), "label": addedLabel, "message": message}
	} else if messageIn.Action == "unlabel" {
		err := message.RemoveLabel(messageIn.Text)
		if err != nil {
			log.Errorf("Error while remove a label from a message %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		info = gin.H{"info": fmt.Sprintf("label %s removed from message", messageIn.Text), "message": message}
	} else {
		ctx.AbortWithError(http.StatusBadRequest, errors.New("Invalid action : "+messageIn.Action))
		return
	}
	go models.WSMessage(&models.WSMessageJSON{Action: messageIn.Action, Username: user.Username, Message: message})
	ctx.JSON(http.StatusCreated, info)
}
示例#22
0
func ApiGetPassphraseRoute(c *gin.Context) {
	// extracting length of password from query parameters
	var length int = 5
	if len(c.Query("parts")) > 0 {
		parts, _ := strconv.ParseInt(c.Query("parts"), 10, 64)
		length = int(parts)

		// if its not matching number range, throw 400 error request
		if length <= 0 || 99 < length {
			c.JSON(400, gin.H{
				"meta": gin.H{
					"message": "Parts need to be integer in range <1,99>.",
				},
			})
			return
		}
	}

	// generate password
	passphrase := diceware.GeneratePassphrase(length)

	// send success response
	c.JSON(200, gin.H{
		"meta": gin.H{
			"message": "Ok.",
		},
		"data": gin.H{
			"passphrase": gin.H{
				"text":  strings.Join(passphrase, ""),
				"parts": passphrase,
			},
		},
	})
}
示例#23
0
文件: messages.go 项目: vmalguy/tat
func (m *MessagesController) addOrRemoveTask(ctx *gin.Context, messageIn *messageJSON, message models.Message, user models.User, topic models.Topic) {
	info := ""
	if messageIn.Action == "task" {
		err := message.AddToTasks(user, topic)
		if err != nil {
			log.Errorf("Error while adding a message to tasks %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		info = fmt.Sprintf("New Task created in %s", models.GetPrivateTopicTaskName(user))
	} else if messageIn.Action == "untask" {
		err := message.RemoveFromTasks(user, topic)
		if err != nil {
			log.Errorf("Error while remove a message from tasks %s", err)
			ctx.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		info = fmt.Sprintf("Task removed from %s", models.GetPrivateTopicTaskName(user))
	} else {
		ctx.AbortWithError(http.StatusBadRequest, errors.New("Invalid action : "+messageIn.Action))
		return
	}
	go models.WSMessage(&models.WSMessageJSON{Action: messageIn.Action, Username: user.Username, Message: message})
	ctx.JSON(http.StatusCreated, gin.H{"info": info})
}
示例#24
0
func loginHandler(c *gin.Context) {
	var (
		login LoginData
	)
	// bind POST data to struct
	err := c.Bind(&login)
	if err != nil {
		c.JSON(401, "Invalid Credentials Provided")
	} else {
		// return 401 if empty
		if login.Username == "" || login.Password == "" {
			c.JSON(401, "Invalid Credentials Provided")
			return
		}

		// get user from database and fill our struct
		dbUserObject, err := validateUser(login.Username, login.Password)
		if err != nil {
			// return 401 if incorect user or password
			c.JSON(401, "Invalid Credentials")
			return
		}
		// generate token
		token := genToken(dbUserObject)

		// return token to user
		c.JSON(200, token)
		return
	}

	// return 400 if any other error is encountered
	c.JSON(400, "Error encountered")
}
示例#25
0
func Error(c *gin.Context) {
	c.Next()
	id, _ := c.Get("request_id")

	// Log out every error we have encoutered (which in most cases is just 1)
	for _, ginError := range c.Errors {
		actError := ginError.Err
		log.InfoFields("Request error", log.Fields{
			"request_id": id,
			"body":       formatErrorBody(actError.Error()),
		})
	}

	// Grab the last error and use that as the error we return to the client
	if len(c.Errors) > 0 {
		clientError := c.Errors[len(c.Errors)-1].Err

		// If it isn't an errors.Http type, assume it is a 500 and return that
		switch clientError.(type) {
		case errors.Http:
			break
		default:
			if c.IsAborted() {
				clientError = errors.NewHttp(c.Writer.Status(), formatErrorBody(clientError.Error()))
			} else {
				clientError = errors.NewHttp(http.StatusInternalServerError, "Unrecognized error")
			}
		}

		// Now write the error to the client
		c.JSON(clientError.(errors.Http).Code, clientError)
	}

}
示例#26
0
func ArticlesDetail(c *gin.Context) {
	article_id := c.Params.ByName("id")
	a_id, _ := strconv.Atoi(article_id)
	article := getArticle(a_id)
	content := gin.H{"title": article.Title, "content": article.Content}
	c.JSON(200, content)
}
示例#27
0
// UserIndex retrieves all available users.
func UserIndex(c *gin.Context) {
	records, err := store.GetUsers(
		c,
	)

	if err != nil {
		logrus.Warnf("Failed to fetch users. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to fetch users",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		records,
	)
}
示例#28
0
文件: login.go 项目: 2bizi/goapicore
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)
}
示例#29
0
// UserDelete removes a specific user.
func UserDelete(c *gin.Context) {
	record := session.User(c)

	err := store.DeleteUser(
		c,
		record,
	)

	if err != nil {
		logrus.Warnf("Failed to delete user. %s", err)

		c.JSON(
			http.StatusBadRequest,
			gin.H{
				"status":  http.StatusBadRequest,
				"message": "Failed to delete user",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		gin.H{
			"status":  http.StatusOK,
			"message": "Successfully deleted user",
		},
	)
}
示例#30
0
func (self TrainsSpResource) Lines(c *gin.Context) {
	var l []*models.Line

	err := self.DB.Find(bson.M{}, GetLimit(c.Request), 1, "linenumber", &l)

	if err != nil {
		c.JSON(500, gin.H{"error": "500", "message": err.Error()})
	} else {
		done := make(chan bool)
		go func() {
			self.setLinks(l)
			self.setStatus(l)
			done <- true
		}()
		<-done

		data := gin.H{
			"lines": l,
			"paging": pagination(
				"v1/sp/metro/lines",
				self.DB,
				GetLimit(c.Request),
				1,
				models.Line{},
				bson.M{},
			),
		}

		render := &DataRender{c.Request, data}
		c.Render(200, render)
	}
}