diff --git a/models/user.go b/models/user.go index a77a3ec..a8119f6 100644 --- a/models/user.go +++ b/models/user.go @@ -6,6 +6,7 @@ import ( "strings" "golang.org/x/crypto/bcrypt" + "google.golang.org/grpc/resolver/passthrough" ) type User struct { @@ -41,3 +42,24 @@ func (us *UserService) Create(email, password string) (*User, error) { } 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 +}