go-cook/api/repositories/users.go

50 lines
1.0 KiB
Go

package repositories
import (
"database/sql"
"go-cook/api/models"
"errors"
"fmt"
"github.com/huandu/go-sqlbuilder"
"golang.org/x/crypto/bcrypt"
)
// Creates a new instance of UserRepository with the bound sql
func NewUserRepository(conn *sql.DB) UserRepository {
return UserRepository{
connection: conn,
}
}
type UserRepository struct {
connection *sql.DB
}
func (ur UserRepository) GetByName(name string) (models.UserModel, error) {
builder := sqlbuilder.NewSelectBuilder()
builder.Select("*").From("users").Where(
builder.E("Name", name),
);
return models.UserModel{}, errors.New("user was not found")
}
func (ur UserRepository) NewUser(name string, password string) (int, error) {
passwordBytes := []byte(password)
hash, err := bcrypt.GenerateFromPassword(passwordBytes, bcrypt.DefaultCost)
if err != nil {
return 0, err
}
fmt.Println(hash)
query := sqlbuilder.NewInsertBuilder()
query.InsertInto("users")
query.Cols("name", "hash")
query.Values(name, string(hash))
ur.connection.Query(query.Build())
return 1, nil
}