2022-02-13 21:45:27 +01:00
|
|
|
package postgres
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
2022-02-14 01:25:36 +01:00
|
|
|
users2 "serverctl/pkg/application/users"
|
2022-02-13 21:45:27 +01:00
|
|
|
"serverctl/pkg/db"
|
|
|
|
)
|
|
|
|
|
2022-02-14 01:25:36 +01:00
|
|
|
var _ users2.Repository = &usersRepository{}
|
2022-02-13 21:45:27 +01:00
|
|
|
|
|
|
|
type usersRepository struct {
|
|
|
|
databasePool *db.Client
|
|
|
|
}
|
|
|
|
|
2022-02-14 01:25:36 +01:00
|
|
|
func NewUsersRepository(db *db.Client) users2.Repository {
|
2022-02-13 21:45:27 +01:00
|
|
|
return &usersRepository{db}
|
|
|
|
}
|
|
|
|
|
2022-02-14 01:25:36 +01:00
|
|
|
func (u *usersRepository) Create(ctx context.Context, user *users2.CreateUser) (int, error) {
|
2022-02-13 21:45:27 +01:00
|
|
|
var userId int
|
|
|
|
conn := u.databasePool.GetConn(ctx)
|
|
|
|
defer conn.Release()
|
|
|
|
|
2022-02-14 01:25:36 +01:00
|
|
|
conn.QueryRow(ctx, "INSERT INTO sctl_user(email, password_hash) values ($1, $2) RETURNING id", user.Email, user.PasswordHash).Scan(&userId)
|
2022-02-13 21:45:27 +01:00
|
|
|
|
|
|
|
if userId == 0 {
|
|
|
|
return -1, errors.New("could not insert data into users table")
|
|
|
|
}
|
|
|
|
|
|
|
|
return userId, nil
|
|
|
|
}
|
|
|
|
|
2022-02-14 01:25:36 +01:00
|
|
|
func (u *usersRepository) GetByEmail(ctx context.Context, email string, passwordHash string) (*users2.User, error) {
|
2022-02-13 21:45:27 +01:00
|
|
|
conn := u.databasePool.GetConn(ctx)
|
|
|
|
defer conn.Release()
|
|
|
|
|
|
|
|
var id int
|
2022-02-14 01:25:36 +01:00
|
|
|
err := conn.QueryRow(ctx, "select id from sctl_user where email = $1 and password_hash = $2", email, passwordHash).Scan(&id)
|
2022-02-13 21:45:27 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if id <= 0 {
|
|
|
|
return nil, errors.New("user with that password doesn't exist")
|
|
|
|
}
|
|
|
|
|
2022-02-14 01:25:36 +01:00
|
|
|
return users2.NewUser(id, email), nil
|
2022-02-13 21:45:27 +01:00
|
|
|
}
|