ms-auth/internal/models/user.go

82 lines
1.6 KiB
Go
Raw Normal View History

2024-08-14 10:36:43 +00:00
package models
import (
2024-10-09 17:07:38 +00:00
"git.sch9.ru/new_gate/ms-auth/pkg/utils"
2024-08-14 10:36:43 +00:00
"golang.org/x/crypto/bcrypt"
"time"
)
type User struct {
Id *int32 `db:"id"`
Username *string `db:"username"`
Password *string `db:"hashed_pwd"`
Email *string `db:"email"`
ExpiresAt *time.Time `db:"expires_at"`
CreatedAt *time.Time `db:"created_at"`
UpdatedAt *time.Time `db:"updated_at"`
Role *Role `db:"role"`
}
func (user *User) ValidUsername() error {
if user.Username == nil {
2024-10-09 17:07:38 +00:00
return utils.ErrBadUsername
2024-08-14 10:36:43 +00:00
}
2024-10-09 17:07:38 +00:00
err := utils.ValidUsername(*user.Username)
2024-08-14 10:36:43 +00:00
if err != nil {
return err
}
return nil
}
func (user *User) ValidPassword() error {
if user.Password == nil {
2024-10-09 17:07:38 +00:00
return utils.ErrBadHandleOrPassword
2024-08-14 10:36:43 +00:00
}
2024-10-09 17:07:38 +00:00
err := utils.ValidPassword(*user.Password)
2024-08-14 10:36:43 +00:00
if err != nil {
return err
}
return nil
}
func (user *User) ValidEmail() error {
if user.Email == nil {
2024-10-09 17:07:38 +00:00
return utils.ErrBadEmail
2024-08-14 10:36:43 +00:00
}
2024-10-09 17:07:38 +00:00
return utils.ValidEmail(*user.Email)
2024-08-14 10:36:43 +00:00
}
func (user *User) ValidRole() error {
if user.Role == nil {
2024-10-09 17:07:38 +00:00
return utils.ErrBadRole
2024-08-14 10:36:43 +00:00
}
return user.Role.Valid()
}
func (user *User) HashPassword() error {
if user.Password == nil {
2024-10-09 17:07:38 +00:00
return utils.ErrBadHandleOrPassword
2024-08-14 10:36:43 +00:00
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(*user.Password), bcrypt.DefaultCost)
if err != nil {
2024-10-09 17:07:38 +00:00
return utils.ErrInternal
2024-08-14 10:36:43 +00:00
}
2024-10-09 17:07:38 +00:00
user.Password = utils.AsStringP(string(hashedPassword))
2024-08-14 10:36:43 +00:00
return nil
}
func (user *User) ComparePassword(password string) error {
if user.Password == nil {
2024-10-09 17:07:38 +00:00
return utils.ErrBadHandleOrPassword
2024-08-14 10:36:43 +00:00
}
err := bcrypt.CompareHashAndPassword([]byte(*user.Password), []byte(password))
if err != nil {
2024-10-09 17:07:38 +00:00
return utils.ErrBadHandleOrPassword
2024-08-14 10:36:43 +00:00
}
return nil
}