示例#1
0
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
}
示例#2
0
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
}
示例#3
0
// 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
}
示例#4
0
/*
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
}
示例#5
0
//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
}
示例#6
0
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
}
示例#7
0
文件: save.go 项目: rooa/puku
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
}
示例#8
0
文件: dao.go 项目: itpkg/base
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
}
示例#9
0
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()
}
示例#10
0
// 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
}
示例#12
0
// 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
}
示例#13
0
// 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
}
示例#14
0
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
}
示例#15
0
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
}
示例#16
0
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)
}
示例#17
0
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
}
示例#18
0
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
}
示例#19
0
文件: main.go 项目: Jiajun-Fan/nandu
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
}
示例#20
0
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)
	}
}
示例#21
0
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
}
示例#22
0
// 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)
}
示例#23
0
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
}
示例#24
0
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
}
示例#25
0
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)
}
示例#26
0
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
}
示例#27
0
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
}
示例#28
0
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
}
示例#29
0
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
}
示例#30
0
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
}