From c4b5dcedf9f016c079735369252fff0aa6ef05ea Mon Sep 17 00:00:00 2001 From: Lucas Schumacher Date: Wed, 7 Aug 2024 19:33:41 -0400 Subject: [PATCH] Add user authentication function --- models/user.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) 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 +}