ms-auth/internal/models/user.go

53 lines
1 KiB
Go
Raw Normal View History

2024-08-14 10:36:43 +00:00
package models
import (
2024-12-30 15:04:26 +00:00
"errors"
2024-08-14 10:36:43 +00:00
"golang.org/x/crypto/bcrypt"
"time"
)
2024-12-30 15:04:26 +00:00
type Role int32
2024-08-14 10:36:43 +00:00
2024-12-30 15:04:26 +00:00
const (
RoleParticipant Role = 0
RoleModerator Role = 1
RoleAdmin Role = 2
)
2024-08-14 10:36:43 +00:00
2024-12-30 15:04:26 +00:00
func (role Role) IsAdmin() bool {
return role == RoleAdmin
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
func (role Role) IsModerator() bool {
return role == RoleModerator
}
2024-08-14 10:36:43 +00:00
2024-12-30 15:04:26 +00:00
func (role Role) IsParticipant() bool {
return role == RoleParticipant
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
func (role Role) AtLeast(other Role) bool {
return role >= other
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
func (role Role) AtMost(other Role) bool {
return role <= other
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
type User struct {
Id int32 `db:"id"`
Username string `db:"username"`
HashedPassword string `db:"hashed_pwd"`
CreatedAt time.Time `db:"created_at"`
ModifiedAt time.Time `db:"modified_at"`
Role Role `db:"role"`
2024-08-14 10:36:43 +00:00
}
func (user *User) ComparePassword(password string) error {
2024-12-30 15:04:26 +00:00
err := bcrypt.CompareHashAndPassword([]byte(user.HashedPassword), []byte(password))
2024-08-14 10:36:43 +00:00
if err != nil {
2024-12-30 15:04:26 +00:00
return errors.New("bad username or password")
2024-08-14 10:36:43 +00:00
}
return nil
}