gpaste/users/user.go

46 lines
854 B
Go
Raw Normal View History

2022-01-20 02:35:55 +00:00
package users
2022-01-19 20:45:53 +00:00
2022-01-21 13:04:41 +00:00
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
2022-01-19 20:45:53 +00:00
2022-01-20 00:19:32 +00:00
type Role string
const (
RoleUnset Role = ""
RoleUser Role = "user"
RoleAdmin Role = "admin"
)
2022-01-19 20:45:53 +00:00
type User struct {
Username string `json:"username"`
2022-01-24 19:25:52 +00:00
HashedPassword []byte `json:"hashedPassword"`
2022-01-20 12:33:11 +00:00
Role Role `json:"role"`
2022-01-19 20:45:53 +00:00
}
2022-01-21 13:04:41 +00:00
var ErrNoSuchUser = fmt.Errorf("no such user")
2022-01-19 20:45:53 +00:00
type UserStore interface {
Get(username string) (*User, error)
Store(user *User) error
Delete(username string) error
2022-01-21 13:04:41 +00:00
List() ([]string, error)
2022-01-19 20:45:53 +00:00
}
func (u *User) ValidatePassword(password string) error {
return bcrypt.CompareHashAndPassword(u.HashedPassword, []byte(password))
}
func (u *User) SetPassword(password string) error {
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
2022-01-24 19:25:52 +00:00
2022-01-19 20:45:53 +00:00
u.HashedPassword = hashed
2022-01-24 19:25:52 +00:00
2022-01-19 20:45:53 +00:00
return nil
}