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