// RetrieveLocation retrieves a location. func RetrieveLocation(c *gin.Context) (model.Location, bool, int64, int, error) { var location model.Location var currentUserId int64 isAuthor := false id := c.Params.ByName("id") if db.ORM.First(&location, "id = ?", id).RecordNotFound() { return location, isAuthor, currentUserId, http.StatusNotFound, errors.New("Location is not found.") } currentUser, err := userService.CurrentUser(c) if err == nil { currentUserId = currentUser.Id isAuthor = currentUser.Id == location.UserId } assignRelatedUser(&location) var commentList model.CommentList comments, currentPage, hasPrev, hasNext, _ := commentService.RetrieveComments(location) commentList.Comments = comments commentService.SetCommentPageMeta(&commentList, currentPage, hasPrev, hasNext, location.CommentCount) location.CommentList = commentList var likingList model.LikingList likings, currentPage, hasPrev, hasNext, _ := likingRetriever.RetrieveLikings(location) likingList.Likings = likings currentUserlikedCount := db.ORM.Model(&location).Where("id =?", currentUserId).Association("Likings").Count() log.Debugf("Current user like count : %d", currentUserlikedCount) likingMeta.SetLikingPageMeta(&likingList, currentPage, hasPrev, hasNext, location.LikingCount, currentUserlikedCount) location.LikingList = likingList return location, isAuthor, currentUserId, http.StatusOK, nil }
// RetrieveOauthStatus retrieves ouath status that provider connected or not. func RetrieveOauthStatus(c *gin.Context) (oauthStatusMap, int, error) { var oauthStatus oauthStatusMap var connections []model.Connection oauthStatus = make(oauthStatusMap) currentUser, err := userService.CurrentUser(c) if err != nil { return oauthStatus, http.StatusUnauthorized, err } db.ORM.Model(¤tUser).Association("Connections").Find(&connections) for _, connection := range connections { log.Debugf("connection.ProviderId : %d", connection.ProviderId) switch connection.ProviderId { case google.ProviderId: oauthStatus["google"] = true case github.ProviderId: oauthStatus["github"] = true case yahoo.ProviderId: oauthStatus["yahoo"] = true case facebook.ProviderId: oauthStatus["facebook"] = true case twitter.ProviderId: oauthStatus["twitter"] = true case linkedin.ProviderId: oauthStatus["linkedin"] = true case kakao.ProviderId: oauthStatus["kakao"] = true case naver.ProviderId: oauthStatus["naver"] = true } } log.Debugf("oauthStatus : %v", oauthStatus) return oauthStatus, http.StatusOK, nil }
// CreateFiles creates files. func CreateFiles(c *gin.Context) (int, error) { var forms FilesForm start := time.Now() c.BindWith(&forms, binding.JSON) log.Debugf("CreateFiles c form : %v", forms) user, _ := userService.CurrentUser(c) sqlStrBuffer := new(bytes.Buffer) stringHelper.Concat(sqlStrBuffer, "INSERT INTO file(user_id, name, size, created_at) VALUES ") values := []interface{}{} for _, file := range forms.Files { stringHelper.Concat(sqlStrBuffer, "(?, ?, ?, ?),") values = append(values, user.Id, file.Name, file.Size, time.Now()) } // sqlStrBuffer.Truncate(sqlStrBuffer.Len() - 1) is slower than slice. if len(values) > 0 { sqlStr := sqlStrBuffer.String() sqlStr = sqlStr[0 : len(sqlStr)-1] log.Debugf("sqlStr for File : %s", sqlStr) db.ORM.Exec(sqlStr, values...) elapsed := time.Since(start) log.Debugf("CreateFiles elapsed : %s", elapsed) } return http.StatusCreated, nil }
// RetrieveArticle retrieve an article. func RetrieveArticle(c *gin.Context) (model.Article, bool, int64, int, error) { var article model.Article var count int var currentUserId int64 var isAuthor bool id := c.Params.ByName("id") if db.ORM.First(&article, "id = ?", id).RecordNotFound() { return article, isAuthor, currentUserId, http.StatusNotFound, errors.New("Article is not found.") } log.Debugf("Article : %s\n", article) log.Debugf("Count : %s\n", count) currentUser, err := userService.CurrentUser(c) if err == nil { currentUserId = currentUser.Id isAuthor = currentUser.Id == article.UserId } assignRelatedUser(&article) var commentList model.CommentList comments, currentPage, hasPrev, hasNext, _ := commentService.RetrieveComments(article) commentList.Comments = comments commentService.SetCommentPageMeta(&commentList, currentPage, hasPrev, hasNext, article.CommentCount) article.CommentList = commentList var likingList model.LikingList likings, currentPage, hasPrev, hasNext, _ := likingRetriever.RetrieveLikings(article) likingList.Likings = likings currentUserlikedCount := db.ORM.Model(&article).Where("id =?", currentUserId).Association("Likings").Count() log.Debugf("Current user like count : %d", currentUserlikedCount) likingMeta.SetLikingPageMeta(&likingList, currentPage, hasPrev, hasNext, article.LikingCount, currentUserlikedCount) article.LikingList = likingList return article, isAuthor, currentUserId, http.StatusOK, nil }
// canUserWrite check that user can write a location. func canUserWrite(c *gin.Context) bool { canWrite := false _, err := userService.CurrentUser(c) if err == nil { canWrite = true } return canWrite }
// @Title test // @Description test API. // @Accept json // @Param theString form string true "The string that required." // @Param theInt form int false "The int that optional." // @Success 200 {object} response.BasicResponse "OK" // @Failure 401 {object} response.BasicResponse "Authentication required" // @Resource /experiments/test // @Router /experiments [get] func test(c *gin.Context) { currentUser, err := userService.CurrentUser(c) log.Debugf("header : %s", c.Request.Header.Get("X-Auth-Token")) // userService.SetCookieHandler(c, "elsa", "qqqq11") if err != nil { c.JSON(200, gin.H{"user": nil}) } else { c.JSON(200, gin.H{"user": currentUser}) } }
// UploadImages uploads images to a storage. func UploadImages(c *gin.Context) (int, error) { r := c.Request reader, err := r.MultipartReader() user, _ = userService.CurrentUser(c) s3UploadPath = config.UploadS3Path + strconv.FormatInt(user.Id, 10) + "/" if err != nil { return http.StatusInternalServerError, err } Upload(reader, KindUploaderBasic) return http.StatusOK, nil }
// UploadAndSyncArticles uploads images and sync articles. func UploadAndSyncArticles(c *gin.Context) (int, error) { r := c.Request reader, err := r.MultipartReader() user, _ = userService.CurrentUser(c) if err != nil { return http.StatusInternalServerError, err } Upload(reader, KindUploaderArticle) return http.StatusOK, nil }
// CurrentUserIdentical check that userId is same as current user's Id. func CurrentUserIdentical(c *gin.Context, userId int64) (int, error) { currentUser, err := userService.CurrentUser(c) if err != nil { return http.StatusUnauthorized, errors.New("Auth failed.") } if currentUser.Id != userId { return http.StatusForbidden, errors.New("User is not identical.") } return http.StatusOK, nil }
// UploadAndSyncArticles uploads images and sync articles. func UploadAndSyncArticles(c *gin.Context) (int, error) { r := c.Request reader, err := r.MultipartReader() user, _ = userService.CurrentUser(c) if err != nil { return http.StatusInternalServerError, err } // concurrency.Concurrent(reader, KindUploaderArticle) concurrency.Concurrent(reader, concurrency.ConcurrencyAgent(reader, Article업로더, ArticleUploader, ArticleCargador, ArticleShàngchuán, Articleзагрузчик)) return http.StatusOK, nil }
// AuthRequired run function when user logged in. func AuthRequired(f func(c *gin.Context)) gin.HandlerFunc { return func(c *gin.Context) { _, err := userService.CurrentUser(c) if err != nil { log.Error("Auth failed.") response.KnownErrorJSON(c, http.StatusUnauthorized, "error.loginPlease", errors.New("Auth failed.")) return } f(c) return } }
// CreateArticle creates an article. func CreateArticle(c *gin.Context) (model.Article, int, error) { var form ArticleForm c.BindWith(&form, binding.Form) log.Debugf("struct map : %s\n", form) user, _ := userService.CurrentUser(c) form.UserId = user.Id article := model.Article{} modelHelper.AssignValue(&article, &form) if db.ORM.Create(&article).Error != nil { return article, http.StatusInternalServerError, errors.New("User is not created.") } return article, http.StatusCreated, nil }
// CreateLocation creates a location. func CreateLocation(c *gin.Context) (model.Location, int, error) { var form LocationForm c.BindWith(&form, binding.Form) log.Debugf("struct map : %s\n", form) user, _ := userService.CurrentUser(c) form.UserId = user.Id location := model.Location{} modelHelper.AssignValue(&location, &form) if db.ORM.Create(&location).Error != nil { return location, http.StatusInternalServerError, errors.New("User is not created.") } return location, http.StatusCreated, nil }
// canUserWrite check that user can write an article. func canUserWrite(c *gin.Context, category int) bool { canWrite := false user, err := userService.CurrentUser(c) if err == nil { if category == 100 { if userPermission.HasAdmin(&user) { canWrite = true } } else { canWrite = true } } return canWrite }
// AdminRequired run function when user logged in and user has an admin role. func AdminRequired(f func(c *gin.Context)) gin.HandlerFunc { return func(c *gin.Context) { user, err := userService.CurrentUser(c) if err == nil { if HasAdmin(&user) { f(c) log.Debug("User has admin role.") return } } log.Error("Admin role required.") response.KnownErrorJSON(c, http.StatusUnauthorized, "error.adminRequired", errors.New("Admin role required.")) return } }
// UpdateUserLikedCount updates user liked count. func UpdateUserLikedCount(c *gin.Context) (int, error) { log.Debug("UpdateUserLikedCount performed") currentUserSrc, err := userService.CurrentUser(c) var currentUser model.User if err != nil { return http.StatusUnauthorized, err } db.ORM.First(¤tUser, currentUserSrc.Id) currentUser.LikedCount = db.ORM.Model(currentUser).Association("Liked").Count() log.Debugf("LikedCount : %d", currentUser.LikedCount) if db.ORM.Save(currentUser).Error != nil { return http.StatusInternalServerError, errors.New("User liked count is not updated.") } return http.StatusOK, nil }
// CreateFile creates a file. func CreateFile(c *gin.Context) (int, error) { var form FileForm c.BindWith(&form, binding.Form) log.Debugf("CreateFile form : %v", form) // err = json.Unmarshal(formDataBuffer[:n], &articles) // file := model.File{Name: form.Name, Size: form.Size} user, _ := userService.CurrentUser(c) form.UserId = user.Id file := model.File{} modelHelper.AssignValue(&file, &form) if db.ORM.Create(&file).Error != nil { return http.StatusInternalServerError, errors.New("File is not created.") } return http.StatusCreated, nil }
// RevokeOauth revokes oauth connection. func RevokeOauth(c *gin.Context, providerID int64) (oauthStatusMap, int, error) { var oauthStatus oauthStatusMap var connection model.Connection currentUser, err := userService.CurrentUser(c) if err != nil { return oauthStatus, http.StatusUnauthorized, err } if db.ORM.First(&connection, "user_id= ? and provider_id = ? ", currentUser.Id, providerID).RecordNotFound() { return oauthStatus, http.StatusNotFound, errors.New("Connection is not found.") } if db.ORM.Delete(&connection).Error != nil { return oauthStatus, http.StatusInternalServerError, errors.New("Connection not revoked from user.") } oauthStatus, status, err := RetrieveOauthStatus(c) return oauthStatus, status, err }
// CreateArticles creates articles. func CreateArticles(c *gin.Context) (int, error) { var forms ArticlesForm c.BindWith(&forms, binding.JSON) log.Debugf("CreateFiles c form : %v", forms) user, _ := userService.CurrentUser(c) sqlStrBuffer := new(bytes.Buffer) stringHelper.Concat(sqlStrBuffer, "INSERT INTO article(user_id, title, url, content, image_name, category_id, created_at) VALUES ") values := []interface{}{} for _, article := range forms.Articles { stringHelper.Concat(sqlStrBuffer, "(?, ?, ?, ?, ?, ?, ?),") values = append(values, user.Id, article.Title, article.Url, article.Content, article.ImageName, 0, time.Now()) } // sqlStrBuffer.Truncate(sqlStrBuffer.Len() - 1) is slower than slice. if len(values) > 0 { sqlStr := sqlStrBuffer.String() sqlStr = sqlStr[0 : len(sqlStr)-1] log.Debugf("sqlStr for File : %s", sqlStr) db.ORM.Exec(sqlStr, values...) } return http.StatusCreated, nil }
// CreateOauthUser creates oauth user. func CreateOauthUser(c *gin.Context, oauthUser *OauthUser, connection *model.Connection) (model.User, int, error) { var registrationForm userService.RegistrationForm var user model.User modelHelper.AssignValue(®istrationForm, oauthUser) registrationForm.Password = random.GenerateRandomString(12) if len(registrationForm.Username) == 0 { if len(registrationForm.Email) > 0 { registrationForm.Username = strings.Split(registrationForm.Email, "@")[0] } else { registrationForm.Username = "******" } } registrationForm.Username = userService.SuggestUsername(registrationForm.Username) generatedPassword, err := bcrypt.GenerateFromPassword([]byte(registrationForm.Password), 10) if err != nil { return user, http.StatusInternalServerError, errors.New("Password not generated.") } registrationForm.Password = string(generatedPassword) currentUser, err := userService.CurrentUser(c) if err != nil { log.Errorf("currentUser : %v", currentUser) user, err = userService.CreateUserFromForm(registrationForm) if err != nil { return user, http.StatusInternalServerError, errors.New("User is not created.") } } else { if db.ORM.Where("id = ?", currentUser.Id).First(&user).RecordNotFound() { return user, http.StatusInternalServerError, errors.New("User is not found.") } } db.ORM.Model(&user).Association("Connections").Append(connection) if db.ORM.Save(&user).Error != nil { return user, http.StatusInternalServerError, errors.New("Connection not appended to user.") } return user, http.StatusOK, nil }