A web blog and personal homepage engine written in Go.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

67 lines
1.6 KiB

package models
import (
"errors"
"fmt"
"strings"
"git.kirsle.net/apps/gophertype/pkg/constants"
"github.com/jinzhu/gorm"
"golang.org/x/crypto/bcrypt"
)
// User account for the site.
type User struct {
gorm.Model
Username string `json:"username" gorm:"unique_index"`
HashedPassword string `json:"-"`
IsAdmin bool `json:"isAdmin" gorm:"index"`
Name string `json:"name"`
Email string `json:"email" gorm:"index"`
}
// Validate the User object has everything filled in. Fixes what it can,
// returns an error if something is wrong. Ensures the HashedPassword is hashed.
func (u *User) Validate() error {
u.Username = strings.TrimSpace(strings.ToLower(u.Username))
u.Name = strings.TrimSpace(strings.ToLower(u.Name))
// Defaults
if len(u.Name) == 0 {
u.Name = u.Username
}
if len(u.Username) == 0 {
return errors.New("username is required")
}
return nil
}
// SetPassword stores the hashed password for a user.
func (u *User) SetPassword(password string) error {
hash, err := bcrypt.GenerateFromPassword([]byte(password), constants.BcryptCost)
if err != nil {
return fmt.Errorf("SetPassword: %s", err)
}
u.HashedPassword = string(hash)
fmt.Printf("Set hashed password: %s", u.HashedPassword)
return nil
}
// FirstAdmin returns the admin user with the lowest ID number.
func FirstAdmin() (User, error) {
var user User
r := DB.First(&user, "is_admin", true)
return user, r.Error
}
// CreateUser adds a new user to the database.
func CreateUser(u User) error {
if err := u.Validate(); err != nil {
return err
}
r := DB.Create(&u)
return r.Error
}