Auth
This commit is contained in:
parent
011b3a8c0b
commit
4ec1d8c5a2
1
.gitignore
vendored
1
.gitignore
vendored
@ -5,3 +5,4 @@ docker/docker-compose.yml
|
||||
cred.txt
|
||||
dist/
|
||||
.air.toml
|
||||
tmp/
|
||||
|
@ -243,6 +243,19 @@ func (app *application) CreateAuthToken(w http.ResponseWriter, r *http.Request)
|
||||
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 {
|
||||
Error bool `json:"error"`
|
||||
Message string `json:"message"`
|
||||
|
@ -68,3 +68,18 @@ func (app *application) badRequest(w http.ResponseWriter, r *http.Request, err e
|
||||
w.Write(out)
|
||||
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
|
||||
}
|
||||
|
@ -3,6 +3,7 @@ package models
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@ -223,3 +224,32 @@ func (m *DBModel) InsertCustomer(customer Customer) (int, error) {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user