2021-06-01 10:51:35 +02:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
2021-06-01 18:44:09 +02:00
|
|
|
// User struct - default User model which could be extended
|
2021-06-01 10:51:35 +02:00
|
|
|
type User struct {
|
|
|
|
ID uuid.UUID `json:"id" gorm:"type:uuid;default:gen_random_uuid()" example:"88078ec0-2135-445f-bf05-632701c77695"`
|
|
|
|
Username string `json:"username" gorm:"unique" example:"kukoon"`
|
|
|
|
Password string `json:"-" example:"super secret password"`
|
|
|
|
}
|
|
|
|
|
2021-06-01 18:44:09 +02:00
|
|
|
// NewUser by username and password
|
2021-06-01 10:51:35 +02:00
|
|
|
func NewUser(username, password string) (*User, error) {
|
|
|
|
user := &User{
|
|
|
|
Username: username,
|
|
|
|
}
|
|
|
|
if err := user.SetPassword(password); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return user, nil
|
|
|
|
}
|
|
|
|
|
2021-06-01 18:44:09 +02:00
|
|
|
// SetPassword - create new hash of password
|
|
|
|
func (u *User) SetPassword(password string) error {
|
2021-06-01 10:51:35 +02:00
|
|
|
p, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-06-01 18:44:09 +02:00
|
|
|
u.Password = string(p)
|
2021-06-01 10:51:35 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-06-01 18:44:09 +02:00
|
|
|
// ValidatePassword - check if given password is equal to saved hash
|
|
|
|
func (u *User) ValidatePassword(password string) bool {
|
|
|
|
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
|
2021-06-01 10:51:35 +02:00
|
|
|
return err == nil
|
|
|
|
}
|
|
|
|
|
2021-06-01 18:44:09 +02:00
|
|
|
// HasPermission interface for middleware check in other models
|
2021-06-01 10:51:35 +02:00
|
|
|
type HasPermission interface {
|
|
|
|
HasPermission(tx *gorm.DB, userID, objID uuid.UUID) (interface{}, error)
|
|
|
|
}
|