Esempio n. 1
0
func AdminGetModels(params martini.Params, r render.Render) {
	var itemList []string
	for k, _ := range models {
		itemList = append(itemList, k)
	}
	r.JSON(200, map[string]interface{}{"models": itemList})
}
Esempio n. 2
0
func MediaCreate(db gorm.DB, r render.Render, media models.Media) {
	if err := db.Save(&media).Error; err != nil {
		r.JSON(http.StatusConflict, map[string]interface{}{"error": "Media conflict"})
		return
	}
	r.JSON(http.StatusCreated, media)
}
func ReadListQnA(req *http.Request, r render.Render, db *mgo.Database) {
	appid := req.Header.Get("Application-Id")
	if appid == "" {
		r.JSON(handlers.HttpErr(http.StatusNotFound, "insert to Application-Id"))
		return
	}
	////
	colQuerier := bson.M{}
	change := bson.M{"$set": bson.M{"reception": true}}
	CollectionName := handlers.CollectionNameQnA(appid)
	if _, err := db.C(CollectionName).UpdateAll(colQuerier, change); err != nil {
		r.JSON(handlers.HttpErr(http.StatusNotFound, err.Error()))
		return
	}
	var qnas []QnA
	if err := db.C(CollectionName).Find(bson.M{}).Sort("-time").All(&qnas); err != nil {
		r.JSON(handlers.HttpErr(http.StatusNotFound, err.Error()))
		return
	}

	if qnas == nil {
		r.JSON(http.StatusOK, map[string]interface{}{"return": bson.D{}})
		return
	}

	r.JSON(http.StatusOK, map[string]interface{}{"return": qnas})
}
func ListBuckets(r render.Render, db database.Database) {
	if buckets, err := db.ListBuckets(); err != nil {
		JsonErrorf(r, http.StatusBadRequest, err.Error())
	} else {
		r.JSON(http.StatusOK, buckets)
	}
}
Esempio n. 5
0
//Get /users/:user_id/relationships
func (u *UserHandler) GetAllRelations(request *http.Request, rd render.Render, params martini.Params) {
	// 获取 url 参数
	userid, err := strconv.ParseInt(params["user_id"], 10, 64)
	if err != nil {
		rd.Text(400, "The request cannot be fulfilled due to bad syntax.")
		return
	}

	//验证 user 是否存在
	_, err = u.userService.GetUser(userid)
	if err != nil {
		if err == pg.ErrNoRows {
			rd.Text(400, fmt.Sprintln("user", userid, "not exist"))
		} else {
			rd.Text(500, err.Error())
		}
		return
	}

	rs, err := u.userService.GetUserRelations(userid)
	if err != nil {
		rd.Text(500, err.Error())
		return
	}

	relations := make([]interface{}, 0, 0)
	for _, r := range rs {
		relations = append(relations, fmtRelationShip(r))
	}

	rd.JSON(200, relations)
}
Esempio n. 6
0
File: server.go Progetto: jartek/meh
func CollectionResponse(r render.Render, collection []interface{}, err error) {
	if err != nil {
		r.JSON(404, nil)
	} else {
		r.JSON(200, collection)
	}
}
Esempio n. 7
0
func createUser(r render.Render, re *http.Request, f *fishhub.DBService, userForm user.UserForm) {
	userExistError := binding.Error{
		Message:        "is already taken",
		FieldNames:     []string{"email"},
		Classification: "UserExistError",
	}
	errors := binding.Errors{userExistError}
	if userExist(f, userForm.UserId) {
		r.JSON(400, errors)
		return
	}

	d := f.DB.Copy()
	defer d.Close()

	query := bson.M{"userid": userForm.UserId}
	update := bson.M{"$set": userForm}
	updated, _ := d.Upsert("users", query, nil, update, true)

	if updated == true {
		r.JSON(200, map[string]interface{}{
			"message": "User profile is successfully created.",
		})
		return
	}

	displayUnknownError(r)
}
Esempio n. 8
0
File: vote.go Progetto: firba1/irq
func Vote(db model.Model, req *http.Request, r render.Render, params martini.Params) {
	id, err := strconv.Atoi(params["id"])
	if err != nil {
		r.JSON(404, ErrorEnv{"invalid quote id"})
		return
	}

	count, err := strconv.Atoi(req.FormValue("count"))
	if err != nil {
		r.JSON(404, ErrorEnv{"invalid vote count"})
		return
	}

	err = db.VoteQuote(id, count)
	if err != nil {
		r.JSON(500, ErrorEnv{"unable to vote quote"})
		return
	}

	quote, err := db.GetQuote(id)
	if err != nil {
		r.JSON(404, ErrorEnv{"quote not found"})
		return
	}

	env := struct {
		Score int `json:"score"`
	}{quote.Score}
	r.JSON(200, env)
}
Esempio n. 9
0
func Index(r render.Render) {
	type homeStats struct {
		RepoCount  int
		IssueCount int
		UserCount  int
		IssueLangs []string
	}

	stats := homeStats{}

	c.DB.Model(c.Repository{}).Count(&stats.RepoCount)
	c.DB.Model(c.Issue{}).Count(&stats.IssueCount)
	c.DB.Model(c.User{}).Count(&stats.UserCount)

	rows := c.DB.Raw(`select distinct language
		from issues
		inner join repositories on repositories.id = issues.repository_id
		where language != ''
		order by language
	`)

	rows.Pluck("language", &stats.IssueLangs)

	r.JSON(200, stats)
}
Esempio n. 10
0
File: random.go Progetto: firba1/irq
func Random(db model.Model, r render.Render, req *http.Request, isJson IsJson) {
	qs := req.URL.Query()

	search := qs.Get("query")

	maxLines, err := strconv.Atoi(qs.Get("max-lines"))
	if err != nil || maxLines < 1 {
		maxLines = 0
	}

	quotes, err := db.GetQuotes(model.Query{
		Limit:       1,
		Search:      search,
		MaxLines:    maxLines,
		OrderBy:     []string{"rand()"},
		IncludeTags: qs["tags"],
		ExcludeTags: qs["exclude-tags"],
	})

	if err != nil || len(quotes) == 0 {
		RenderError(r, 500, isJson, fmt.Sprint("quote not found", err))
		return
	}

	quote := quotes[0]

	if isJson {
		r.JSON(200, quote)
	} else {
		r.Redirect(fmt.Sprintf("/quote/%d", quote.ID))
	}
}
func LoginHandler(r render.Render, user model.User, appx *appx.Datastore) {
	response := model.Response{
		ErrorCode: http.StatusOK,
		Message:   []string{},
		Data:      nil,
	}

	isValid, validationErr := user.IsValid()

	if !isValid {
		response.ErrorCode = http.StatusBadRequest
		response.Message = validationErr
	} else {
		err := appx.Save(&user)

		if err != nil {
			log.Printf("Error: %v", err)
			response.ErrorCode = http.StatusInternalServerError
			response.Message = append(response.Message, err.Error())
		} else {
			response.Data = user
		}
	}

	r.JSON(200, response)

}
Esempio n. 12
0
func PostIdeaHandler(req *http.Request, render render.Render, log *log.Logger) {
	log.Println("Receive post data.")
	name := req.FormValue("name")
	email := req.FormValue("email")
	link := req.FormValue("link")
	content := req.FormValue("content")
	log.Println("Name: " + name)
	log.Println("Email: " + email)
	log.Println("Link: " + link)
	log.Println("Content: " + content)
	if len(name) == 0 {
		render.JSON(400, map[string]interface{}{"error": 1, "message": "Empty name."})
		return
	}
	if len(email) == 0 {
		render.JSON(400, map[string]interface{}{"error": 2, "message": "Empty email."})
		return
	}
	if len(content) == 0 {
		render.JSON(400, map[string]interface{}{"error": 3, "message": "Empty content."})
		return
	}
	AddIdea(name, email, link, content)
	render.JSON(200, map[string]interface{}{"error": 0})
}
Esempio n. 13
0
func (this *EurekaRequestGet) request(data interface{}, r render.Render, req *http.Request) {
	if req.URL.Query().Get("json") != "" {
		r.JSON(200, data)
	} else {
		r.XML(200, data)
	}
}
Esempio n. 14
0
func ListBuckets(ctx context.Context, r render.Render, db database.Database) {
	if buckets, err := db.ListBuckets(); err != nil {
		LogAndRespondWithError(ctx, r, http.StatusBadRequest, err)
	} else {
		r.JSON(http.StatusOK, buckets)
	}
}
/**
更新
**/
func UpdateQuestion(r render.Render, req *http.Request) {
	c := appengine.NewContext(req)
	id, _ := strconv.Atoi(req.FormValue("Key"))
	key := datastore.NewKey(c, "Question", "", int64(id), nil)
	var question Question
	if err := datastore.Get(c, key, &question); err != nil {
		c.Criticalf(err.Error())
	}
	question.Content = req.FormValue("Content")
	question.LargeCategoryKey = req.FormValue("LargeCategoryKey")
	question.MediumCategoryKey = req.FormValue("MediumCategoryKey")
	question.SmallCategoryKey = req.FormValue("SmallCategoryKey")
	question.Rubric = req.FormValue("Rubric")
	question.Percentage, _ = strconv.ParseFloat(req.FormValue("Percentage"), 64)
	question.Status = req.FormValue("Status")
	question.Level = req.FormValue("Level")
	question.UserKey = req.FormValue("UserKey")
	_, err := datastore.Put(c, key, &question)
	if err != nil {
		c.Criticalf("%s", err)
		r.JSON(400, err)
	} else {
		r.JSON(200, question)
	}
}
Esempio n. 16
0
// A simple status endpoint to ping to see if the agent is up and responding.  There's not much
// to do here except respond with 200 and OK
// This is pointed to by a configurable endpoint and has a configurable status message
func (this *HttpAPI) Status(params martini.Params, r render.Render, req *http.Request) {
	if uint(time.Since(agent.LastTalkback).Seconds()) > config.Config.StatusBadSeconds {
		r.JSON(500, "BAD")
	} else {
		r.JSON(200, "OK")
	}
}
Esempio n. 17
0
func GroupCreate(db gorm.DB, r render.Render, group models.Group) {
	if err := db.Save(&group).Error; err != nil {
		r.JSON(http.StatusConflict, map[string]interface{}{"error": "Group conflict"})
		return
	}
	r.JSON(http.StatusCreated, group)
}
Esempio n. 18
0
func UserGet(ren render.Render, params martini.Params, dbmap *gorp.DbMap, s sessions.Session) {
	var usr User
	log.Println(params)
	err := dbmap.SelectOne(&usr, "SELECT * from users WHERE id = $1", s.Get("userId"))
	PanicIf(err)
	ren.JSON(200, usr)
}
Esempio n. 19
0
File: server.go Progetto: jartek/meh
func IndividualResponse(r render.Render, collection interface{}, err error) {
	if err != nil {
		r.JSON(404, nil)
	} else {
		r.JSON(200, collection)
	}
}
Esempio n. 20
0
// POST /api/users
func (mgr *Manager) AddUser(w http.ResponseWriter, r *http.Request, rnd render.Render) {
	req := make(map[string]string)
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil || len(req["name"]) < 3 || len(req["password"]) < 3 {
		w.WriteHeader(400)
		return
	}
	passwd, err := bcrypt.GenerateFromPassword([]byte(req["password"]), 11)
	if err != nil {
		log.Error("bcrypt.GenerateFromPassword: "******"insert into users (name, password) values(?,?)", req["name"], passwd)
	if err == nil {
		id, err = result.LastInsertId()
	}
	if err != nil {
		mgr.showError(err, w)
		return
	}
	rnd.JSON(200, map[string]interface{}{"name": req["name"], "id": id})
}
Esempio n. 21
0
func updateUser(r render.Render, params martini.Params, re *http.Request, f *fishhub.DBService, userForm user.UserUpdateForm) {
	d := f.DB.Copy()
	defer d.Close()
	query := bson.M{"_id": bson.ObjectIdHex(params["id"])}

	update := bson.M{
		"address":      userForm.Address,
		"contactno":    userForm.ContactNo,
		"country":      userForm.Country,
		"email":        userForm.Email,
		"locale":       userForm.Locale,
		"name":         userForm.Name,
		"notification": userForm.Notification,
		"role":         userForm.Role,
	}

	err := d.Update("users", query, bson.M{"$set": update})

	if err != nil {
		displayUnknownError(r)
		return
	}

	r.JSON(200, userForm)
}
Esempio n. 22
0
func GetEvent(r render.Render, db DB, params martini.Params) {
	key, ok := strconv.Atoi(params["id"])
	if ok != nil {
		fmt.Println(key)
	}
	r.JSON(200, db.Get(key))
}
Esempio n. 23
0
func (ac *AuthController) Login(user models.User, r render.Render) {
	getuser := models.User{}
	session := ac.session.DB(os.Getenv("DB_NAME")).C("users")
	err := session.Find(bson.M{"email": user.Email}).One(&getuser)
	if err != nil {
		panic(err)
	}

	err = bcrypt.CompareHashAndPassword([]byte(getuser.Password), []byte(user.Password))

	if err != nil {
		panic(err)
	}

	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["user_id"] = getuser.Id
	token.Claims["email"] = getuser.Email
	token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix()
	tokenString, err := token.SignedString([]byte(SecretKey))
	if err != nil {
		r.JSON(500, map[string]interface{}{"_error": "500: Signing Error."})
		return
	}

	data := map[string]string{
		"token": tokenString,
	}

	r.JSON(200, data)
}
Esempio n. 24
0
func ShowError(rend render.Render) {
	if master.Error {
		rend.JSON(200, helper.Success(master.ErrorLog))
	} else {
		rend.JSON(200, helper.Error())
	}
}
Esempio n. 25
0
func genericResponseFormatter(r render.Render, apikey string, payload map[string]interface{}, extErr error) {
	var (
		statusCode int
		err        error
		res        Response
	)

	if extErr != nil {
		statusCode = FailureStatus
		res = Response{
			ErrorMsg: extErr.Error(),
		}

	} else {

		if _, err = json.Marshal(payload); err != nil {
			statusCode = FailureStatus
			res = Response{
				ErrorMsg: err.Error(),
			}

		} else {
			statusCode = SuccessStatus
			res = Response{
				APIKey:  apikey,
				Payload: payload,
			}
		}
	}
	r.JSON(statusCode, res)
}
Esempio n. 26
0
func createNote(rend render.Render, req *http.Request, params martini.Params, dbh *db.DBHandle) {
	err := req.ParseForm()
	if err != nil {
		rend.JSON(http.StatusBadRequest, err.Error())
		return
	}
	u := unmarshalNoteJSON{}
	err = json.NewDecoder(req.Body).Decode(&u)
	if err != nil {
		rend.JSON(http.StatusBadRequest, err.Error())
		return
	}

	p := db.Person{Id: u.PersonId}
	err = dbh.ORM.Read(&p)
	if err != nil {
		rend.JSON(http.StatusInternalServerError, fmt.Sprintf("Unknown Person ID: %d", u.PersonId))
		return
	}

	dbnote := db.Note{
		Text:     u.Text,
		Category: u.Category,
		Date:     u.Date,
		Person:   &p,
	}
	err = dbh.CreateNote(&dbnote)
	if err != nil {
		rend.JSON(http.StatusInternalServerError, err.Error())
		return
	}
	rend.JSON(200, noteWithPersonIdJSON{&dbnote, p.Id})
}
Esempio n. 27
0
func Verify(res http.ResponseWriter, req *http.Request, r render.Render, dbh *db.Dbh) {
	pk := req.FormValue("user_private_key")
	a := req.FormValue("file_album")

	album := dbh.GetAlbum(a)

	if album.Id > 0 && album.Privatekey == pk {
		return
	}

	if pk == "" || pk != utils.ImageCfg.SecretKey() {
		log.Printf("Upload failed: Invalid Private Key (%s)\n", pk)
		r.JSON(http.StatusUnauthorized, Response{"error": http.StatusUnauthorized, "code": "Invalid Private Key", "name": a})
		return
	}

	if a == "" {
		log.Printf("Upload failed: Invalid Album Name (%s)\n", a)
		r.JSON(http.StatusUnauthorized, Response{"error": http.StatusUnauthorized, "code": "Invalid Album Name", "name": a})
		return
	}

	log.Println("verify: good")
	return
}
Esempio n. 28
0
func DeleteItem(r render.Render, params martini.Params, c *redis.Client) {
	err := c.HDel("godo:items", params["id"]).Err()
	if err != nil {
		panic(err)
	}
	r.JSON(http.StatusOK, nil)
}
Esempio n. 29
0
// Index returns people
func Index(render render.Render, r doorbot.Repositories, session *auth.Authorization) {
	repo := r.PersonRepository()

	people, err := repo.All(r.DB())

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
		}).Error("Api::People->Index database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	switch session.Type {
	case auth.AuthorizationAdministrator:
		render.JSON(http.StatusOK, PeopleViewModel{People: people})
	case auth.AuthorizationDevice:
		render.JSON(http.StatusOK, PublicPeopleViewModel{People: newPublicPeople(people)})
	case auth.AuthorizationPerson:
		if session.Person.IsAccountManager() {
			render.JSON(http.StatusOK, PeopleViewModel{People: people})
			return
		}

		render.JSON(http.StatusOK, PublicPeopleViewModel{People: newPublicPeople(people)})
	}
}
func CreatePostHandler(r render.Render, post model.Post, appx *appx.Datastore, location middleware.RequestLocation) {

	response := model.Response{
		ErrorCode: http.StatusOK,
		Message:   []string{},
		Data:      nil,
	}

	post.CarPlate = strings.ToUpper(post.CarPlate)
	post.Country = location.Country
	post.CreatedAt = time.Now()

	isValid, validationErr := post.IsValid(location.Country)

	if !isValid {
		response.ErrorCode = http.StatusBadRequest
		response.Message = validationErr
	} else {
		err := appx.Save(&post)

		if err != nil {
			log.Printf("Error: %+v", err)
			response.ErrorCode = http.StatusInternalServerError
			response.Message = append(response.Message, err.Error())
		} else {
			postResource := &resources.PostResource{}
			postResource.From(post)
			response.Data = postResource
		}
	}

	r.JSON(200, response)
}