64 lines
1.5 KiB
Go
64 lines
1.5 KiB
Go
package models
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.maronato.dev/maronato/goshort/internal/util/passwords"
|
|
)
|
|
|
|
const (
|
|
// noLoginPassword is the password used when the user is not allowed to login using a password.
|
|
noLoginPassword = "nologin"
|
|
)
|
|
|
|
type User struct {
|
|
// ID is the user's ID.
|
|
ID string `json:"id"`
|
|
// Username is the user's username.
|
|
Username string `json:"username"`
|
|
// password is the user's password.
|
|
password string `json:"-"`
|
|
|
|
// CreatedAt is the time the user was created.
|
|
CreatedAt time.Time `json:"createdAt,omitempty"`
|
|
}
|
|
|
|
// NewAuthenticatableUser is a elper function for storages that takes
|
|
// a public user and adds a hashed password to it.
|
|
func NewAuthenticatableUser(user *User, hashedPass string) *User {
|
|
return &User{
|
|
ID: user.ID,
|
|
Username: user.Username,
|
|
CreatedAt: user.CreatedAt,
|
|
password: hashedPass,
|
|
}
|
|
}
|
|
|
|
// SetPassword sets a password.
|
|
func (u *User) SetPassword(hasher passwords.PasswordHasher, pass string) error {
|
|
hash, err := hasher.Hash(pass)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to hash password: %w", err)
|
|
}
|
|
|
|
// Set the hashed password
|
|
u.password = hash
|
|
|
|
return nil
|
|
}
|
|
|
|
// SetNoLoginPassword sets the user's password to a no-login password.
|
|
func (u *User) SetNoLoginPassword() {
|
|
u.password = noLoginPassword
|
|
}
|
|
|
|
// GetPasswordHash Returns the password hash to be saved in a storage.
|
|
func (u *User) GetPasswordHash() string {
|
|
return u.password
|
|
}
|
|
|
|
func (u *User) CanLogin() bool {
|
|
return u.password != noLoginPassword && u.password != ""
|
|
}
|