2014-03-25 03:31:33 +00:00
|
|
|
package models
|
|
|
|
|
2015-02-07 23:30:22 +00:00
|
|
|
import "github.com/jinzhu/gorm"
|
2014-03-25 03:31:33 +00:00
|
|
|
|
|
|
|
// User represents the user model for gophish.
|
|
|
|
type User struct {
|
|
|
|
Id int64 `json:"id"`
|
2014-03-26 20:01:49 +00:00
|
|
|
Username string `json:"username" sql:"not null;unique"`
|
2014-03-25 03:31:33 +00:00
|
|
|
Hash string `json:"-"`
|
2014-03-26 20:01:49 +00:00
|
|
|
ApiKey string `json:"api_key" sql:"not null;unique"`
|
2014-03-25 03:31:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetUser returns the user that the given id corresponds to. If no user is found, an
|
|
|
|
// error is thrown.
|
|
|
|
func GetUser(id int64) (User, error) {
|
|
|
|
u := User{}
|
2014-03-26 04:53:51 +00:00
|
|
|
err := db.Where("id=?", id).First(&u).Error
|
2018-01-12 00:11:57 +00:00
|
|
|
return u, err
|
2014-03-25 03:31:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetUserByAPIKey returns the user that the given API Key corresponds to. If no user is found, an
|
|
|
|
// error is thrown.
|
2014-03-26 04:53:51 +00:00
|
|
|
func GetUserByAPIKey(key string) (User, error) {
|
2014-03-25 03:31:33 +00:00
|
|
|
u := User{}
|
2014-03-26 20:01:49 +00:00
|
|
|
err := db.Where("api_key = ?", key).First(&u).Error
|
2018-01-12 00:11:57 +00:00
|
|
|
return u, err
|
2014-03-25 03:31:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetUserByUsername returns the user that the given username corresponds to. If no user is found, an
|
|
|
|
// error is thrown.
|
|
|
|
func GetUserByUsername(username string) (User, error) {
|
|
|
|
u := User{}
|
2014-03-26 04:53:51 +00:00
|
|
|
err := db.Where("username = ?", username).First(&u).Error
|
2015-02-07 23:30:22 +00:00
|
|
|
// No issue if we don't find a record
|
2016-03-09 04:37:55 +00:00
|
|
|
if err == gorm.ErrRecordNotFound {
|
2015-02-07 23:30:22 +00:00
|
|
|
return u, nil
|
|
|
|
} else if err == nil {
|
2014-03-25 03:31:33 +00:00
|
|
|
return u, ErrUsernameTaken
|
|
|
|
}
|
2015-02-07 23:30:22 +00:00
|
|
|
return u, err
|
2014-03-25 03:31:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// PutUser updates the given user
|
|
|
|
func PutUser(u *User) error {
|
2014-03-27 18:19:57 +00:00
|
|
|
err := db.Save(u).Error
|
2014-03-25 03:31:33 +00:00
|
|
|
return err
|
|
|
|
}
|