implement auth using Auth0
This commit is contained in:
@@ -0,0 +1,313 @@
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"ruben/inventory2/internal/consts"
|
||||
)
|
||||
|
||||
// TODO: move these to a config?
|
||||
const (
|
||||
// The URL of our Auth0 Tenant Domain.
|
||||
// If you're using a Custom Domain, be sure to set this to that value instead.
|
||||
AUTH0_DOMAIN = "dev-uq3gqy5bdnwxmr6d.us.auth0.com"
|
||||
|
||||
// Our Auth0 application"s Client ID.
|
||||
AUTH0_CLIENT_ID = "JEjrXTQ9fxlTLgp9RgTIACpUk8a2lqNT"
|
||||
|
||||
// Our Auth0 application"s Client Secret.
|
||||
AUTH0_CLIENT_SECRET = "83U-iWdVaNnwk9XDzteo_2VMyOq_l1siKYqg1_2E7jCzgL8MnkaxlysPMcPMGlxA"
|
||||
|
||||
// The Callback URL of our application.
|
||||
AUTH0_CALLBACK_URL = "https://inventory-plus-plus.com/login/callback"
|
||||
)
|
||||
|
||||
type (
|
||||
// Authenticator is used to authenticate our users.
|
||||
Authenticator struct {
|
||||
*oidc.Provider
|
||||
oauth2.Config
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
// AccessTokenClaims is the claims Auth0 provides in access tokens
|
||||
AccessTokenClaims struct {
|
||||
Audience string `json:"aud"`
|
||||
Expires int64 `json:"exp"`
|
||||
FamilyName string `json:"family_name"`
|
||||
GivenName string `json:"given_name"`
|
||||
IssuedAt int64 `json:"iat"`
|
||||
Issuer string `json:"iss"`
|
||||
Name string `json:"name"`
|
||||
Nickname string `json:"nickname"`
|
||||
Picture string `json:"picture"`
|
||||
SessionID string `json:"sid"`
|
||||
Subject string `json:"sub"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
)
|
||||
|
||||
// New instantiates the *Authenticator.
|
||||
func New(ctx context.Context, db *pgxpool.Pool) (*Authenticator, error) {
|
||||
provider, err := oidc.NewProvider(
|
||||
ctx,
|
||||
"https://"+AUTH0_DOMAIN+"/",
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Authenticator{
|
||||
Provider: provider,
|
||||
Config: oauth2.Config{
|
||||
ClientID: AUTH0_CLIENT_ID,
|
||||
ClientSecret: AUTH0_CLIENT_SECRET,
|
||||
RedirectURL: AUTH0_CALLBACK_URL,
|
||||
Endpoint: provider.Endpoint(),
|
||||
Scopes: []string{oidc.ScopeOpenID, "profile"},
|
||||
},
|
||||
db: db,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// VerifyIDToken verifies that an *oauth2.Token is a valid *oidc.IDToken.
|
||||
func (a *Authenticator) VerifyIDToken(ctx context.Context, token *oauth2.Token) (*oidc.IDToken, error) {
|
||||
rawIDToken, ok := token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
return nil, errors.New("no id_token field in oauth2 token")
|
||||
}
|
||||
|
||||
oidcConfig := &oidc.Config{
|
||||
ClientID: a.ClientID,
|
||||
}
|
||||
|
||||
return a.Verifier(oidcConfig).Verify(ctx, rawIDToken)
|
||||
}
|
||||
|
||||
// NewState creates a new state for logging in, saving it in the database.
|
||||
func (a *Authenticator) NewState(ctx context.Context) ([32]byte, error) {
|
||||
state, err := generateRandomState()
|
||||
if err != nil {
|
||||
return state, fmt.Errorf("failed to generate random state: %w", err)
|
||||
}
|
||||
|
||||
if _, err = a.db.Exec(
|
||||
ctx,
|
||||
"INSERT INTO oauth_login_states (state) VALUES (@state)",
|
||||
pgx.NamedArgs{
|
||||
"state": state[:],
|
||||
},
|
||||
); err != nil {
|
||||
return state, fmt.Errorf("failed to execute query: %w", err)
|
||||
}
|
||||
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func generateRandomState() ([32]byte, error) {
|
||||
var b [32]byte
|
||||
_, err := rand.Read(b[:])
|
||||
return b, err
|
||||
}
|
||||
|
||||
// GetStateExpiration get's the oauth state's expiration
|
||||
// func (a *Authenticator) GetStateExpiration(ctx context.Context, state [32]byte) (time.Time, error) {
|
||||
func (a *Authenticator) GetStateExpiration(ctx context.Context, state string) (time.Time, error) {
|
||||
rows, err := a.db.Query(
|
||||
ctx,
|
||||
`SELECT expiration from oauth_login_states WHERE state = ('\x' || @state)::BYTEA`,
|
||||
pgx.NamedArgs{
|
||||
//"state": state[:],
|
||||
"state": state,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("failed to perform query: %w", err)
|
||||
}
|
||||
|
||||
exp, err := pgx.CollectExactlyOneRow(rows, pgx.RowTo[time.Time])
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return time.Time{}, consts.ErrNotFound
|
||||
}
|
||||
|
||||
return time.Time{}, fmt.Errorf("failed to scan row: %w", err)
|
||||
}
|
||||
|
||||
return exp, nil
|
||||
}
|
||||
|
||||
func (a *Authenticator) GetLogoutURL(requestHost string) *url.URL {
|
||||
return &url.URL{
|
||||
Scheme: "https",
|
||||
Host: AUTH0_DOMAIN,
|
||||
Path: "/v2/logout",
|
||||
RawQuery: url.Values{
|
||||
"returnTo": {
|
||||
(&url.URL{
|
||||
Scheme: "https",
|
||||
Host: requestHost,
|
||||
}).String(),
|
||||
},
|
||||
"client_id": {AUTH0_CLIENT_ID},
|
||||
}.Encode(),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Authenticator) Exchange(ctx context.Context, state, code string) (accessToken string, expiration time.Time, err error) {
|
||||
// validate state
|
||||
|
||||
if exp, err := a.GetStateExpiration(ctx, state); errors.Is(err, consts.ErrNotFound) {
|
||||
return "", time.Time{}, fmt.Errorf("invalid state: %w", consts.ErrNotFound)
|
||||
} else if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("failed to load state expiration: %w", err)
|
||||
} else if exp.Before(time.Now()) {
|
||||
return "", time.Time{}, fmt.Errorf("invalid state: state expired")
|
||||
}
|
||||
|
||||
// obtain token and profile
|
||||
|
||||
token, err := a.Config.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("failed to exchange an authorization code for a token: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("TOKEN:", token)
|
||||
|
||||
idToken, err := a.VerifyIDToken(ctx, token)
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("failed to verify ID Token: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("ID TOKEN:", idToken)
|
||||
|
||||
// claims []byte
|
||||
|
||||
var claims map[string]any
|
||||
if err := idToken.Claims(&claims); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("Failed to obtain id token claims: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("CUSTOM CLAIMS / PROFILE:", claims)
|
||||
|
||||
claimsJSON, _ := json.Marshal(claims)
|
||||
|
||||
if _, err := a.db.Exec(
|
||||
ctx,
|
||||
`
|
||||
INSERT INTO oauth_tokens (
|
||||
access_token,
|
||||
token_type,
|
||||
refresh_token,
|
||||
expiry,
|
||||
|
||||
id_token_issuer,
|
||||
id_token_audience,
|
||||
id_token_subject,
|
||||
id_token_expiry,
|
||||
id_token_issued_at,
|
||||
id_token_nonce,
|
||||
id_token_access_token_hash,
|
||||
|
||||
claims
|
||||
)
|
||||
VALUES (
|
||||
@access_token,
|
||||
@token_type,
|
||||
@refresh_token,
|
||||
@expiry,
|
||||
|
||||
@id_token_issuer,
|
||||
@id_token_audience,
|
||||
@id_token_subject,
|
||||
@id_token_expiry,
|
||||
@id_token_issued_at,
|
||||
@id_token_nonce,
|
||||
@id_token_access_token_hash,
|
||||
|
||||
@claims
|
||||
)
|
||||
`,
|
||||
pgx.NamedArgs{
|
||||
"access_token": token.AccessToken,
|
||||
"token_type": token.TokenType,
|
||||
"refresh_token": token.RefreshToken,
|
||||
"expiry": token.Expiry,
|
||||
|
||||
"id_token_issuer": idToken.Issuer,
|
||||
"id_token_audience": pgtype.FlatArray[string](idToken.Audience),
|
||||
"id_token_subject": idToken.Subject,
|
||||
"id_token_expiry": idToken.Expiry,
|
||||
"id_token_issued_at": idToken.IssuedAt,
|
||||
"id_token_nonce": idToken.Nonce,
|
||||
"id_token_access_token_hash": idToken.AccessTokenHash,
|
||||
|
||||
"claims": json.RawMessage(claimsJSON),
|
||||
},
|
||||
); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("failed to perform query to save tokens: %w", err)
|
||||
}
|
||||
|
||||
return token.AccessToken, token.Expiry.UTC(), nil
|
||||
}
|
||||
|
||||
// TODO: need to automatically clean up expired tokens
|
||||
func (a *Authenticator) DeleteOAuthTokens(ctx context.Context, accessToken string) error {
|
||||
_, err := a.db.Exec(ctx, "DELETE FROM oauth_tokens WHERE access_token = @access_token", pgx.NamedArgs{"access_token": accessToken})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to perform query: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Authenticator) GetAccessTokenClaimsAndExpiration(ctx context.Context, accessToken string) (claims AccessTokenClaims, expiration time.Time, err error) {
|
||||
rows, err := a.db.Query(
|
||||
ctx,
|
||||
`
|
||||
SELECT
|
||||
expiry,
|
||||
claims
|
||||
FROM
|
||||
oauth_tokens
|
||||
WHERE
|
||||
access_token = @access_token
|
||||
`,
|
||||
pgx.NamedArgs{
|
||||
"access_token": accessToken,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return AccessTokenClaims{}, time.Time{}, fmt.Errorf("failed to perform query: %w", err)
|
||||
}
|
||||
|
||||
type Row struct {
|
||||
Expiry time.Time
|
||||
Claims json.RawMessage
|
||||
}
|
||||
|
||||
r, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByNameLax[Row])
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return AccessTokenClaims{}, time.Time{}, consts.ErrNotFound
|
||||
}
|
||||
return AccessTokenClaims{}, time.Time{}, fmt.Errorf("failed to scan row: %w", err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(r.Claims, &claims); err != nil {
|
||||
return AccessTokenClaims{}, time.Time{}, fmt.Errorf("failed to scan claims json: %w", err)
|
||||
}
|
||||
|
||||
return claims, r.Expiry, nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"ruben/inventory2/internal/consts"
|
||||
"ruben/inventory2/internal/domains/authentication"
|
||||
)
|
||||
|
||||
// just keep this around long enough for testing auth middleware..
|
||||
func (s *Server) testAuthEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Println("SUCCESS:", getCustomClaims(r.Context()))
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
type customClaimsKey struct{}
|
||||
|
||||
// auth middleware to verify access_token cookie and set custom claims in the request context
|
||||
func (s *Server) authenticate(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ck, err := r.Cookie("access_token")
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
claims, expiration, err := s.auth.GetAccessTokenClaimsAndExpiration(ctx, ck.Value)
|
||||
if err != nil {
|
||||
if errors.Is(err, consts.ErrNotFound) {
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, fmt.Sprintf("failed to authenticate: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if expiration.Before(time.Now()) {
|
||||
deleteCookieInResponse(w, "access_token")
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
h.ServeHTTP(w, r.WithContext(context.WithValue(ctx, customClaimsKey{}, claims)))
|
||||
})
|
||||
}
|
||||
|
||||
// get custom claims from request context
|
||||
func getCustomClaims(ctx context.Context) authentication.AccessTokenClaims {
|
||||
c, _ := ctx.Value(customClaimsKey{}).(authentication.AccessTokenClaims)
|
||||
return c
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package site
|
||||
|
||||
import "net/http"
|
||||
|
||||
func deleteCookieInResponse(w http.ResponseWriter, name string) {
|
||||
w.Header().Set("Set-Cookie", (&http.Cookie{
|
||||
Name: name,
|
||||
Path: "/",
|
||||
MaxAge: -1, // expire the cookie
|
||||
}).String())
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// GET /login
|
||||
func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
state, err := s.auth.NewState(ctx)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to generate random state: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
base64EncodedState := fmt.Sprintf("%x", state[:])
|
||||
|
||||
http.Redirect(w, r, s.auth.AuthCodeURL(base64EncodedState), http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
// POST /login
|
||||
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
email := r.FormValue("email")
|
||||
if email == "" {
|
||||
http.Error(w, "no email provided", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
acct, err := s.accts.GetAccountByEmail(ctx, email)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to create account: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
//http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||
http.Redirect(w, r, fmt.Sprintf("/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// GET /login/callback
|
||||
func (s *Server) loginCallback(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
q := r.URL.Query()
|
||||
|
||||
// obtain token and profile
|
||||
|
||||
accessToken, expiration, err := s.auth.Exchange(ctx, q.Get("state"), q.Get("code"))
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to exchange an authorization code for a token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// set access_token cookie and redirect to a reasonable place
|
||||
|
||||
w.Header().Set("Set-Cookie", (&http.Cookie{
|
||||
Name: "access_token",
|
||||
Value: accessToken,
|
||||
Path: "/",
|
||||
Expires: expiration,
|
||||
MaxAge: 0, // using Expiration instead
|
||||
Secure: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
}).String())
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
// GET /logout
|
||||
func (s *Server) logoutPage(w http.ResponseWriter, r *http.Request) {
|
||||
host := r.Header.Get("X-Forwarded-Host")
|
||||
if host == "" {
|
||||
host = r.Host
|
||||
}
|
||||
|
||||
deleteCookieInResponse(w, "access_token")
|
||||
|
||||
if ck, err := r.Cookie("access_token"); err == nil && ck != nil {
|
||||
if err := s.auth.DeleteOAuthTokens(r.Context(), ck.Value); err != nil {
|
||||
fmt.Println("[ERROR] failed to delete auth token:", err)
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, s.auth.GetLogoutURL(host).String(), http.StatusTemporaryRedirect)
|
||||
}
|
||||
+102
-194
@@ -5,234 +5,142 @@ import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/angelbeltran/templater"
|
||||
|
||||
"ruben/inventory2/internal/domains/accounts"
|
||||
"ruben/inventory2/internal/domains/authentication"
|
||||
etsy_platform "ruben/inventory2/internal/domains/platforms/etsy"
|
||||
"ruben/inventory2/internal/domains/raw_events"
|
||||
)
|
||||
|
||||
func NewSiteHandler(
|
||||
dir string,
|
||||
type Server struct {
|
||||
mux *http.ServeMux
|
||||
contentDir string
|
||||
templater *templater.Templater
|
||||
rawEvents *raw_events.Store
|
||||
accts *accounts.Store
|
||||
etsy *etsy_platform.Platform
|
||||
auth *authentication.Authenticator
|
||||
}
|
||||
|
||||
func NewServer(
|
||||
contentDir string,
|
||||
rawEvents *raw_events.Store,
|
||||
accts *accounts.Store,
|
||||
etsy *etsy_platform.Platform,
|
||||
) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
auth *authentication.Authenticator,
|
||||
) *Server {
|
||||
s := &Server{
|
||||
mux: http.NewServeMux(),
|
||||
contentDir: contentDir,
|
||||
templater: templater.NewTemplater(
|
||||
contentDir+"/templates",
|
||||
func() template.FuncMap {
|
||||
return template.FuncMap{
|
||||
"buildSitePath": func(parts ...any) string {
|
||||
strParts := make([]string, len(parts))
|
||||
for i, p := range parts {
|
||||
strParts[i] = fmt.Sprint(p)
|
||||
}
|
||||
|
||||
// TODO: make "/site" dynamic somehow
|
||||
//return path.Join(append([]string{"/site"}, strParts...)...)
|
||||
return path.Join(strParts...)
|
||||
},
|
||||
"splitPath": func(p string) []string {
|
||||
if p == "" {
|
||||
return nil
|
||||
}
|
||||
return strings.Split(strings.TrimSuffix(strings.TrimPrefix(p, "/"), "/"), "/")
|
||||
},
|
||||
|
||||
"prettyPrintJSON": func(j json.RawMessage) string {
|
||||
b, err := json.MarshalIndent(j, " ", "")
|
||||
if err != nil {
|
||||
return string(j)
|
||||
}
|
||||
return string(b)
|
||||
},
|
||||
|
||||
"parseInt64": func(s string) (int64, error) {
|
||||
return strconv.ParseInt(s, 10, 64)
|
||||
},
|
||||
|
||||
"addInt": func(a, b int) int {
|
||||
return a + b
|
||||
},
|
||||
"subInt": func(a, b int) int {
|
||||
return a - b
|
||||
},
|
||||
"multInt": func(a, b int) int {
|
||||
return a * b
|
||||
},
|
||||
}
|
||||
},
|
||||
),
|
||||
rawEvents: rawEvents,
|
||||
accts: accts,
|
||||
etsy: etsy,
|
||||
auth: auth,
|
||||
}
|
||||
|
||||
// api routes
|
||||
|
||||
mux.HandleFunc("POST /accounts", func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
email := r.FormValue("email")
|
||||
if email == "" {
|
||||
http.Error(w, "no email provided", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.mux.HandleFunc("GET /login", s.loginPage)
|
||||
s.mux.HandleFunc("GET /login/callback", s.loginCallback)
|
||||
s.mux.HandleFunc("GET /logout", s.logoutPage)
|
||||
|
||||
acct, err := accts.CreateAccount(ctx, email)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to create account: %w", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// TODO: eliminate once no longer used.
|
||||
s.mux.HandleFunc("POST /login", s.login)
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||
})
|
||||
// TODO: when a user is created, we should make an account for them that is associated with their openid subject.
|
||||
// - then this can go away
|
||||
s.mux.HandleFunc("POST /accounts", s.createAccount)
|
||||
|
||||
mux.HandleFunc("POST /log-in", func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
email := r.FormValue("email")
|
||||
if email == "" {
|
||||
http.Error(w, "no email provided", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// TODO: test the new auth middleware
|
||||
s.mux.Handle("GET /test-auth", s.authenticate(http.HandlerFunc(s.testAuthEndpoint)))
|
||||
|
||||
acct, err := accts.GetAccountByEmail(ctx, email)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to create account: %w", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// webpage content
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||
})
|
||||
|
||||
// non-html routes
|
||||
|
||||
scfs := http.FileServer(http.Dir(dir + "/scripts"))
|
||||
mux.Handle("/scripts/", http.StripPrefix("/scripts", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
scfs := http.FileServer(http.Dir(contentDir + "/scripts"))
|
||||
s.mux.Handle("GET /scripts/", http.StripPrefix("/scripts", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/javascript")
|
||||
if path.Ext(r.URL.Path) == ".gz" {
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
}
|
||||
scfs.ServeHTTP(w, r)
|
||||
})))
|
||||
mux.Handle("/styles/", http.StripPrefix("/styles", http.FileServer(http.Dir(dir+"/styles"))))
|
||||
s.mux.Handle("GET /styles/", http.StripPrefix("/styles", http.FileServer(http.Dir(contentDir+"/styles"))))
|
||||
|
||||
// html page routes
|
||||
s.mux.HandleFunc("GET /", s.serveTemplates)
|
||||
|
||||
tmplr := templater.NewTemplater(
|
||||
dir+"/templates",
|
||||
func() template.FuncMap {
|
||||
return template.FuncMap{
|
||||
"buildSitePath": func(parts ...any) string {
|
||||
strParts := make([]string, len(parts))
|
||||
for i, p := range parts {
|
||||
strParts[i] = fmt.Sprint(p)
|
||||
}
|
||||
|
||||
// TODO: make "/site" dynamic somehow
|
||||
return path.Join(append([]string{"/site"}, strParts...)...)
|
||||
},
|
||||
"splitPath": func(p string) []string {
|
||||
if p == "" {
|
||||
return nil
|
||||
}
|
||||
return strings.Split(strings.TrimSuffix(strings.TrimPrefix(p, "/"), "/"), "/")
|
||||
},
|
||||
|
||||
"prettyPrintJSON": func(j json.RawMessage) string {
|
||||
b, err := json.MarshalIndent(j, " ", "")
|
||||
if err != nil {
|
||||
return string(j)
|
||||
}
|
||||
return string(b)
|
||||
},
|
||||
|
||||
"parseInt64": func(s string) (int64, error) {
|
||||
return strconv.ParseInt(s, 10, 64)
|
||||
},
|
||||
|
||||
"addInt": func(a, b int) int {
|
||||
return a + b
|
||||
},
|
||||
"subInt": func(a, b int) int {
|
||||
return a - b
|
||||
},
|
||||
"multInt": func(a, b int) int {
|
||||
return a * b
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
name, pathParams := getPageTemplateNameForURL(r.URL)
|
||||
b, err := tmplr.ExecutePage(
|
||||
name,
|
||||
"Request",
|
||||
r,
|
||||
// add services here
|
||||
"RawEvents",
|
||||
rawEvents.WithContext(ctx),
|
||||
"URLCalc",
|
||||
newURLCalculator(r.URL),
|
||||
"PathParams",
|
||||
pathParams,
|
||||
"Accounts",
|
||||
accts.WithContext(ctx),
|
||||
"Etsy",
|
||||
etsy.WithContext(ctx),
|
||||
)
|
||||
if err != nil {
|
||||
// TODO: handle 'not found' as a 404?
|
||||
fmt.Println("[ERROR]: failed to load or parse layout template:", err)
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
w.Write(b)
|
||||
})
|
||||
|
||||
return mux
|
||||
return s
|
||||
}
|
||||
|
||||
// TODO: clean this up...
|
||||
// TODO: somehow tell what the path params are and pass them up.
|
||||
// - then consider pushing this functionality into the template library.
|
||||
//
|
||||
// getPageTemplateNameForURL eliminate any trailing .html or /, and checks for any
|
||||
// file with path parameters in the name, eg '{abc}.html.tmpl', prefering exact filename matches.
|
||||
func getPageTemplateNameForURL(u *url.URL) (name string, params map[string]string) {
|
||||
fp := strings.TrimPrefix(strings.TrimSuffix(strings.TrimSuffix(u.Path, ".html"), "/"), "/")
|
||||
if fp == "" {
|
||||
// "/" maps to "/index"
|
||||
fp = "index"
|
||||
// http.Handler implementation
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.mux.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// POST /accounts
|
||||
func (s *Server) createAccount(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
email := r.FormValue("email")
|
||||
if email == "" {
|
||||
http.Error(w, "no email provided", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
fpParts := strings.Split(fp, "/")
|
||||
res := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(fpParts)
|
||||
for _, combs := range res {
|
||||
const pageBodiesPrefix = "internal/site/templates/page_bodies"
|
||||
pattern := path.Join(pageBodiesPrefix, path.Join(combs...)) + ".html.tmpl"
|
||||
|
||||
matches, _ := filepath.Glob(pattern)
|
||||
if len(matches) == 0 {
|
||||
pattern := path.Join(pageBodiesPrefix, path.Join(combs...), "index") + ".html.tmpl"
|
||||
matches, _ = filepath.Glob(pattern)
|
||||
}
|
||||
if len(matches) > 0 {
|
||||
match := matches[0]
|
||||
name = strings.TrimPrefix(strings.TrimSuffix(match, ".html.tmpl"), pageBodiesPrefix+"/")
|
||||
|
||||
patternParts := strings.Split(name, "/")
|
||||
params = make(map[string]string)
|
||||
for i, pp := range patternParts {
|
||||
if strings.HasPrefix(pp, "{") && strings.HasSuffix(pp, "}") {
|
||||
params[pp[1:len(pp)-1]] = fpParts[i]
|
||||
}
|
||||
}
|
||||
|
||||
return name, params
|
||||
}
|
||||
acct, err := s.accts.CreateAccount(ctx, email)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to create account: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
return fp, nil
|
||||
}
|
||||
|
||||
func getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts []string) [][]string {
|
||||
switch len(filepathParts) {
|
||||
case 0:
|
||||
return nil
|
||||
case 1:
|
||||
return [][]string{
|
||||
[]string{filepathParts[0]},
|
||||
[]string{"{*}"},
|
||||
}
|
||||
default:
|
||||
tailCombs := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts[1:])
|
||||
|
||||
combs := make([][]string, 2*len(tailCombs))
|
||||
for i, c := range tailCombs {
|
||||
combs[i*2] = append([]string{filepathParts[0]}, c...)
|
||||
combs[i*2+1] = append([]string{"{*}"}, c...)
|
||||
}
|
||||
|
||||
return combs
|
||||
}
|
||||
}
|
||||
|
||||
type URLCalculator struct {
|
||||
url *url.URL
|
||||
}
|
||||
|
||||
func newURLCalculator(u *url.URL) URLCalculator {
|
||||
cpy := *u
|
||||
return URLCalculator{
|
||||
url: &cpy,
|
||||
}
|
||||
}
|
||||
|
||||
func (c URLCalculator) SetQueryParam(k string, v any) string {
|
||||
u := *c.url
|
||||
q := u.Query()
|
||||
q.Set(k, fmt.Sprint(v))
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
return u.String()
|
||||
//http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||
http.Redirect(w, r, fmt.Sprintf("/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// GET /
|
||||
func (s *Server) serveTemplates(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
name, pathParams := getPageTemplateNameForURL(r.URL)
|
||||
b, err := s.templater.ExecutePage(
|
||||
name,
|
||||
"Request",
|
||||
r,
|
||||
// add services here
|
||||
"RawEvents",
|
||||
s.rawEvents.WithContext(ctx),
|
||||
"URLCalc",
|
||||
newURLCalculator(r.URL),
|
||||
"PathParams",
|
||||
pathParams,
|
||||
"Accounts",
|
||||
s.accts.WithContext(ctx),
|
||||
"Etsy",
|
||||
s.etsy.WithContext(ctx),
|
||||
)
|
||||
if err != nil {
|
||||
// TODO: handle 'not found' as a 404?
|
||||
fmt.Println("[ERROR]: failed to load or parse layout template:", err)
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
// TODO: clean this up...
|
||||
// TODO: somehow tell what the path params are and pass them up.
|
||||
// - then consider pushing this functionality into the template library.
|
||||
//
|
||||
// getPageTemplateNameForURL eliminate any trailing .html or /, and checks for any
|
||||
// file with path parameters in the name, eg '{abc}.html.tmpl', prefering exact filename matches.
|
||||
func getPageTemplateNameForURL(u *url.URL) (name string, params map[string]string) {
|
||||
fp := strings.TrimPrefix(strings.TrimSuffix(strings.TrimSuffix(u.Path, ".html"), "/"), "/")
|
||||
if fp == "" {
|
||||
// "/" maps to "/index"
|
||||
fp = "index"
|
||||
}
|
||||
|
||||
fpParts := strings.Split(fp, "/")
|
||||
res := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(fpParts)
|
||||
for _, combs := range res {
|
||||
const pageBodiesPrefix = "internal/site/templates/page_bodies"
|
||||
pattern := path.Join(pageBodiesPrefix, path.Join(combs...)) + ".html.tmpl"
|
||||
|
||||
matches, _ := filepath.Glob(pattern)
|
||||
if len(matches) == 0 {
|
||||
pattern := path.Join(pageBodiesPrefix, path.Join(combs...), "index") + ".html.tmpl"
|
||||
matches, _ = filepath.Glob(pattern)
|
||||
}
|
||||
if len(matches) > 0 {
|
||||
match := matches[0]
|
||||
name = strings.TrimPrefix(strings.TrimSuffix(match, ".html.tmpl"), pageBodiesPrefix+"/")
|
||||
|
||||
patternParts := strings.Split(name, "/")
|
||||
params = make(map[string]string)
|
||||
for i, pp := range patternParts {
|
||||
if strings.HasPrefix(pp, "{") && strings.HasSuffix(pp, "}") {
|
||||
params[pp[1:len(pp)-1]] = fpParts[i]
|
||||
}
|
||||
}
|
||||
|
||||
return name, params
|
||||
}
|
||||
}
|
||||
|
||||
return fp, nil
|
||||
}
|
||||
|
||||
func getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts []string) [][]string {
|
||||
switch len(filepathParts) {
|
||||
case 0:
|
||||
return nil
|
||||
case 1:
|
||||
return [][]string{
|
||||
[]string{filepathParts[0]},
|
||||
[]string{"{*}"},
|
||||
}
|
||||
default:
|
||||
tailCombs := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts[1:])
|
||||
|
||||
combs := make([][]string, 2*len(tailCombs))
|
||||
for i, c := range tailCombs {
|
||||
combs[i*2] = append([]string{filepathParts[0]}, c...)
|
||||
combs[i*2+1] = append([]string{"{*}"}, c...)
|
||||
}
|
||||
|
||||
return combs
|
||||
}
|
||||
}
|
||||
|
||||
type URLCalculator struct {
|
||||
url *url.URL
|
||||
}
|
||||
|
||||
func newURLCalculator(u *url.URL) URLCalculator {
|
||||
cpy := *u
|
||||
return URLCalculator{
|
||||
url: &cpy,
|
||||
}
|
||||
}
|
||||
|
||||
func (c URLCalculator) SetQueryParam(k string, v any) string {
|
||||
u := *c.url
|
||||
q := u.Query()
|
||||
q.Set(k, fmt.Sprint(v))
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
return u.String()
|
||||
}
|
||||
@@ -1,22 +1,28 @@
|
||||
<nav>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="{{ buildSitePath }}">
|
||||
<a href="/">
|
||||
Home
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<li>
|
||||
<a href="{{ buildSitePath "sign-up" }}">
|
||||
<a href="/sign-up">
|
||||
Sign Up
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<li>
|
||||
<a href="{{ buildSitePath "log-in" }}">
|
||||
<a href="/login">
|
||||
Log In
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<li>
|
||||
<a href="/logout">
|
||||
Log Out
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
<head>
|
||||
<title>WIP</title>
|
||||
|
||||
<link rel="stylesheet" href="/site/styles/index.css">
|
||||
<link rel="stylesheet" href="/styles/index.css">
|
||||
|
||||
<script src="/site/scripts/htmx.min.js.gz"></script>
|
||||
<script src="/site/scripts/_hyperscript.min.js.gz"></script>
|
||||
<script src="/scripts/htmx.min.js.gz"></script>
|
||||
<script src="/scripts/_hyperscript.min.js.gz"></script>
|
||||
|
||||
{{/* This is where the page_head template will be inserted into the page */}}
|
||||
{{- block "head" . }}{{ end }}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
{{ componentBody "nav_bar" }}
|
||||
|
||||
|
||||
<h1>Account: {{ .PathParams.acctID }}</h1>
|
||||
|
||||
{{- $acctID := parseInt64 .PathParams.acctID }}
|
||||
{{- $acct := (.Accounts.GetAccount $acctID) }}
|
||||
|
||||
Email: {{ (.Accounts.GetAccount $acctID).Email }}
|
||||
<h1>Account: {{ $acct.Email }} (id: {{ $acctID }})</h1>
|
||||
|
||||
{{- $etsyUser := .Etsy.GetUserPointerByAccountID $acctID }}
|
||||
{{- if $etsyUser }}
|
||||
|
||||
@@ -2,4 +2,6 @@
|
||||
|
||||
<h1>Home</h1>
|
||||
|
||||
<h2><a href="sign-up">Sign Up!</a></h2>
|
||||
<h2><a href="/sign-up">Sign Up!</a></h2>
|
||||
|
||||
<h2><a href="/test-auth">Test Auth</a></h2>
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
<h1>Log In</h1>
|
||||
|
||||
<form action="log-in" method="post">
|
||||
<form action="login" method="post">
|
||||
<label>
|
||||
Email:
|
||||
<input type="text" required name="email" />
|
||||
@@ -102,7 +102,7 @@ func NewWebhookHandler(
|
||||
|
||||
// TODO: response with a redirect to the user's account page (SUCCESS - new sign up or login)!
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acctID), http.StatusSeeOther)
|
||||
http.Redirect(w, r, fmt.Sprintf("/accounts/%d", acctID), http.StatusSeeOther)
|
||||
})
|
||||
|
||||
return mux
|
||||
|
||||
Reference in New Issue
Block a user