golang-lib/web/auth/models.go

45 lines
1.1 KiB
Go
Raw Normal View History

2021-06-01 10:51:35 +02:00
package auth
import (
"github.com/google/uuid"
"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-22 18:17:52 +02:00
p, err := HashPassword(password)
2021-06-01 10:51:35 +02:00
if err != nil {
return err
}
2021-06-22 18:17:52 +02:00
u.Password = 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 {
2021-06-22 18:17:52 +02:00
return ValidatePassword(u.Password, password)
2021-06-01 10:51:35 +02:00
}
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)
}