package repository import ( "context" "fmt" "github.com/uptrace/bun" "gitrepo.ru/neonxp/gorum/models" "golang.org/x/crypto/bcrypt" ) type User struct { db *bun.DB } func NewUser(db *bun.DB) *User { return &User{ db: db, } } func (u *User) Create(ctx context.Context, email, password, username string, role models.UserRole) (int, error) { hpassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return 0, models.ErrInvalidPassword } user := &models.User{ Email: email, Password: string(hpassword), Username: username, Role: role, } if _, err := u.db.NewInsert().Model(user).Returning("id").Exec(ctx); err != nil { return 0, models.ErrUserAlreadyExists } return user.ID, nil } func (u *User) Login(ctx context.Context, email, password string) (*models.User, error) { user := new(models.User) if err := u.db.NewSelect().Model(user).Where("email = ?", email).Scan(ctx); err != nil { return nil, fmt.Errorf("user not found: %w", models.ErrInvalidUserOrPassword) } if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { return nil, fmt.Errorf("invalid password: %w", models.ErrInvalidUserOrPassword) } return user, nil } func (u *User) List(ctx context.Context) ([]*models.User, error) { ret := make([]*models.User, 0) return ret, u.db.NewSelect().Model(&ret).Scan(ctx) }