// EmailVerification verifies an email of user. func EmailVerification(c *gin.Context) (int, error) { var user model.User var verifyEmailForm VerifyEmailForm c.BindWith(&verifyEmailForm, binding.Form) log.Debugf("verifyEmailForm.ActivationToken : %s", verifyEmailForm.ActivationToken) if db.ORM.Where(&model.User{ActivationToken: verifyEmailForm.ActivationToken}).First(&user).RecordNotFound() { return http.StatusNotFound, errors.New("User is not found.") } isExpired := timeHelper.IsExpired(user.ActivateUntil) log.Debugf("passwordResetUntil : %s", user.ActivateUntil.UTC()) log.Debugf("expired : %t", isExpired) if isExpired { return http.StatusForbidden, errors.New("token not valid.") } user.ActivationToken = "" user.ActivateUntil = time.Now() user.ActivatedAt = time.Now() user.Activation = true status, err := UpdateUserCore(&user) if err != nil { return status, err } status, err = SetCookie(c, user.Token) return status, err }
// 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 }
func (s *Server) CommentDeleteHandler(c *gin.Context) { var form struct { Entry string `form:"entry" binding:"required"` Comment string `form:"comment" binding:"required"` } c.BindWith(&form, binding.Form) // TODO: check perm profile, _ := s.CurrentUser(c) graph, _ := s.CurrentGraph(c) req := &pb.CommentDeleteRequest{ Entry: form.Entry, Comment: form.Comment, User: profile.Id, } ctx, cancel := DefaultTimeoutContext() defer cancel() entry, err := s.client.DeleteComment(ctx, req) if RequestError(c, err) { return } entry.FormatComments(int32(0)) entry.RebuildCommentsCommand(profile, graph) c.JSON(200, entry.Comments) }
func addUser(c *gin.Context) { var ( user User err error passHash []byte ) err = c.BindWith(&user, binding.JSON) if err != nil { c.JSON(404, "Couldn't bind!") } else { if db.NewRecord(user) { user.CreatedAt = time.Now().UTC() user.UpdatedAt = time.Now().UTC() // Create password hash originalPass := []byte(user.PasswordHash) if passHash, err = bcrypt.GenerateFromPassword(originalPass, bcrypt.DefaultCost); err != nil { fmt.Printf("%v", err) } user.PasswordHash = string(passHash) db.Create(&user) c.JSON(201, user) } else { c.JSON(400, "This user already exist") } } }
func (ac *AdminController) SaveBlogEditCtr(c *gin.Context) { session := sessions.Default(c) username := session.Get("username") if username == nil { (&umsg{"You have no permission", "/"}).ShowMessage(c) return } var BI EditBlogItem c.BindWith(&BI, binding.Form) if BI.Aid == "" { (&umsg{"Can not find the blog been edit", "/"}).ShowMessage(c) return } if BI.Title == "" { (&umsg{"Title can not empty", "/"}).ShowMessage(c) return } if BI.Content == "" { (&umsg{"Content can not empty", "/"}).ShowMessage(c) return } _, err := DB.Exec("update top_article set title=?, content=? where aid = ?", BI.Title, BI.Content, BI.Aid) if err == nil { Cache = lru.New(8192) (&umsg{"Success", "/"}).ShowMessage(c) } else { (&umsg{"Failed to save blog", "/"}).ShowMessage(c) } }
func commonDeploy(ginCtx *gin.Context) (DeployRequest, error) { ginCtx.Request.ParseForm() var givenDeploy DeployRequest ginCtx.BindWith(&givenDeploy, binding.JSON) glog.Infof("given %+v", givenDeploy) return givenDeploy, nil }
// SendPasswordResetToken sends a password reset token. func SendPasswordResetToken(c *gin.Context) (int, error) { var user model.User var sendPasswordResetForm SendPasswordResetForm var err error log.Debugf("c.Params : %v", c.Params) c.BindWith(&sendPasswordResetForm, binding.Form) if db.ORM.Where(&model.User{Email: sendPasswordResetForm.Email}).First(&user).RecordNotFound() { return http.StatusNotFound, errors.New("User is not found. Please Check the email.") } user.PasswordResetUntil = timeHelper.TwentyFourHoursLater() user.PasswordResetToken, err = crypto.GenerateRandomToken16() if err != nil { return http.StatusInternalServerError, err } log.Debugf("generated token : %s", user.PasswordResetToken) status, err := UpdateUserCore(&user) if err != nil { return status, err } err = SendEmailPasswordResetToken(user.Email, user.PasswordResetToken, "en-us") if err != nil { return http.StatusInternalServerError, err } return http.StatusOK, nil }
// ResetPassword resets a password of user. func ResetPassword(c *gin.Context) (int, error) { var user model.User var passwordResetForm PasswordResetForm c.BindWith(&passwordResetForm, binding.Form) if db.ORM.Where(&model.User{PasswordResetToken: passwordResetForm.PasswordResetToken}).First(&user).RecordNotFound() { return http.StatusNotFound, errors.New("User is not found.") } isExpired := timeHelper.IsExpired(user.PasswordResetUntil) log.Debugf("passwordResetUntil : %s", user.PasswordResetUntil.UTC()) log.Debugf("expired : %t", isExpired) if isExpired { return http.StatusForbidden, errors.New("token not valid.") } newPassword, err := bcrypt.GenerateFromPassword([]byte(passwordResetForm.Password), 10) if err != nil { return http.StatusInternalServerError, errors.New("User is not updated. Password not Generated.") } passwordResetForm.Password = string(newPassword) log.Debugf("user password before : %s ", user.Password) modelHelper.AssignValue(&user, &passwordResetForm) user.PasswordResetToken = "" user.PasswordResetUntil = time.Now() log.Debugf("user password after : %s ", user.Password) status, err := UpdateUserCore(&user) if err != nil { return status, err } status, err = SetCookie(c, user.Token) return status, err }
func (ac *AdminController) SaveBlogAddCtr(c *gin.Context) { session := sessions.Default(c) username := session.Get("username") if username == nil { (&umsg{"You have no permission", "/"}).ShowMessage(c) return } var BI BlogItem c.BindWith(&BI, binding.Form) if BI.Title == "" { (&umsg{"Title can not empty", "/"}).ShowMessage(c) return } if BI.Content == "" { (&umsg{"Content can not empty", "/"}).ShowMessage(c) return } _, err := DB.Exec( "insert into top_article (title, content, publish_time, publish_status) values (?, ?, ?, 1)", BI.Title, BI.Content, time.Now().Format("2006-01-02 15:04:05")) if err == nil { Cache = lru.New(8192) (&umsg{"Success", "/"}).ShowMessage(c) } else { (&umsg{"Failed to save blog", "/"}).ShowMessage(c) } }
func (fc *AdminController) SaveBlogEditCtr(c *gin.Context) { var BI EditBlogItem config := GetConfig() c.BindWith(&BI, binding.Form) if BI.Aid == "" { (&msg{"Can not find the blog been edit"}).ShowMessage(c) return } if BI.Title == "" { (&msg{"Title can not empty"}).ShowMessage(c) return } if BI.Content == "" { (&msg{"Content can not empty"}).ShowMessage(c) return } db := GetDB(config) _, err := db.Exec("update top_article set title=?, content=? where aid = ?", BI.Title, BI.Content, BI.Aid) if err == nil { (&msg{"Success"}).ShowMessage(c) } else { (&msg{"Failed to save blog"}).ShowMessage(c) } }
func updateUser(c *gin.Context) { var ( user User changeset User err error passHash []byte ) id := c.Params.ByName("id") db.First(&user, id) err = c.BindWith(&changeset, binding.JSON) if err != nil { c.JSON(404, "Couldn't bind!") } else { user.UpdatedAt = time.Now().UTC() user.Username = changeset.Username user.Email = changeset.Email if changeset.PasswordHash != "" && changeset.PasswordHash != user.PasswordHash { err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(changeset.PasswordHash)) if err != nil { if passHash, err = bcrypt.GenerateFromPassword([]byte(changeset.PasswordHash), bcrypt.DefaultCost); err != nil { fmt.Printf("%v", err) } user.PasswordHash = string(passHash) } } db.Save(&user) c.JSON(201, user) } }
// OauthGithub link connection and user. func OauthGithub(c *gin.Context) (int, error) { var authResponse oauth2.AuthResponse var oauthUser OauthUser c.BindWith(&authResponse, binding.Form) log.Debugf("oauthRedirect form: %v", authResponse) response, token, err := oauth2.OauthRequest(github.RequestURL, github.Config, authResponse) if err != nil { log.Error("get response error") return http.StatusInternalServerError, err } githubUser, err := SetGithubUser(response) if err != nil { log.Error("SetGithubUser error") return http.StatusInternalServerError, err } modelHelper.AssignValue(&oauthUser, githubUser) oauthUser.Id = strconv.Itoa(githubUser.UserId) log.Debugf("\noauthUser item : %v", oauthUser) status, err := LoginOrCreateOauthUser(c, &oauthUser, github.ProviderId, token) if err != nil { log.Errorf("LoginOrCreateOauthUser error: %d", status) return status, err } return http.StatusSeeOther, nil }
func addPointToListHandler(c *gin.Context) { request := addPointToListRequest{} if err := c.Bind(&request.addPointToListRequestParams); err != nil { outputJSONErrorCheckType(c.Writer, err, http.StatusInternalServerError) return } if err := c.BindWith(&request.addPointToListRequestParams, binding.Form); err != nil { outputJSONErrorCheckType(c.Writer, err, http.StatusInternalServerError) return } request.list = c.Params.ByName("list") request.point = c.Params.ByName("point") if err := addPointToList(&request); err != nil { outputJSONErrorCheckType(c.Writer, err, http.StatusInternalServerError) return } if request.ReturnZone == false { c.Writer.Header().Set("Content-Type", "application/json") c.Writer.WriteHeader(http.StatusCreated) } else { listZoneModel := listZoneModel{} if err := db.Get(&listZoneModel, "select * from get_list_geohash_zones_for_point($1, $2, $3)", request.list, request.point, maxListZoneNPoints); err != nil { outputJSONErrorCheckType(c.Writer, err, http.StatusInternalServerError) return } c.JSON(http.StatusCreated, &listZoneModel) } }
// CreateUserAuthentication creates user authentication. func CreateUserAuthentication(c *gin.Context) (int, error) { var form LoginForm c.BindWith(&form, binding.Form) email := form.Email pass := form.Password status, err := SetCookieHandler(c, email, pass) return status, err }
// CreateRole creates a role. func CreateRole(c *gin.Context) (model.Role, int, error) { var form RoleForm c.BindWith(&form, binding.Form) name := form.Name description := form.Description role := model.Role{Name: name, Description: description} if db.ORM.Create(&role).Error != nil { return role, http.StatusInternalServerError, errors.New("Role is not created.") } return role, http.StatusCreated, nil }
func (ac *AdminController) LoginProcessCtr(c *gin.Context) { var form AdminLoginForm c.BindWith(&form, binding.Form) if form.Username == Config.Admin_user && form.Password == Config.Admin_password { session := sessions.Default(c) session.Set("username", "netroby") session.Save() c.Redirect(301, "/") } else { (&msg{"Login failed"}).ShowMessage(c) } }
// 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 }
// 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 }
// ActivateUser toggle activation of a user. func ActivateUser(c *gin.Context) (model.User, int, error) { id := c.Params.ByName("id") var user model.User var form ActivateForm c.BindWith(&form, binding.Form) if db.ORM.First(&user, id).RecordNotFound() { return user, http.StatusNotFound, errors.New("User is not found.") } user.Activation = form.Activation if db.ORM.Save(&user).Error != nil { return user, http.StatusInternalServerError, errors.New("User not activated.") } return user, http.StatusOK, nil }
func slackPOST(c *gin.Context) { var reqBody SlackPayload c.BindWith(&reqBody, binding.Form) if configured() && validSlackToken(reqBody.Token) { payload, err := buildLibratoPayload(reqBody.Text) if err != nil { c.JSON(slackReply(422)) } else { c.JSON(slackReply(annotate(payload))) } } else { c.JSON(slackReply(401)) } }
// RetrieveCommentsOnArticles retrieve comments on an article. func RetrieveCommentsOnArticle(c *gin.Context) ([]model.Comment, int, bool, bool, int, int, error) { var article model.Article var comments []model.Comment var retrieveListForm form.RetrieveListForm var hasPrev, hasNext bool var currentPage, count int articleId := c.Params.ByName("id") if db.ORM.First(&article, articleId).RecordNotFound() { return comments, currentPage, hasPrev, hasNext, count, http.StatusNotFound, errors.New("Article is not found.") } c.BindWith(&retrieveListForm, binding.Form) log.Debugf("retrieveListForm : %v", retrieveListForm) comments, currentPage, hasPrev, hasNext, count = commentService.RetrieveComments(article, retrieveListForm.CurrentPage) return comments, currentPage, hasPrev, hasNext, count, http.StatusOK, nil }
// RetrieveCommentsOnLocations retrieve comments on a location. func RetrieveCommentsOnLocation(c *gin.Context) ([]model.Comment, int, bool, bool, int, int, error) { var location model.Location var comments []model.Comment var retrieveListForm form.RetrieveListForm var hasPrev, hasNext bool var currentPage, count int locationId := c.Params.ByName("id") if db.ORM.First(&location, locationId).RecordNotFound() { return comments, currentPage, hasPrev, hasNext, count, http.StatusNotFound, errors.New("Location is not found.") } c.BindWith(&retrieveListForm, binding.Form) comments, currentPage, hasPrev, hasNext, count = commentService.RetrieveComments(location, retrieveListForm.CurrentPage) return comments, currentPage, hasPrev, hasNext, count, 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 }
// UpdateRole updates a role. func UpdateRole(c *gin.Context) (model.Role, int, error) { var role model.Role var form RoleForm id := c.Params.ByName("id") c.BindWith(&form, binding.Form) if db.ORM.First(&role, id).RecordNotFound() { return role, http.StatusNotFound, errors.New("Role is not found.") } role.Name = form.Name role.Description = form.Description if db.ORM.Save(&role).Error != nil { return role, http.StatusInternalServerError, errors.New("Role is not updated.") } return role, http.StatusOK, nil }
// RetrieveLikingsOnArticles retrieves likings on article. func RetrieveLikingsOnArticles(c *gin.Context) ([]model.User, int, bool, bool, int, int, error) { var article model.Article var likings []model.User var retrieveListForm form.RetrieveListForm var hasPrev, hasNext bool var currentPage, count int articleId := c.Params.ByName("id") log.Debugf("Liking params : %v", c.Params) c.BindWith(&retrieveListForm, binding.Form) log.Debugf("retrieveListForm %+v\n", retrieveListForm) if db.ORM.First(&article, articleId).RecordNotFound() { return likings, currentPage, hasPrev, hasNext, count, http.StatusNotFound, errors.New("Article is not found.") } likings, currentPage, hasPrev, hasNext, count = likingRetriever.RetrieveLikings(article, retrieveListForm.CurrentPage) return likings, currentPage, hasPrev, hasNext, count, http.StatusOK, nil }
// RetrieveLikingsOnLocations retrieves likings on location. func RetrieveLikingsOnLocations(c *gin.Context) ([]*model.PublicUser, int, bool, bool, int, int, error) { var location model.Location var likings []*model.PublicUser var retrieveListForm form.RetrieveListForm var hasPrev, hasNext bool var currentPage, count int locationId := c.Params.ByName("id") log.Debugf("Liking params : %v", c.Params) c.BindWith(&retrieveListForm, binding.Form) log.Debugf("retrieveListForm %+v\n", retrieveListForm) if db.ORM.First(&location, locationId).RecordNotFound() { return likings, currentPage, hasPrev, hasNext, count, http.StatusNotFound, errors.New("Location is not found.") } likings, currentPage, hasPrev, hasNext, count = likingRetriever.RetrieveLikings(location, retrieveListForm.CurrentPage) return likings, currentPage, hasPrev, hasNext, count, http.StatusOK, nil }
// CreateComment creates a comment. func CreateComment(c *gin.Context, item interface{}) (int, error) { var form CreateCommentForm var comment model.Comment c.BindWith(&form, binding.Form) log.Debugf("comment_form : %v", form) status, err := userPermission.CurrentUserIdentical(c, form.UserId) if err != nil { return status, err } if db.ORM.First(item, form.ParentId).RecordNotFound() { return http.StatusNotFound, errors.New("Item is not found.") } modelHelper.AssignValue(&comment, &form) db.ORM.Model(item).Association("Comments").Append(comment) return http.StatusOK, nil }
// TODO: allow cross post to multiply feeds func (s *Server) EntryPostHandler(c *gin.Context) { var form struct { FeedId string `form:"feedid" binding:"required"` Body string `form:"body" binding:"required"` } c.BindWith(&form, binding.MultipartForm) if !s.feedWritable(c, form.FeedId) { c.AbortWithStatus(401) return } body := util.DefaultSanitize(form.Body) body = util.EntityToLink(body) ctx, cancel := DefaultTimeoutContext() defer cancel() profile, _ := s.CurrentUser(c) dt := time.Now().UTC() name := profile.Uuid + "/" + dt.Format(time.RFC3339) uuid1 := uuid.NewV5(uuid.NamespaceURL, name) from := &pb.Feed{ Id: profile.Id, Name: profile.Name, Type: profile.Type, } entry := &pb.Entry{ Id: uuid1.String(), Date: dt.Format(time.RFC3339), Body: body, RawBody: form.Body, From: from, // To: []*pb.Feed{from}, // Thumbnails: thumbnails, ProfileUuid: profile.Uuid, } entry, err := s.client.PostEntry(ctx, entry) if RequestError(c, err) { return } // c.JSON(200, gin.H{"entry": entry}) c.Redirect(http.StatusFound, "/") }
// CreateLiking create a liking. func CreateLiking(c *gin.Context, item interface{}) (int, error) { var form CreateLikingForm var likingUser model.User c.BindWith(&form, binding.Form) log.Debugf("liking_form : %v", form) if db.ORM.First(item, form.ParentId).RecordNotFound() { return http.StatusNotFound, errors.New("Item is not found.") } if db.ORM.First(&likingUser, form.UserId).RecordNotFound() { return http.StatusNotFound, errors.New("User is not found.") } status, err := userPermission.CurrentUserIdentical(c, likingUser.Id) if err != nil { return status, err } db.ORM.Model(item).Association("Likings").Append(likingUser) return http.StatusOK, nil }
// UpdateFile updates a file. func UpdateFile(c *gin.Context) (model.File, int, error) { var file model.File var form FileForm id := c.Params.ByName("id") c.BindWith(&form, binding.Form) if db.ORM.First(&file, id).RecordNotFound() { return file, http.StatusNotFound, errors.New("File is not found.") } status, err := userPermission.CurrentUserIdentical(c, file.UserId) if err != nil { return file, status, err } file.Name = form.Name file.Size = form.Size if db.ORM.Save(&file).Error != nil { return file, http.StatusInternalServerError, errors.New("File is not updated.") } return file, http.StatusOK, nil }