ictgj-voting/model_users.go

77 lines
1.7 KiB
Go
Raw Normal View History

2017-04-21 18:17:18 +00:00
package main
import "golang.org/x/crypto/bcrypt"
// dbHasUser
// Returns true if there are any users in the database
func (db *gjDatabase) hasUser() bool {
return len(db.getAllUsers()) > 0
2017-04-21 18:17:18 +00:00
}
func (db *gjDatabase) getAllUsers() []string {
if err := db.open(); err != nil {
2017-04-21 18:17:18 +00:00
return []string{}
}
defer db.close()
2017-04-21 18:17:18 +00:00
usrs, err := db.bolt.GetBucketList([]string{"users"})
2017-04-21 18:17:18 +00:00
if err != nil {
return []string{}
}
return usrs
}
func (db *gjDatabase) isValidUserEmail(email string) bool {
if err := db.open(); err != nil {
2017-04-21 18:17:18 +00:00
return false
}
defer db.close()
2017-04-21 18:17:18 +00:00
usrPath := []string{"users", email}
_, err := db.bolt.GetValue(usrPath, "password")
2017-04-21 18:17:18 +00:00
return err == nil
}
func (db *gjDatabase) checkCredentials(email, pw string) error {
2017-04-21 18:17:18 +00:00
var err error
if err = db.open(); err != nil {
2017-04-21 18:17:18 +00:00
return err
}
defer db.close()
2017-04-21 18:17:18 +00:00
var uPw string
usrPath := []string{"users", email}
if uPw, err = db.bolt.GetValue(usrPath, "password"); err != nil {
2017-04-21 18:17:18 +00:00
return err
}
return bcrypt.CompareHashAndPassword([]byte(uPw), []byte(pw))
}
// updateUserPassword
2017-04-21 18:17:18 +00:00
// Takes an email address and a password
// Creates the user if it doesn't exist, encrypts the password
// and updates it in the db
func (db *gjDatabase) updateUserPassword(email, password string) error {
2017-04-21 18:17:18 +00:00
cryptPw, cryptError := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if cryptError != nil {
return cryptError
}
if err := db.open(); err != nil {
2017-04-21 18:17:18 +00:00
return err
}
defer db.close()
2017-04-21 18:17:18 +00:00
usrPath := []string{"users", email}
return db.bolt.SetValue(usrPath, "password", string(cryptPw))
2017-04-21 18:17:18 +00:00
}
func (db *gjDatabase) deleteUser(email string) error {
2017-04-21 18:17:18 +00:00
var err error
if err = db.open(); err != nil {
2017-04-21 18:17:18 +00:00
return err
}
defer db.close()
2017-04-21 18:17:18 +00:00
return db.bolt.DeleteBucket([]string{"users"}, email)
2017-04-21 18:17:18 +00:00
}