This commit is contained in:
vinchent 2024-08-13 13:47:56 +02:00
parent 011b3a8c0b
commit 4ec1d8c5a2
4 changed files with 59 additions and 0 deletions

1
.gitignore vendored
View File

@ -5,3 +5,4 @@ docker/docker-compose.yml
cred.txt cred.txt
dist/ dist/
.air.toml .air.toml
tmp/

View File

@ -243,6 +243,19 @@ func (app *application) CreateAuthToken(w http.ResponseWriter, r *http.Request)
return return
} }
// get the user from the db by email, send error if invalid email
user, err := app.DB.GetUserByEmail(userInput.Email)
if err != nil {
app.invalidCredentials(w)
return
}
// validate the password, send error if invalid password
// generate the token
// send response
var payload struct { var payload struct {
Error bool `json:"error"` Error bool `json:"error"`
Message string `json:"message"` Message string `json:"message"`

View File

@ -68,3 +68,18 @@ func (app *application) badRequest(w http.ResponseWriter, r *http.Request, err e
w.Write(out) w.Write(out)
return nil return nil
} }
func (app *application) invalidCredentials(w http.ResponseWriter) error {
var payload struct {
Error bool `json:"error"`
Message string `json:"message"`
}
payload.Error = true
payload.Message = "invalid authentication credentials"
err := app.writeJSON(w, http.StatusUnauthorized, payload)
if err != nil {
return err
}
return nil
}

View File

@ -3,6 +3,7 @@ package models
import ( import (
"context" "context"
"database/sql" "database/sql"
"strings"
"time" "time"
) )
@ -223,3 +224,32 @@ func (m *DBModel) InsertCustomer(customer Customer) (int, error) {
} }
return int(id), nil return int(id), nil
} }
// GetUserByEmail gets a user by email address
func (m *DBModel) GetUserByEmail(email string) (User, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
email = strings.ToLower(email)
var u User
query := `SELECT id, first_name, last_name, email, password, created_at, updated_at
FROM users
WHERE email = ?`
row := m.DB.QueryRowContext(ctx, query, email)
err := row.Scan(
&u.ID,
&u.FirstName,
&u.LastName,
&u.Email,
&u.CreatedAt,
&u.UpdatedAt,
)
if err != nil {
return User{}, err
}
return u, nil
}