Compare commits

...

2 Commits

Author SHA1 Message Date
4a756e850e Validating the token on the back end 2024-08-19 22:22:40 +02:00
7ef68d030b Checking authentication on the backend 2024-08-19 21:39:36 +02:00
6 changed files with 104 additions and 2 deletions

View File

@ -1,5 +1,5 @@
STRIPE_SECRET=$(shell sed '2q;d' cred.txt)
STRIPE_KEY=$(shell sed '2q;d' cred.txt)
STRIPE_KEY=$(shell sed '1q;d' cred.txt)
GOSTRIPE_PORT=4000
API_PORT=4001
DSN=vinchent:secret@tcp(localhost:3306)/widgets?parseTime=true&tls=false

View File

@ -2,11 +2,13 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"myapp/internal/cards"
"myapp/internal/models"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
@ -297,3 +299,47 @@ func (app *application) CreateAuthToken(w http.ResponseWriter, r *http.Request)
_ = app.writeJSON(w, http.StatusOK, payload)
}
func (app *application) authenticateToken(r *http.Request) (*models.User, error) {
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

@ -23,6 +23,7 @@ func (app *application) routes() http.Handler {
mux.Post("/api/create-customer-and-subscribe-to-plan", app.CreateCustomerAndSubscribeToPlan)
mux.Post("/api/authenticate", app.CreateAuthToken)
mux.Post("/api/is-authenticated", app.CheckAuthentication)
return mux
}

View File

@ -76,8 +76,10 @@ Virtual Terminal
{{ define "js" }}
<script src="https://js.stripe.com/v3/"></script>
<script type="module">
import {stripeInit} from "/static/js/common.js";
import {stripeInit, checkAuth} from "/static/js/common.js";
import {val} from "/static/js/stripe.js"
checkAuth({{.API}});
stripeInit('{{.StripePubKey}}');
document.getElementById("charge_amount").addEventListener("change", (evt) => {
if (evt.target.value !== "") {

View File

@ -71,3 +71,27 @@ func (m *DBModel) InsertToken(t *Token, u User) error {
}
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

@ -62,3 +62,32 @@ export function stripeInit(pubKey) {
});
})();
}
export function checkAuth(api) {
if (localStorage.getItem("token") === null) {
location.href = "/login";
return
} else {
let token = localStorage.getItem("token")
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Bearer " + token);
const requestOptions = {
method: "POST",
headers: myHeaders,
}
fetch(api + "/api/is-authenticated", requestOptions)
.then(response => response.json())
.then(function(data) {
if (data.error === true) {
console.log("not logged in");
location.href = "/login"
} else {
console.log("Logged in");
}
})
}
}