Protecting routes on hte FE and improving authentication

This commit is contained in:
2024-08-20 21:45:13 +02:00
parent 2f7300db0f
commit a6d54242bb
14 changed files with 98 additions and 12 deletions

View File

@ -3,8 +3,11 @@ package models
import (
"context"
"database/sql"
"errors"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
)
// DBModel is the type for database connection values
@ -254,3 +257,26 @@ func (m *DBModel) GetUserByEmail(email string) (User, error) {
return u, nil
}
func (m *DBModel) Authenticate(email, password string) (int, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
var id int
var hashedPassword string
row := m.DB.QueryRowContext(ctx, "SELECT id, password from users WHERE email = ?", email)
err := row.Scan(&id, &hashedPassword)
if err != nil {
return 0, err
}
err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
if err == bcrypt.ErrMismatchedHashAndPassword {
return 0, errors.New("incorrect password")
} else if err != nil {
return 0, err
}
return id, nil
}