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 }
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 }
// Retreive purchase from database func (purch *Purchase) Retreive(db *gorm.DB) ([]Purchase, error) { var purchs []Purchase err := db.Where(purch).Find(&purchs).Error if err != nil { return nil, err } for i, p := range purchs { order := Order{} order.ID = p.OrderId if err := db.Model(&p).Related(&order, "OrderId").Error; err != nil { return nil, err } pproducts := []PurchaseProduct{} if err := db.Model(order).Related(&pproducts, "Pproducts").Error; err != nil { fmt.Println("[ERROR] ", err.Error()) return nil, err } order.Pproducts = pproducts p.PurschaseOrder = order purchs[i] = p } return purchs, err }
/* GetUser returns the user with that id */ func GetUser(db *gorm.DB, id int) (*User, error) { var user User if err := db.Where("ID = ?", id).First(&user).Error; err != nil { return nil, err } return &user, 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 CreateClient(db gorm.DB, options *Options) (id int64) { var c Client db.Where( &Client{ Hostname: options.Hostname, Interface: options.Interface, MacAddr: options.InterfaceData.HardwareAddr.String(), Ip: options.Ip, }, ).First(&c) if c.Id != 0 { db.Model(&c).Update( &Client{ LastSeen: time.Now().Unix(), }, ) } else { c.LastSeen = time.Now().Unix() c.Hostname = options.Hostname c.MacAddr = options.InterfaceData.HardwareAddr.String() c.Interface = options.Interface c.Ip = options.Ip db.Table("clients").Create(&c) } options.Client = &c return c.Id }
func checkVideoID(db *gorm.DB, videos []*putube.YoutubeVideo) (newVideoIdxs []int) { videoIDs := make([]string, len(videos)) for i := range videos { videoIDs[i] = videos[i].VideoID } var existingVideos []putube.YoutubeVideo if db.Where("video_id in (?)", videoIDs).Find(&existingVideos).RecordNotFound() { existingVideos = []putube.YoutubeVideo{} } newVideoIdxs = []int{} for i := range videos { nf := true for j := range existingVideos { if videos[i].VideoID == existingVideos[j].VideoID { nf = false break } } if nf { newVideoIdxs = append(newVideoIdxs, i) } } return }
func (p *AuthDao) GetByEmail(db *gorm.DB, email string) *User { var user User if db.Where("email = ? AND provider = ?", email, "email").First(&user).RecordNotFound() { return nil } return &user }
func FeedForGroupGet(db gorm.DB, params martini.Params, res http.ResponseWriter) (int, string) { podcast := models.Group{} var media = []models.Media{} if err := db.Where(&models.Group{Slug: params["slug"]}).First(&podcast).Error; err != nil { res.Header().Set(ContentType, PlainType) return http.StatusNotFound, "Feed not found" } db.Model(&podcast).Order("created_at desc").Limit(15).Related(&media) tpl, err := template.New("xml_feed").Funcs(template.FuncMap{"short": ShortenString}).Parse(xml_feed_t) if err != nil { res.Header().Set(ContentType, PlainType) return http.StatusInternalServerError, "Generating XML failed" } data := Feed{&podcast, &media} buf := new(bytes.Buffer) err = tpl.Execute(buf, data) log.Println(err) if err != nil { res.Header().Set(ContentType, PlainType) return http.StatusInternalServerError, "Generating XML failed" } res.Header().Set(ContentType, RSSType) return http.StatusOK, buf.String() }
// Bootstrap creates "migrations" table // to keep track of already run database migrations func Bootstrap(db *gorm.DB) error { migrationName := "bootstrap_migrations" migration := new(Migration) // Using Error instead of RecordNotFound because we want to check // if the migrations table exists. This is different from later migrations // where we query the already create migrations table. exists := nil == db.Where("name = ?", migrationName).First(migration).Error if exists { logger.Infof("Skipping %s migration", migrationName) return nil } logger.Infof("Running %s migration", migrationName) // Create migrations table if err := db.CreateTable(new(Migration)).Error; err != nil { return fmt.Errorf("Error creating migrations table: %s", db.Error) } // Save a record to migrations table, // so we don't rerun this migration again migration.Name = migrationName if err := db.Create(migration).Error; err != nil { return fmt.Errorf("Error saving record to migrations table: %s", err) } return nil }
func main() { var ( db gorm.DB ) db = SetupDb() db.Save(&User{ FirstName: "John", LastName: "Doe", Age: 24, }) db.Save(&User{ FirstName: "Jane", LastName: "Doe", Age: 52, }) db.Save(&User{ FirstName: "Joe", LastName: "Shmoe", Age: 10, }) //START CODE OMIT var users []User db.Where("last_name = ?", "Doe").Or("age < ?", 12).Limit(2).Order("age", true).Find(&users) for _, user := range users { fmt.Printf("%+v,", user) } fmt.Println() //END CODE OMIT }
// BeforeSave invokes required actions before persisting. func (u *User) BeforeSave(db *gorm.DB) (err error) { if u.Slug == "" { for i := 0; true; i++ { if i == 0 { u.Slug = slugify.Slugify(u.Username) } else { u.Slug = slugify.Slugify( fmt.Sprintf("%s-%d", u.Username, i), ) } notFound := db.Where( "slug = ?", u.Slug, ).Not( "id", u.ID, ).First( &User{}, ).RecordNotFound() if notFound { break } } } if u.Email != "" { email, err := govalidator.NormalizeEmail( u.Email, ) if err != nil { return fmt.Errorf("Failed to normalize email") } u.Email = email } if u.Password != "" { encrypt, err := bcrypt.GenerateFromPassword( []byte(u.Password), bcrypt.DefaultCost, ) if err != nil { return fmt.Errorf("Failed to encrypt password") } u.Hashword = string(encrypt) } if u.Hash == "" { u.Hash = base32.StdEncoding.EncodeToString( securecookie.GenerateRandomKey(32), ) } return nil }
// BeforeSave invokes required actions before persisting. func (u *Team) BeforeSave(db *gorm.DB) (err error) { if u.Slug == "" { for i := 0; true; i++ { if i == 0 { u.Slug = slugify.Slugify(u.Name) } else { u.Slug = slugify.Slugify( fmt.Sprintf("%s-%d", u.Name, i), ) } notFound := db.Where( "slug = ?", u.Slug, ).Not( "id", u.ID, ).First( &Team{}, ).RecordNotFound() if notFound { break } } } return nil }
func getUserById(db *gorm.DB, uId int64) (*MaillistUser, error) { var mu MaillistUser err := db.Where(&MaillistUser{UserId: uId}).Find(&mu).Error if err != nil { return nil, err } return &mu, nil }
func getUserDetailByUserId(db *gorm.DB, userid int64) (*UserDetail, error) { var user UserDetail err := db.Where(&UserDetail{UserId: userid}).First(&user).Error if err != nil { return nil, err } return &user, nil }
func GroupGet(db gorm.DB, r render.Render, params martini.Params) { podcast := models.Group{} if err := db.Where("slug = ?", params["slug"]).First(&podcast).Error; err != nil { r.JSON(http.StatusNotFound, map[string]interface{}{"error": "Group not found"}) return } r.JSON(http.StatusOK, podcast) }
func getUserProfileElementByUserIdField(db *gorm.DB, userid int64, field string) (*UserProfileElement, error) { var user UserProfileElement err := db.Where(&UserProfileElement{UserId: userid}).First(&user).Error if err != nil { return nil, err } return &user, nil }
func getUserProfileElementsByUserId(db *gorm.DB, userid int64) ([]UserProfileElement, error) { var user []UserProfileElement err := db.Where(&UserProfileElement{UserId: userid}).Find(&user).Error if err != nil { return nil, err } return user, nil }
func getPhotos(start uint, stop uint, db *gorm.DB) []TumblrPhoto { if start >= stop { return nil } photos := make([]TumblrPhoto, 0, 0) db.Where("id >= ? and id < ?", start, stop).Find(&photos) return photos }
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 GetUserFileById(db *gorm.DB, uId, dsId int64) (ds *UserFile, err error) { err = db.Where(&UserFileInfo{UserId: uId, FileId: dsId}).First(ds).Error if err != nil { revel.TRACE.Println(err) return nil, err } return }
// addWhere adds where query func addWhere(query *gorm.DB, selector map[string]interface{}) *gorm.DB { if selector == nil { return query } // instead sending one selector, do chaining here return query.Where(selector) }
func getVisitorByVisitorIp(db *gorm.DB, ip string) (*Visitor, error) { var user Visitor err := db.Where(&Visitor{VisitorIp: ip}).First(&user).Error if err != nil { return nil, err } return &user, nil }
func getVisitorByVisitorId(db *gorm.DB, userid int64) (*Visitor, error) { var user Visitor err := db.Where(&Visitor{VisitorId: userid}).First(&user).Error if err != nil { return nil, err } return &user, nil }
func MediaGet(db gorm.DB, r render.Render, params martini.Params) { media := models.Media{} if err := db.Where("slug = ?", params["slug"]).First(&media).Error; err != nil { r.JSON(http.StatusNotFound, map[string]interface{}{"error": "Media not found"}) return } r.JSON(http.StatusOK, media) }
func getUserByEmail(db *gorm.DB, email string) (*MaillistUser, error) { var mu MaillistUser err := db.Where(&MaillistUser{Email: email}).Find(&mu).Error if err != nil { return nil, err } return &mu, nil }
func DeleteItems(db *gorm.DB, data custom_structs.ItemsForDeleting) error { item := models.DBTypesMap()[data.Category] err := db.Where("id in (?)", data.Ids).Delete(item).Error if err != nil { return err } return nil }
func getUserBasicByName(db *gorm.DB, name string) (*UserBasic, error) { var user UserBasic err := db.Where(&UserBasic{UserName: name}).First(&user).Error if err != nil { return nil, err } return &user, nil }
func GetAllDraftMessages(db *gorm.DB) ([]MaillistMessage, error) { var mms []MaillistMessage err := db.Where(&MaillistMessage{Draft: true}).Find(&mms).Error if err != nil { return nil, err } return mms, nil }
func getUsersByList(db *gorm.DB, list string) ([]MaillistUser, error) { var mus []MaillistUser err := db.Where(&MaillistUser{List: list}).Find(&mus).Error if err != nil { return nil, err } return mus, nil }