1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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)
}
|