Add user authentication function

This commit is contained in:
Lucas Schumacher 2024-08-07 19:33:41 -04:00
parent 2d53824194
commit c4b5dcedf9

View File

@ -6,6 +6,7 @@ import (
"strings" "strings"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"google.golang.org/grpc/resolver/passthrough"
) )
type User struct { type User struct {
@ -41,3 +42,24 @@ func (us *UserService) Create(email, password string) (*User, error) {
} }
return &user, nil return &user, nil
} }
func (us UserService) Authenticate(email, password string) (*User, error) {
user := User{
Email: strings.ToLower(email),
}
row := us.DB.QueryRow(`
SELECT id, password_hash
FROM users WHERE email=$1
`, email)
err := row.Scan(&user.ID, &user.PasswordHash)
if err != nil {
return nil, fmt.Errorf("authenticate: %w", err)
}
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
if err != nil {
return nil, fmt.Errorf("authenticate: %w", err)
}
return &user, nil
}