Validating the token on the back end

This commit is contained in:
vinchent 2024-08-19 22:22:40 +02:00
parent 7ef68d030b
commit 4a756e850e
3 changed files with 69 additions and 3 deletions

View File

@ -2,11 +2,13 @@ package main
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"myapp/internal/cards" "myapp/internal/cards"
"myapp/internal/models" "myapp/internal/models"
"net/http" "net/http"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
@ -298,6 +300,46 @@ func (app *application) CreateAuthToken(w http.ResponseWriter, r *http.Request)
_ = app.writeJSON(w, http.StatusOK, payload) _ = app.writeJSON(w, http.StatusOK, payload)
} }
func (app *application) CheckAuthentication(w http.ResponseWriter, r *http.Request) { func (app *application) authenticateToken(r *http.Request) (*models.User, error) {
app.invalidCredentials(w) authorizationHeader := r.Header.Get("Authorization")
if authorizationHeader == "" {
return nil, errors.New("no authorization header received")
}
headerParts := strings.Split(authorizationHeader, " ")
if len(headerParts) != 2 || headerParts[0] != "Bearer" {
return nil, errors.New("no authorization header received")
}
token := headerParts[1]
if len(token) != 26 {
return nil, errors.New("authentication token wrong size")
}
// get the user from the tokens table
user, err := app.DB.GetUserForToken(token)
if err != nil {
return nil, errors.New("no matching user found")
}
return user, nil
}
func (app *application) CheckAuthentication(w http.ResponseWriter, r *http.Request) {
// validate the token, and get associated user
user, err := app.authenticateToken(r)
if err != nil {
app.errorLog.Println(err)
app.invalidCredentials(w)
return
}
// valid user
var payload struct {
Error bool `json:"error"`
Message string `json:"message"`
}
payload.Error = false
payload.Message = fmt.Sprintf("authenticated user %s", user.Email)
app.writeJSON(w, http.StatusOK, payload)
} }

View File

@ -71,3 +71,27 @@ func (m *DBModel) InsertToken(t *Token, u User) error {
} }
return nil return nil
} }
func (m *DBModel) GetUserForToken(token string) (*User, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
tokenHash := sha256.Sum256([]byte(token))
var user User
query := `SELECT u.id, u.first_name, u.last_name, u.email
FROM users u
INNER JOIN tokens t on (u.id = t.user_id)
WHERE t.token_hash = ?`
err := m.DB.QueryRowContext(ctx, query, tokenHash[:]).Scan(
&user.ID,
&user.FirstName,
&user.LastName,
&user.Email,
)
if err != nil {
return nil, err
}
return &user, nil
}

View File

@ -75,7 +75,7 @@ export function checkAuth(api) {
const requestOptions = { const requestOptions = {
method: "POST", method: "POST",
Headers: myHeaders, headers: myHeaders,
} }
fetch(api + "/api/is-authenticated", requestOptions) fetch(api + "/api/is-authenticated", requestOptions)