// SaveBinary will efficently save a binary and it's associated parts. // Having to do this for efficency is probably a good sign that I should just // use sqlx or something. func saveBinary(tx *gorm.DB, b *types.Binary) error { var txerr error if tx.NewRecord(b) { parts := b.Parts b.Parts = []types.Part{} txerr = tx.Save(b).Error if txerr != nil { return txerr } pids := make([]int64, len(parts)) for i, p := range parts { pids[i] = p.ID } txerr = tx.Model(types.Part{}).Where("id IN (?)", pids).Updates(map[string]interface{}{"binary_id": b.ID}).Error if txerr != nil { return txerr } } else { pids := make([]int64, len(b.Parts)) for i, p := range b.Parts { pids[i] = p.ID } txerr = tx.Model(types.Part{}).Where("id IN (?)", pids).Updates(map[string]interface{}{"binary_id": b.ID}).Error if txerr != nil { return txerr } } return nil }
func ChangePassword(username string, newpassword string, db *gorm.DB) (int, error) { var user User var err error dbErr := db.Where(&User{UserName: username}).Find(&user).Error if dbErr != nil { if dbErr == gorm.RecordNotFound { WARNING.Println(UnregisteredUser.Error() + " ,username: "******"Password record not updated for userId: " + strconv.FormatInt(user.Id, 10) + ", Error details: " + updatePasswordErr.Error()) return 500, DatabaseError } db.Save(&ActivityLog{UserId: user.Id, TokenId: -1, ActivityTime: time.Now().UTC(), Event: PASSWORD_CHANGE}) TRACE.Println("Password changed for userId: " + strconv.FormatInt(user.Id, 10)) return 200, nil }
//Create new token entry in the database func CreateNewTokenDbEntry(login LoginCredential, db *gorm.DB) (string, error) { user := User{} db.Where(&User{UserName: login.Username}).Find(&user) token := Token{} token.UserId = user.Id token.Key = uuid.New() token.CreatedAt = time.Now().UTC() token.LastAccessedAt = time.Now().UTC() token.Token = generateSessionToken(login.Username+token.CreatedAt.String(), token.Key) token.Active = true expiryTime, err := GetTimeOutValue(login.DeviceId) if err != nil { ERROR.Println(err.Error()) return "", err } token.ExpiresAt = expiryTime var device DeviceType db.Where(&DeviceType{DeviceCode: login.DeviceId}).Find(&device) token.DeviceTypeId = device.Id db.Save(&token) db.Save(&ActivityLog{UserId: token.UserId, TokenId: token.Id, ActivityTime: time.Now().UTC(), Event: LOGIN}) return token.Token, nil }
func CreateNewUser(request CreateUserRequest, db *gorm.DB) (int, error) { var err error if ValidateUniqueUsername(request.Username, db) { var user User user.UserName = request.Username user.LegalName = request.LegalName user.Password, err = EncryptPassword(request.Password) user.UpdatedAt = time.Now().UTC() user.Active = false if err != nil { ERROR.Println(err.Error()) return 500, EncryptionError } db.Save(&user) TRACE.Println("New user created, userId: " + strconv.FormatInt(user.Id, 10)) db.Save(&PasswordRecord{UserId: user.Id, LoginCount: 0}) TRACE.Println("New password record created, userId: " + strconv.FormatInt(user.Id, 10)) return 200, nil } ERROR.Println("Duplicate username " + request.Username + " server validation in create user") return 409, DuplicateUsernameError }
func ValidateSessionToken(sessionToken string, db *gorm.DB) (error, int64) { var token Token dbErr := db.Where(&Token{Token: sessionToken}).Find(&token).Error if dbErr != nil { if dbErr == gorm.RecordNotFound { WARNING.Println(InvalidSessionToken.Error() + ", sessionToken: " + sessionToken) return InvalidSessionToken, -1 } ERROR.Println(dbErr.Error() + ", sessionToken: " + sessionToken) return dbErr, -1 } if token.Active && token.ExpiresAt.After(time.Now().UTC()) { TRACE.Println("SessionToken validated: " + sessionToken) timeLeft := token.ExpiresAt.Sub(time.Now().UTC()) if timeLeft.Minutes() < 5 { token.ExpiresAt = token.ExpiresAt.Add(time.Duration(GetTimeExtension()) * time.Minute) } token.LastAccessedAt = time.Now().UTC() db.Save(&token) return nil, token.UserId } return ExpiredSessionToken, -1 }
func Process(address *models.Address, db *gorm.DB, key string) error { query := fmt.Sprintf("%s, %s, %s, %s, BR, %s", address.Logradouro, address.Bairro, address.Localidade, address.Uf, address.Cep) address.Latitude, address.Longitude = getGeocode(query, key) return db.Save(address).Error }
func updateTodoHandler(r *http.Request, params martini.Params, rendr render.Render, db *gorm.DB) { id, err := strconv.Atoi(params["id"]) if err != nil { rendr.Text(http.StatusBadRequest, "Provide a `completed` paramter as a boolean") return } t, err := findTodo(db, &todo{ID: id}) if err != nil { rendr.Text(http.StatusBadRequest, err.Error()) return } text := r.FormValue("text") if text != "" { t.Text = text } completed := r.FormValue("completed") if completed != "" { completedBool, err := strconv.ParseBool(completed) if err != nil { rendr.Text(http.StatusBadRequest, err.Error()) return } t.Completed = completedBool } db.Save(t) rendr.JSON(http.StatusOK, t) }
// AfterSave invokes required actions after persisting. func (u *Repo) AfterSave(db *gorm.DB) (err error) { tags := Tags{} err = db.Model( u, ).Related( &tags, ).Error if err != nil { return err } for _, tag := range tags { err = db.Save( tag, ).Error if err != nil { return err } } return nil }
func PutContent(db gorm.DB, router *gin.Engine) { // PUT /content // Update content data by id router.PUT("/content/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var contentData model.ContentData if err := c.BindJSON(&contentData); err == nil { content := &model.Content{ ContentData: contentData, ContentId: model.ContentId{Id: id}, } if err := checkDataContent(content.ContentData); err { checkContent := &model.Content{ ContentData: contentData, ContentId: model.ContentId{Id: id}, } if err := db.First(checkContent).Error; err == nil { db.Save(&content) c.JSON(http.StatusOK, content) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func PutModuleEnabled(db gorm.DB, router *gin.Engine) { // PUT /module_enabled // Update module_enabled data by id router.PUT("/module_enabled/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var module_enabledData model.ModuleEnabledData if err := c.BindJSON(&module_enabledData); err == nil { module_enabled := &model.ModuleEnabled{ ModuleEnabledData: module_enabledData, ModuleEnabledId: model.ModuleEnabledId{Id: id}, } if err := checkDataModuleEnabled(module_enabled.ModuleEnabledData); err { checkModuleEnabled := &model.ModuleEnabled{ ModuleEnabledData: module_enabledData, ModuleEnabledId: model.ModuleEnabledId{Id: id}, } if err := db.First(checkModuleEnabled).Error; err == nil { db.Save(&module_enabled) c.JSON(http.StatusOK, module_enabled) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func PutProfileFieldCategory(db gorm.DB, router *gin.Engine) { // PUT /profile_field_category // Update profile_field_category data by id router.PUT("/profile_field_category/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var profile_field_categoryData model.ProfileFieldCategoryData if err := c.BindJSON(&profile_field_categoryData); err == nil { profile_field_category := &model.ProfileFieldCategory{ ProfileFieldCategoryData: profile_field_categoryData, ProfileFieldCategoryId: model.ProfileFieldCategoryId{Id: id}, } if err := checkDataProfileFieldCategory(profile_field_category.ProfileFieldCategoryData); err { checkProfileFieldCategory := &model.ProfileFieldCategory{ ProfileFieldCategoryData: profile_field_categoryData, ProfileFieldCategoryId: model.ProfileFieldCategoryId{Id: id}, } if err := db.First(checkProfileFieldCategory).Error; err == nil { db.Save(&profile_field_category) c.JSON(http.StatusOK, profile_field_category) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func PutUrlOembed(db gorm.DB, router *gin.Engine) { // PUT /url_oembed // Update url_oembed data by id router.PUT("/url_oembed/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var url_oembedData model.UrlOembedData if err := c.BindJSON(&url_oembedData); err == nil { url_oembed := &model.UrlOembed{ UrlOembedData: url_oembedData, UrlOembedId: model.UrlOembedId{Id: id}, } if err := checkDataUrlOembed(url_oembed.UrlOembedData); err { checkUrlOembed := &model.UrlOembed{ UrlOembedData: url_oembedData, UrlOembedId: model.UrlOembedId{Id: id}, } if err := db.First(checkUrlOembed).Error; err == nil { db.Save(&url_oembed) c.JSON(http.StatusOK, url_oembed) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func PutSpaceSetting(db gorm.DB, router *gin.Engine) { // PUT /space_setting // Update space_setting data by id router.PUT("/space_setting/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var space_settingData model.SpaceSettingData if err := c.BindJSON(&space_settingData); err == nil { space_setting := &model.SpaceSetting{ SpaceSettingData: space_settingData, SpaceSettingId: model.SpaceSettingId{Id: id}, } if err := checkDataSpaceSetting(space_setting.SpaceSettingData); err { checkSpaceSetting := &model.SpaceSetting{ SpaceSettingData: space_settingData, SpaceSettingId: model.SpaceSettingId{Id: id}, } if err := db.First(checkSpaceSetting).Error; err == nil { db.Save(&space_setting) c.JSON(http.StatusOK, space_setting) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
// AfterSave invokes required actions after persisting. func (u *Registry) AfterSave(db *gorm.DB) (err error) { orgs := Orgs{} err = db.Model( u, ).Related( &orgs, ).Error if err != nil { return err } for _, org := range orgs { err = db.Save( org, ).Error if err != nil { return err } } return nil }
func PutUserHttpSession(db gorm.DB, router *gin.Engine) { // PUT /user_http_session // Update user_http_session data by id router.PUT("/user_http_session/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var user_http_sessionData model.UserHttpSessionData if err := c.BindJSON(&user_http_sessionData); err == nil { user_http_session := &model.UserHttpSession{ UserHttpSessionData: user_http_sessionData, UserHttpSessionId: model.UserHttpSessionId{Id: id}, } if err := checkDataUserHttpSession(user_http_session.UserHttpSessionData); err { checkUserHttpSession := &model.UserHttpSession{ UserHttpSessionData: user_http_sessionData, UserHttpSessionId: model.UserHttpSessionId{Id: id}, } if err := db.First(checkUserHttpSession).Error; err == nil { db.Save(&user_http_session) c.JSON(http.StatusOK, user_http_session) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
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 PutPost(db gorm.DB, router *gin.Engine) { // PUT /post // Update post data by id router.PUT("/post/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var postData model.PostData if err := c.BindJSON(&postData); err == nil { post := &model.Post{ PostData: postData, PostId: model.PostId{Id: id}, } if err := checkDataPost(post.PostData); err { checkPost := &model.Post{ PostData: postData, PostId: model.PostId{Id: id}, } if err := db.First(checkPost).Error; err == nil { db.Save(&post) c.JSON(http.StatusOK, post) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func AddUserFile(db *gorm.DB, udt *UserFileInfo, content []byte) error { lastId, err := getLastFileIdByUserId(db, udt.UserId) if err != nil { revel.TRACE.Println(err) return err } nextId := lastId + 1 // revel.INFO.Println("Next DS id: ", nextId) udt.FileId = nextId err = db.Save(udt).Error if err != nil { revel.TRACE.Println(err) return err } ds := &UserFile{ UserId: udt.UserId, FileId: udt.FileId, Content: content, } err = db.Save(ds).Error if err != nil { revel.TRACE.Println(err) return err } return err }
func ClassifyPost(params martini.Params, res http.ResponseWriter, cls models.Classify, db *gorm.DB) string { db.Save(&cls) fi, err := os.Open("./jade/layout-tmpl.jade") if err != nil { panic(err) } defer fi.Close() fd, err2 := ioutil.ReadAll(fi) f, err2 := os.OpenFile("./jade/layout.jade", os.O_RDWR, 0755) if err2 != nil { panic(err) } css := []models.Classify{} db.Find(&css) var buf bytes.Buffer for _, v := range css { buf.WriteString(" a(href=\"/" + v.Url + ".html\") " + v.Title + "\n") } w := strings.Replace(string(fd), "####", buf.String(), -1) n, err1 := io.WriteString(f, w) //写入文件(字符串) if err1 != nil { panic(err1) } fmt.Printf("写入 %d 个字节n", n) return "1" }
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) }
func PutLike(db gorm.DB, router *gin.Engine) { // PUT /like // Update like data by id router.PUT("/like/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var likeData model.LikeData if err := c.BindJSON(&likeData); err == nil { like := &model.Like{ LikeData: likeData, LikeId: model.LikeId{Id: id}, } if err := checkDataLike(like.LikeData); err { checkLike := &model.Like{ LikeData: likeData, LikeId: model.LikeId{Id: id}, } if err := db.First(checkLike).Error; err == nil { db.Save(&like) c.JSON(http.StatusOK, like) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func PutWallEntry(db gorm.DB, router *gin.Engine) { // PUT /wall_entry // Update wall_entry data by id router.PUT("/wall_entry/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var wall_entryData model.WallEntryData if err := c.BindJSON(&wall_entryData); err == nil { wall_entry := &model.WallEntry{ WallEntryData: wall_entryData, WallEntryId: model.WallEntryId{Id: id}, } if err := checkDataWallEntry(wall_entry.WallEntryData); err { checkWallEntry := &model.WallEntry{ WallEntryData: wall_entryData, WallEntryId: model.WallEntryId{Id: id}, } if err := db.First(checkWallEntry).Error; err == nil { db.Save(&wall_entry) c.JSON(http.StatusOK, wall_entry) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func PutFile(db gorm.DB, router *gin.Engine) { // PUT /file // Update file data by id router.PUT("/file/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var fileData model.FileData if err := c.BindJSON(&fileData); err == nil { file := &model.File{ FileData: fileData, FileId: model.FileId{Id: id}, } if err := checkDataFile(file.FileData); err { checkFile := &model.File{ FileData: fileData, FileId: model.FileId{Id: id}, } if err := db.First(checkFile).Error; err == nil { db.Save(&file) c.JSON(http.StatusOK, file) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func PutActivity(db gorm.DB, router *gin.Engine) { // PUT /activity // Update activity data by id router.PUT("/activity/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var activityData model.ActivityData if err := c.BindJSON(&activityData); err == nil { activity := &model.Activity{ ActivityData: activityData, ActivityId: model.ActivityId{Id: id}, } if err := checkDataActivity(activity.ActivityData); err { checkActivity := &model.Activity{ ActivityData: activityData, ActivityId: model.ActivityId{Id: id}, } if err := db.First(checkActivity).Error; err == nil { db.Save(&activity) c.JSON(http.StatusOK, activity) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func PutGroupAdmin(db gorm.DB, router *gin.Engine) { // PUT /group_admin // Update group_admin data by id router.PUT("/group_admin/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var group_adminData model.GroupAdminData if err := c.BindJSON(&group_adminData); err == nil { group_admin := &model.GroupAdmin{ GroupAdminData: group_adminData, GroupAdminId: model.GroupAdminId{Id: id}, } if err := checkDataGroupAdmin(group_admin.GroupAdminData); err { checkGroupAdmin := &model.GroupAdmin{ GroupAdminData: group_adminData, GroupAdminId: model.GroupAdminId{Id: id}, } if err := db.First(checkGroupAdmin).Error; err == nil { db.Save(&group_admin) c.JSON(http.StatusOK, group_admin) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
// AfterSave invokes required actions after persisting. func (u *Org) AfterSave(db *gorm.DB) (err error) { repos := Repos{} err = db.Model( u, ).Related( &repos, ).Error if err != nil { return err } for _, repo := range repos { err = db.Save( repo, ).Error if err != nil { return err } } return nil }
// UpdateSingle Function, Updating User (Not Including Profile Relation) func UpdateSingle(id int, f UserUpdateForm, DB *gorm.DB) (user User, err []helper.ErrorMessage) { user, _err := GetSingle(id, DB) if _err != nil { return user, _err } user.Fullname = f.Data.Fullname user.Profile.Gender = f.Data.Gender user.Profile.Address = f.Data.Address user.Profile.PhoneNumber = f.Data.PhoneNumber user.Profile.BirthPlace = f.Data.BirthPlace user.Profile.BirthDate, _ = time.Parse("01/02/2006", f.Data.BirthDate) _errSaving := DB.Save(&user).Error if _errSaving != nil { err = append(err, helper.ErrorMessage{ Code: 400, Source: helper.SourceErrors{}, Title: "Update User Failed", Details: _errSaving.Error(), }) return user, err } return user, nil }
func PutNotification(db gorm.DB, router *gin.Engine) { // PUT /notification // Update notification data by id router.PUT("/notification/:id", func(c *gin.Context) { _id := c.Param("id") if id, err := strconv.ParseUint(_id, 10, 64); err == nil { var notificationData model.NotificationData if err := c.BindJSON(¬ificationData); err == nil { notification := &model.Notification{ NotificationData: notificationData, NotificationId: model.NotificationId{Id: id}, } if err := checkDataNotification(notification.NotificationData); err { checkNotification := &model.Notification{ NotificationData: notificationData, NotificationId: model.NotificationId{Id: id}, } if err := db.First(checkNotification).Error; err == nil { db.Save(¬ification) c.JSON(http.StatusOK, notification) } else { c.AbortWithStatus(http.StatusNotFound) } } else { c.AbortWithStatus(http.StatusBadRequest) } } } else { log.Print(err) c.AbortWithError(http.StatusBadRequest, err) } }) }
func setFileId(db *gorm.DB, pid uint, fid uint) { photo := TumblrPhoto{} db.Where("id = ?", pid).First(&photo) if !db.NewRecord(photo) { photo.FileDataID = fid db.Save(&photo) } }
func addUserPhone(db *gorm.DB, uId int64, p_type, number string) error { u := &UserPhone{ UserId: uId, PhoneType: p_type, PhoneNumber: number, } return db.Save(u).Error }