Beispiel #1
1
// Update inserts a new friendship in database
func Update(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	friendID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		return msg.BadRequest(err)
	}

	// Bind body request to friend
	var friend models.FriendUpdate
	err = c.Bind(&friend)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Validate input
	err = validator.Validate(friend)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Insert into database
	err = mangos.Update(constants.CFriends, bson.M{"friend_id": int64(friendID), "digits_id": digitsID}, friend)
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok(friend)
}
Beispiel #2
0
// deleteBot получает команду от веб-клиента (удалить бота) и перенаправляет ее менеджеру ботов
func deleteBot(c *echo.Context) error {
	id := c.Param("id")
	action := "delete"
	MB.SendActionToBot(id, action, nil)

	return c.String(http.StatusOK, "ok\n")
}
Beispiel #3
0
func RemoveTodo(c echo.Context) error {
	id := c.Param("id")

	tododao.DeleteTodo(id)

	return c.String(http.StatusOK, "")
}
Beispiel #4
0
func getPunchesHandler(c echo.Context) error {
	id, err := strconv.ParseInt(c.Param("userID"), 10, 64)
	if err != nil {
		return err
	}
	return nil
}
Beispiel #5
0
func (s *Server) handleGetTransferResultsByIP(c echo.Context) error {
	ip := net.ParseIP(c.Param("IP"))

	res := s.registry.TransferResultsByIP(ip)

	return c.JSON(200, res)
}
Beispiel #6
0
func postDevicePairing(c *echo.Context) error {
	groupID := c.Get("GroupID").(string)
	deviceID := c.Param("device-id")
	_, _ = groupID, deviceID
	var pairingKey struct {
		Key string
	}
	err := c.Bind(&pairingKey) // читаем ключ из запроса
	if err != nil || len(pairingKey.Key) < 4 {
		return echo.NewHTTPError(http.StatusBadRequest)
	}
	var deviceIDResp string
	err = nce.Request(serviceNamePairingKey, pairingKey.Key, &deviceIDResp, natsRequestTimeout)
	if err != nil {
		llog.Error("NATS Pairing Key response error: %v", err)
		return err
	}
	if deviceIDResp == "" {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	if deviceIDResp == deviceID {
		// TODO: реально связать в базе
		return echo.NewHTTPError(http.StatusOK)
	}
	if deviceID == "" {
		return c.JSON(http.StatusOK, map[string]string{"ID": deviceIDResp})
	}
	return echo.NewHTTPError(http.StatusBadRequest)
}
Beispiel #7
0
func (r *EnvironmentResource) Update(c echo.Context) error {
	name := c.Param("name")

	environment, err := r.store.GetEnvironmentByName(name)
	if err != nil {
		if err == store.ErrNoRows {
			return NotFound(c)
		}

		return InternalServerError(c, err)
	}

	input := struct {
		Name string `json:"name"`
	}{}

	if err := c.Bind(&input); err != nil {
		return BadRequest(c, "Payload must be a valid JSON object")
	}

	if input.Name != "" {
		environment.Name = input.Name
	}

	if err := r.store.UpdateEnvironment(environment); err != nil {
		return InternalServerError(c, err)
	}

	return OK(c, environment)
}
Beispiel #8
0
// Delete deletes the resume.
//
//		Method           POST
//
//		Route            /resume/delete/:id
//
//		Restrictions     Yes
//
// 		Template         None
func Delete(ctx *echo.Context) error {
	var flashMessages = flash.New()
	id, err := utils.GetInt(ctx.Param("id"))
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.BadRequestMessage)
		return ctx.Render(http.StatusBadRequest, tmpl.ErrBadRequest, utils.GetData(ctx))
	}
	user := ctx.Get("User").(*models.Person)

	resume, err := query.GetResumeByID(id)
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.NotFoundMessage)
		return ctx.Render(http.StatusNotFound, tmpl.ErrNotFoundTpl, tmpl.NotFoundMessage)
	}

	// Users are allowed to delete resumes that they don't own.
	if resume.PersonID != user.ID {
		utils.SetData(ctx, "Message", tmpl.BadRequestMessage)
		return ctx.Render(http.StatusBadRequest, tmpl.ErrBadRequest, utils.GetData(ctx))
	}

	err = query.Delete(resume)
	if err != nil {
		utils.SetData(ctx, "Message", tmpl.ServerErrorMessage)
		return ctx.Render(http.StatusInternalServerError, tmpl.ErrServerTpl, utils.GetData(ctx))
	}

	flashMessages.Success("resume successful deleted")
	flashMessages.Save(ctx)
	ctx.Redirect(http.StatusFound, "/resume/")
	return nil
}
Beispiel #9
0
// DelAdmin removes a member from an existing group
func DelAdmin(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Get group id and convert from string to objectId
	rawMID := c.Param("mid")
	if !bson.IsObjectIdHex(rawMID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	memberID := bson.ObjectIdHex(rawMID)

	// Get group id and convert from string to objectId
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	groupID := bson.ObjectIdHex(rawGID)
	err := mangos.Update(constants.CGroups, bson.M{
		"$and": []bson.M{
			bson.M{"_id": groupID},
			bson.M{"admins": digitsID},
		},
	}, bson.M{"$pull": bson.M{"admins": memberID}})
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok("deleted admin")
}
Beispiel #10
0
// Make an application unusable
func UnpublishApplication(c *echo.Context) error {
	appId := c.Param("app_id")
	if len(appId) < 1 {
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "App id must be specified",
				},
			},
		})
	}

	err := apps.UnpublishApp(appId)
	if err == apps.UnpublishFailed {
		return c.JSON(http.StatusInternalServerError, hash{
			"error": [1]hash{
				hash{
					"detail": err.Error(),
				},
			},
		})
	}

	return c.JSON(http.StatusOK, hash{
		"data": hash{
			"success": true,
		},
	})
}
Beispiel #11
0
// Update patches a group in database
func Update(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Bind request body to a group update
	var group models.GroupUpdate
	err := c.Bind(&group)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Get group id and convert from string to objectId
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// Update the object, only if its a admin
	groupID := bson.ObjectIdHex(rawGID)
	err = mangos.Update(constants.CGroups, bson.M{
		"$and": []bson.M{
			bson.M{"_id": groupID},
			bson.M{"admins": digitsID},
		},
	}, bson.M{"$set": group})
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok(group)
}
Beispiel #12
0
func (app *App) putValues(ctx *echo.Context) (err error) {
	key := ctx.Param("key")
	value, err := readBody(ctx.Request())
	if err != nil {
		return err
	}

	app.Lock()
	entry, ok := app.store[key]
	if !ok {
		entry = newEntry()
		entry.Lock()
		app.store[key] = entry
	} else {
		entry.Lock()
	}
	app.Unlock()

	entry.value = value
	entry.lockID = generateID(32)
	app.cond.Broadcast()
	entry.Unlock()

	response := map[string]interface{}{}
	response["lock_id"] = entry.lockID
	ctx.JSON(200, response)
	return
}
Beispiel #13
0
func getGroupHandler(ctx *echo.Context) error {
	g, err := getGroup(dbFromContext(ctx), ctx.Param("id"))
	if err != nil {
		return err
	}
	return ctx.JSON(200, g)
}
Beispiel #14
0
// Make an application unusable
func UnpublishApplication(c *echo.Context) error {
	user := c.Get("user").(*users.User)

	appId := c.Param("app_id")
	if len(appId) < 1 {
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "App id must be specified",
				},
			},
		})
	}

	err := apps.UnpublishApp(user, appId)
	if err == apps.UnpublishFailed {
		return c.JSON(http.StatusInternalServerError, hash{
			"error": [1]hash{
				hash{
					"detail": err.Error(),
				},
			},
		})
	}

	return c.JSON(http.StatusOK, hash{
		"meta": hash{},
	})
}
Beispiel #15
0
/**
 * @api {put} /topics/{id} Updates a topic
 * @apiName UpdateTopic
 * @apiGroup Topics
 *
 * @apiParam {Number} id The id of the topic to update
 * @apiParam {String} [name] The new name of the topic
 */
func (tc *TopicsController) Update(c *echo.Context) error {
	resp := response.New(c)
	defer resp.Render()

	// Getting params
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		resp.SetResponse(http.StatusBadRequest, nil)
		return nil
	}

	// Loading the topic
	topic := new(models.Topic)
	err = topic.Load(id)
	if err != nil {
		resp.SetResponse(http.StatusNotFound, nil)
		return nil
	}

	name := c.Form("name")
	if name != "" {
		topic.Name = name
	}

	err = topic.Update()
	if err != nil {
		resp.SetResponse(http.StatusInternalServerError, nil)
		return nil
	}

	resp.SetResponse(http.StatusOK, topic)
	return nil
}
Beispiel #16
0
func httpTimeline(c *echo.Context) error {
	r := c.Request()
	w := c.Response()
	e := c.Get("engine").(storage.Engine)

	domain := c.Param("domain")

	iter, code, err := domainIteratorResource(domain, r, e)

	if err != nil {
		return c.JSON(code, map[string]interface{}{
			"error": fmt.Sprint(err),
		})
	}

	events, err := view.Timeline(iter, view.Descending)

	if err != nil {
		return c.JSON(code, map[string]interface{}{
			"error": fmt.Sprint(err),
		})
	}

	return json.NewEncoder(w).Encode(events)
}
Beispiel #17
0
func saveSite(c *echo.Context) error {
	id, iderr := strconv.Atoi(c.Param("id"))
	if iderr != nil {
		return c.String(http.StatusNotAcceptable, "Invalid ID")
	}

	site := new(SiteType)
	if binderr := c.Bind(site); binderr != nil {
		log.Println(binderr.Error())
		return binderr
	}
	log.Println(site)

	_, err := ExecDb(db,
		`update site
			set name=$2,
			    address=$3,
			    phone=$4,
			    contactname=$5
			where id=$1`,
		id,
		site.Name,
		site.Address,
		site.Phone,
		site.ContactName)

	if err != nil {
		log.Println(err.Error())
	}

	return c.JSON(http.StatusOK, site)
}
Beispiel #18
0
func GetUser(c *echo.Context) error {
	userId := c.Param("id")
	if userId == "" {
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "User id needed to retrieve account informations",
				},
			},
		})
	}

	user, err := users.GetUser(userId)
	if err != nil {
		return err
	}

	if user == nil {
		return c.JSON(http.StatusNotFound, hash{
			"error": [1]hash{
				hash{
					"detail": "User Not Found",
				},
			},
		})
	}

	return c.JSON(http.StatusOK, hash{
		"data": hash{
			"id":         user.Id,
			"type":       "user",
			"attributes": user,
		},
	})
}
Beispiel #19
0
func (as ApiService) deleteService(c echo.Context) error {
	if err := as.balancer.DeleteService(c.Param("service_name")); err != nil {
		return err
	}

	return c.NoContent(http.StatusNoContent)
}
Beispiel #20
0
// 消息列表
func (MessageController) ReadList(ctx echo.Context) error {
	user := ctx.Get("user").(*model.Me)
	msgtype := ctx.Param("msgtype")
	if msgtype == "" {
		msgtype = "system"
	}

	curPage := goutils.MustInt(ctx.QueryParam("p"), 1)
	paginator := logic.NewPaginator(curPage)

	var (
		messages []map[string]interface{}
		total    int64
	)
	switch msgtype {
	case "system":
		messages = logic.DefaultMessage.FindSysMsgsByUid(ctx, user.Uid, paginator)
		total = logic.DefaultMessage.SysMsgCount(ctx, user.Uid)
	case "inbox":
		messages = logic.DefaultMessage.FindToMsgsByUid(ctx, user.Uid, paginator)
		total = logic.DefaultMessage.ToMsgCount(ctx, user.Uid)
	case "outbox":
		messages = logic.DefaultMessage.FindFromMsgsByUid(ctx, user.Uid, paginator)
		total = logic.DefaultMessage.FromMsgCount(ctx, user.Uid)
	default:
		return ctx.Redirect(http.StatusSeeOther, "/")
	}

	pageHtml := paginator.SetTotal(total).GetPageHtml(fmt.Sprintf("/message/%s", msgtype))

	return render(ctx, "messages/list.html", map[string]interface{}{"messages": messages, "msgtype": msgtype, "page": template.HTML(pageHtml)})
}
Beispiel #21
0
func StartVM(c *echo.Context) error {
	name := c.Param("id")

	if name == "" {
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "No VM name provided",
				},
			},
		})
	}

	err := Start(name)
	if err != nil {
		log.Error("Error while starting VM")
		return c.JSON(http.StatusInternalServerError, hash{
			"error": [1]hash{
				hash{
					"detail": err.Error(),
				},
			},
		})
	}

	return c.JSON(http.StatusOK, hash{
		"success": true,
	})
}
Beispiel #22
0
func StopVM(c *echo.Context) error {
	name := c.Param("id")

	if name == "" {
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "No VM name provided",
				},
			},
		})
	}

	err := Stop(name)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, hash{
			"error": [1]hash{
				hash{
					"detail": "Unable to stop the specified VM",
				},
			},
		})
	}

	return c.JSON(http.StatusOK, hash{
		"success": true,
	})
}
Beispiel #23
0
// Retrieve writes the requested group from database
func Retrieve(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Get group id and convert it from string to objectid
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	groupID := bson.ObjectIdHex(rawGID)
	var group models.Group
	err := mangos.FindOne(constants.CGroups, bson.M{"_id": groupID}, &group)
	if err != nil {
		return msg.InternalError(err)
	}

	// check if user is member (is not part of the query because we need to light bson query)
	for _, member := range group.Members {
		if member == digitsID {
			return msg.Ok(group)
		}
	}

	return msg.Forbidden("you must be part of the group")
}
Beispiel #24
0
func saveEquipType(c *echo.Context) error {
	id, iderr := strconv.Atoi(c.Param("id"))
	if iderr != nil {
		return c.String(http.StatusNotAcceptable, "Invalid ID")
	}

	et := new(EquipType)
	if binderr := c.Bind(et); binderr != nil {
		log.Println(binderr.Error())
		return binderr
	}
	//log.Println(et)

	_, err := ExecDb(db,
		`update equip_type
			set name=$2,
			    is_consumable=$3,
			    is_asset=$4
			where id=$1`,
		id,
		et.Name,
		et.Consumable,
		et.Asset)

	if err != nil {
		log.Println(err.Error())
	}

	return c.JSON(http.StatusOK, et)
}
Beispiel #25
0
// ArchiveView shows a list of posts arranged by its date
func ArchiveView(c *echo.Context) error {
	id := c.Param("id")
	var err error

	// Get archive data
	var archive models.Archive
	err = database.Current.Get(&archive, database.Queries.ArchiveBySignature, id)
	if err != nil {
		log.Println("Cannot get archive by signature", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Get related posts
	var posts []models.AuthoredPost
	err = database.Current.Select(&posts, database.Queries.ArchiveAuthoredPosts, id)
	if err != nil {
		log.Println("Cannot select posts", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Create our render context and fill base data
	ac := archiveContext{
		Archive:      archive,
		RelatedPosts: posts,
	}

	err = fillBlogContext(c, &ac.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	return c.Render(200, "archive", ac)
}
Beispiel #26
0
// Retrieve writes profile public information, if requested id is the same as the
// session, then full data is written.
func Retrieve(c *echo.Context) (int, interface{}) {
	reqid, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	attid, _ := c.Get("digitsID").(int64)

	if reqid == attid {
		// Serve private profile
		var profile models.Profile

		log.Printf("Awaiting for [Profile = %d] fetch", reqid)
		err := mangos.FindOne(collection, bson.M{"_id": reqid}, &profile)
		if err != nil {
			log.Printf("Cannot retrieve [Profile = %d]: %s", reqid, err)
			return msg.InternalError(err)
		}

		log.Printf("Served profile ->\n%s", msg.Detail(profile))
		return msg.Ok(profile)
	}

	// Serve public profile
	var public models.PublicProfile
	log.Printf("Awaiting for [PublicProfile = %d] fetch", reqid)
	err := mangos.FindOne(collection, bson.M{"_id": reqid}, &public)
	if err != nil {
		log.Printf("Cannot retrieve [PublicProfile = %d]: %s", reqid, err)
		return msg.InternalError(err)
	}

	log.Printf("Served PublicProfile ->\n%s", msg.Detail(public))
	return msg.Ok(public)
}
Beispiel #27
0
func GetUser(c *echo.Context) error {
	userId := c.Param("id")
	if userId == "" {
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "User id needed to retrieve account informations",
				},
			},
		})
	}

	user, err := users.GetUser(userId)
	if err != nil {
		return err
	}

	if user == nil {
		return c.JSON(http.StatusNotFound, hash{
			"error": [1]hash{
				hash{
					"detail": "User Not Found",
				},
			},
		})
	}

	return utils.JSON(c, http.StatusOK, user)
}
Beispiel #28
0
func putHandler(c echo.Context) error {
	var val map[string]interface{}

	if err := c.Bind(&val); err != nil {
		return err
	}

	cfg := c.Get("config").(*Config)

	key := c.Param("key")
	obj, err := Put(cfg, key, val)

	if err != nil {
		// Failed validation.
		if errs, ok := err.(ResultErrors); ok {
			return c.JSON(StatusUnprocessableEntity, errs)
		}

		return err
	}

	// No change.
	if obj == nil {
		return c.NoContent(http.StatusNoContent)
	}

	return c.JSON(http.StatusOK, obj)
}
Beispiel #29
0
func httpLog(c *echo.Context) error {
	r := c.Request()
	w := c.Response()
	e := c.Get("engine").(storage.Engine)

	domain := c.Param("domain")

	iter, code, err := domainIteratorResource(domain, r, e)

	if err != nil {
		return c.JSON(code, map[string]interface{}{
			"error": fmt.Sprint(err),
		})
	}

	facts, err := origins.ReadAll(iter)

	if err != nil {
		return c.JSON(code, map[string]interface{}{
			"error": fmt.Sprint(err),
		})
	}

	return json.NewEncoder(w).Encode(facts)
}
// path /update/account/:DeviceID/:ID?field1=value1&&field2=value2
// example /update/account/device10/12?Weight=17.3&&Height=20.69&&BodyFat=100.44
func setAccount(c *echo.Context, isInsert bool) error {
	deviceid := c.Param("DeviceID")
	id, err := strconv.ParseUint(c.Param("ID"), 10, 64)
	if err != nil {
		return jsonResp(c, err.Error())
	}

	acc := Account{DeviceID: deviceid, ID: id}
	has, err := g_engine.Get(&acc)
	if err != nil {
		return jsonResp(c, err.Error())
	}
	if isInsert && has {
		return jsonResp(c, "exists")
	}

	if !isInsert && !has {
		return jsonResp(c, "not exists")
	}

	for _, field := range []string{"Weight", "Height", "BodyFat"} {
		switch field {
		case "Weight":
			tmp, err := strconv.ParseFloat(c.Query(field), 32)
			acc.Weight = JSONFloat64(tmp)
			if err != nil {
				return jsonResp(c, err.Error())
			}
		case "Height":
			tmp, err := strconv.ParseFloat(c.Query(field), 32)
			acc.Height = JSONFloat64(tmp)
			if err != nil {
				return jsonResp(c, err.Error())
			}
		case "BodyFat":
			tmp, err := strconv.ParseFloat(c.Query(field), 32)
			acc.BodyFat = JSONFloat64(tmp)
			if err != nil {
				return jsonResp(c, err.Error())
			}
		}
	}

	if isInsert {
		_, err = g_engine.Insert(&acc)
	} else {
		_, err = g_engine.Update(&acc)
	}

	if err != nil {
		return jsonResp(c, err.Error())
	}

	if err = updateOrInsert(&SyncTime{DeviceID: deviceid}); err != nil {
		return jsonResp(c, err.Error())
	}

	return jsonResp(c, "success")
}