func (s *APIServer) getFeeds(c echo.Context) error { dbuser := c.Get("dbuser").(*db.User) b := new(feedsReqBinder) if err := c.Bind(b); err != nil { return newError(c, "Unable to parse request", err) } var feeds []*db.FeedInfo var err error if b.Name != "" { feeds, err = s.DBH.GetUsersFeedsByName(dbuser, b.Name) } else { feeds, err = s.DBH.GetUsersFeeds(dbuser) } if err != nil { return newError(c, "Unable to get feeds", err) } feedInterface := make([]interface{}, len(feeds)) for i, f := range feeds { feedInterface[i] = f } c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8) c.Response().WriteHeader(http.StatusOK) return jsonapi.MarshalManyPayload(c.Response(), feedInterface) }
func success(ctx echo.Context, data interface{}) error { result := map[string]interface{}{ "ok": 1, "msg": "操作成功", "data": data, } b, err := json.Marshal(result) if err != nil { return err } go func(b []byte) { if cacheKey := ctx.Get(nosql.CacheKey); cacheKey != nil { nosql.DefaultLRUCache.CompressAndAdd(cacheKey, b, nosql.NewCacheData()) } }(b) if ctx.Response().Committed() { getLogger(ctx).Flush() return nil } return ctx.JSONBlob(http.StatusOK, b) }
// 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 }
func UserList(ctx *echo.Context) error { interactor := ctx.Get("UserInteractor").(*usecases.UserInteractor) result := interactor.List() return ctx.JSON(http.StatusOK, result) }
// 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{}, }) }
// 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") }
// 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") }
// RenderAdmin html 输出 func RenderAdmin(ctx echo.Context, contentTpl string, data map[string]interface{}) error { if data == nil { data = map[string]interface{}{} } objLog := logic.GetLogger(ctx) contentTpl = AdminLayoutTpl + "," + contentTpl // 为了使用自定义的模板函数,首先New一个以第一个模板文件名为模板名。 // 这样,在ParseFiles时,新返回的*Template便还是原来的模板实例 htmlFiles := strings.Split(contentTpl, ",") for i, contentTpl := range htmlFiles { htmlFiles[i] = config.TemplateDir + "admin/" + contentTpl } requestURI := Request(ctx).RequestURI tpl, err := template.New("common.html").Funcs(funcMap).ParseFiles(htmlFiles...) if err != nil { objLog.Errorf("解析模板出错(ParseFiles):[%q] %s\n", requestURI, err) return err } // 当前用户信息 curUser := ctx.Get("user").(*model.Me) if menu1, menu2, curMenu1 := logic.DefaultAuthority.GetUserMenu(ctx, curUser, requestURI); menu2 != nil { data["menu1"] = menu1 data["menu2"] = menu2 data["uri"] = requestURI data["cur_menu1"] = curMenu1 } return executeTpl(ctx, tpl, data) }
func (app *App) userLogin(c *echo.Context) error { userData := c.Get("userInput").(userData) var response struct { Bearer string `json:"bearer,omitempty"` Timestamp int64 `json:"timestamp,omitempty"` Error string `json:"error,omitempty"` } // Handle credentials here // If everything is alright (pass is correct) // proceed further user, err := FindUserByUsername(app.DB, userData.Username) if err == nil { if err := bcrypt.CompareHashAndPassword( []byte(user.Password), []byte(userData.Password), ); err == nil { response.Bearer = user.GenSignedString(app.SigningKey) response.Timestamp = time.Now().Unix() // user is found and password is correct return c.JSON(http.StatusOK, response) } } response.Error = "Incorrect credentials" return c.JSON(http.StatusOK, response) }
// Index 首页 func (IndexController) Index(ctx echo.Context) error { num := 10 paginator := logic.NewPaginatorWithPerPage(1, num) topicsList := make([]map[string]interface{}, num) // 置顶的topic topTopics := logic.DefaultTopic.FindAll(ctx, paginator, "ctime DESC", "top=1") if len(topTopics) < num { // 获取最新帖子 paginator.SetPerPage(num - len(topTopics)) newTopics := logic.DefaultTopic.FindAll(ctx, paginator, "ctime DESC", "top=0") topicsList = append(topTopics, newTopics...) } // 获得最新博文 recentArticles := logic.DefaultArticle.FindBy(ctx, 10) // 获取当前用户喜欢对象信息 var likeFlags map[int]int if len(recentArticles) > 0 { curUser, ok := ctx.Get("user").(*model.Me) if ok { likeFlags, _ = logic.DefaultLike.FindUserLikeObjects(ctx, curUser.Uid, model.TypeArticle, recentArticles[0].Id, recentArticles[len(recentArticles)-1].Id) } } // Golang 资源 resources := logic.DefaultResource.FindBy(ctx, 10) return render(ctx, "index.html", map[string]interface{}{"topics": topicsList, "articles": recentArticles, "likeflags": likeFlags, "resources": resources}) }
// 消息列表 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)}) }
func ProjectGetAll(ctx *echo.Context) error { interactor := ctx.Get("ProjectInteractor").(*usecases.ProjectInteractor) result := interactor.List() return ctx.JSON(http.StatusOK, result) }
// Version return accept version from reuqest header func Version(c echo.Context) string { version := c.Get("Version") if version != nil { return version.(string) } return VersionV1 }
// putPlace изменяет определение уже существующего места. func putPlace(c *echo.Context) error { groupID := c.Get("GroupID").(string) placeID := c.Query("place-id") if !bson.IsObjectIdHex(placeID) { return echo.NewHTTPError(http.StatusNotFound) } var place places.Place // описание места err := c.Bind(&place) // разбираем описание места из запроса if err != nil { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } if place.Circle == nil && place.Polygon == nil { return echo.NewHTTPError(http.StatusBadRequest) } place.ID = bson.ObjectIdHex(placeID) place.GroupID = groupID _, err = placesDB.Save(place) if err == mgo.ErrNotFound { return echo.NewHTTPError(http.StatusNotFound) } if err != nil { llog.Error("placesDB error: %v", err) return err } return c.NoContent(http.StatusOK) }
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) }
func (h *handler) RemoveFromFavPostHandler(c *echo.Context) error { s := c.Get("session").(session.Session) if s.Get("username") == "" { return c.JSON(http.StatusForbidden, "") } user := c.Get("user").(model.UserRow) p, err := h.back.Model.Package.GetItem(c.Form("package")) if err != nil { log.Println(err) return c.JSON(http.StatusBadRequest, err.Error()) } var packages []bson.ObjectId for _, up := range user.Packages { if up != p.Id { packages = append(packages, up) } } user.Packages = packages _, err = h.back.Model.User.Upsert(&user) if err != nil { log.Println(err) return c.JSON(http.StatusBadRequest, err.Error()) } return c.JSON(http.StatusOK, nil) }
// 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) }
func EnvironmentGetAll(ctx *echo.Context) error { interactor := ctx.Get("EnvironmentInteractor").(*usecases.EnvironmentInteractor) result := interactor.List() return ctx.JSON(http.StatusOK, result) }
// Create inserts a new group into database func Create(c *echo.Context) (int, interface{}) { digitsID, ok := c.Get("digitsID").(int64) if !ok { return msg.Forbidden("session required") } // Bind request body with group var group models.Group err := c.Bind(&group) // Validate group err = validator.Validate(group) if err != nil { return msg.BadRequest(err) } // Set values group.ID = bson.NewObjectId() group.Admins = []int64{digitsID} group.Creator = digitsID group.Members = []int64{digitsID} // Create group err = mangos.Insert(constants.CGroups, group) if err != nil { return msg.InternalError(err) } return msg.Ok(group) }
func GetDownloadToken(c *echo.Context) error { filename := c.Query("filename") if len(filename) == 0 { return c.JSON( http.StatusBadRequest, hash{ "error": "filename not specified", }, ) } accessToken, fail := oauth2.GetAccessToken(c.Request()) if fail != nil { return oauthError(c, fail) } user := c.Get("user").(*users.User) token, err := createDownloadToken(user, accessToken, filename) if err != nil { return err } return c.JSON( http.StatusOK, hash{ "token": token, }, ) }
// JobsNewPost process the new job form. // // Method POST // // Route /dash/jobs/new // // Restrictions Yes // // Template None func JobsNewPost(ctx *echo.Context) error { var flashMessages = flash.New() f := forms.New(utils.GetLang(ctx)) jf := f.JobForm()(ctx.Request()) if !jf.IsValid() { // TODO: improve flash message ? flashMessages.Err(msgInvalidorm) flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/dash/jobs/new") return nil } if isLoged := ctx.Get("IsLoged"); isLoged != nil { person := ctx.Get("User").(*models.Person) if jerr := query.PersonCreateJob(person, jf.GetModel().(forms.JobForm)); jerr != nil { // TODO: improve flash message ? flashMessages.Err("some really bad fish happened") flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/dash/jobs/new") return nil } // add flash message flashMessages.Success("new job was created successful") flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/dash/") return nil } he := echo.NewHTTPError(http.StatusUnauthorized) ctx.Error(he) return nil }
func CreateAccount(c *echo.Context) error { logrus.Infof("create account") caRequest, err := validateCreateAccount(c.Request().Body) if err != nil { logrus.Errorf("failed create account input validation %s", err.Error()) c.JSON(400, Response{}) return nil } db := c.Get("db").(*mgo.Database) _, err = models.LoadAccount(db, caRequest.Username) if err == nil { logrus.Errorf("account taken: %s", caRequest.Username) c.JSON(409, Response{}) return nil } else if err != models.AccountNotFound && err != nil { logrus.Errorf("db error in create account: %s", err.Error()) c.JSON(500, Response{}) return nil } a := models.Account{ Username: caRequest.Username, Password: caRequest.Password, } err = models.CreateAccount(db, a) if err != nil { logrus.Errorf("failed to create account: %s", err.Error()) c.JSON(500, Response{}) return nil } c.JSON(200, Response{true, a}) return nil }
func List(c *echo.Context) error { user := c.Get("user").(*users.User) winUser, err := user.WindowsCredentials() if err != nil { return err } sessionList, err := sessions.GetAll(winUser.Sam) if err != nil { log.Error(err) return utils.JSON(c, http.StatusInternalServerError, hash{ "error": [1]hash{ hash{ "detail": err.Error(), }, }, }) } var response = make([]hash, len(sessionList)) for i, val := range sessionList { res := hash{ "id": val.Id, "type": "session", "attributes": val, } response[i] = res } return c.JSON(http.StatusOK, hash{"data": response}) }
// Detail 文章详细页 func (ArticleController) Detail(ctx echo.Context) error { article, prevNext, err := logic.DefaultArticle.FindByIdAndPreNext(ctx, goutils.MustInt(ctx.Param("id"))) if err != nil { return ctx.Redirect(http.StatusSeeOther, "/articles") } if article == nil || article.Id == 0 || article.Status == model.ArticleStatusOffline { return ctx.Redirect(http.StatusSeeOther, "/articles") } likeFlag := 0 hadCollect := 0 me, ok := ctx.Get("user").(*model.Me) if ok { likeFlag = logic.DefaultLike.HadLike(ctx, me.Uid, article.Id, model.TypeArticle) hadCollect = logic.DefaultFavorite.HadFavorite(ctx, me.Uid, article.Id, model.TypeArticle) } logic.Views.Incr(Request(ctx), model.TypeArticle, article.Id) // 为了阅读数即时看到 article.Viewnum++ return render(ctx, "articles/detail.html,common/comment.html", map[string]interface{}{"activeArticles": "active", "article": article, "prev": prevNext[0], "next": prevNext[1], "likeflag": likeFlag, "hadcollect": hadCollect}) }
// ======================================================================================================================== // Procedure: createConnections // // Does: // - Create all connections in DB for a particular user in order to use all applications // ======================================================================================================================== func GetConnections(c *echo.Context) error { userList, err := users.FindUsers() if err != nil { return c.JSON(http.StatusInternalServerError, hash{ "error": "Unable to retrieve users", }) } user := c.Get("user").(*users.User) connections, err := apps.RetrieveConnections(user, userList) if err == apps.AppsListUnavailable { return c.JSON(http.StatusInternalServerError, hash{ "error": "Unable to retrieve applications list", }) } var response = make([]hash, len(connections)) for i, val := range connections { res := hash{ "id": i, "type": "application", "attributes": val, } response[i] = res } return c.JSON(http.StatusOK, hash{"data": response}) }
// 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) }
// Create 发布新资源 func (ResourceController) Create(ctx echo.Context) error { title := ctx.FormValue("title") // 请求新建资源页面 if title == "" || ctx.Request().Method() != "POST" { return render(ctx, "resources/new.html", map[string]interface{}{"activeResources": "active", "categories": logic.AllCategory}) } errMsg := "" resForm := ctx.FormValue("form") if resForm == model.LinkForm { if ctx.FormValue("url") == "" { errMsg = "url不能为空" } } else { if ctx.FormValue("content") == "" { errMsg = "内容不能为空" } } if errMsg != "" { return fail(ctx, 1, errMsg) } me := ctx.Get("user").(*model.Me) err := logic.DefaultResource.Publish(ctx, me, ctx.FormParams()) if err != nil { return fail(ctx, 2, "内部服务错误,请稍候再试!") } return success(ctx, nil) }
func addSubscribersHandler(c echo.Context) error { cfg := c.Get("config").(*Config) var ( err error emails []string ) if err = c.Bind(&emails); err != nil { return c.JSON(StatusUnprocessableEntity, map[string]interface{}{ "message": "problem decoding request body", "error": err, }) } subs, err := SubscribeEmail(cfg, emails...) if err != nil { return c.JSON(StatusUnprocessableEntity, map[string]interface{}{ "message": "problem subscribing emails", "error": err, }) } return c.JSON(http.StatusOK, map[string]interface{}{ "subscribed": len(subs), }) }
// Home shows the resumes home page. // // Method GET // // Route /resume/ // // Restrictions Yes // // Template resume/home.html func Home(ctx *echo.Context) error { user := ctx.Get("User").(*models.Person) if res, err := query.GetAllPersonResumes(user); err == nil { utils.SetData(ctx, "resumes", res) } return ctx.Render(http.StatusOK, tmpl.ResumeHomeTpl, utils.GetData(ctx)) }
// shortcut to get session func Default(c *echo.Context) Session { session := c.Get(DefaultKey) if session == nil { return nil } return c.Get(DefaultKey).(Session) }