Compare commits
7 Commits
v0.1.6
...
f4d5a52cf9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4d5a52cf9 | ||
| 8789c5414e | |||
|
|
7a1c91c858 | ||
|
|
2ad0abaf44 | ||
|
|
b1f754831a | ||
| 93147ffc46 | |||
|
|
72d31fd143 |
@@ -11,6 +11,10 @@
|
|||||||
# PORT=7331
|
# PORT=7331
|
||||||
|
|
||||||
# Goose CLI migration config (only needed for running goose manually)
|
# Goose CLI migration config (only needed for running goose manually)
|
||||||
|
# Gitea API token for downloading datastar-pro from private repo (CI/Docker only).
|
||||||
|
# Not needed for local dev — falls back to copying from ../optional/.
|
||||||
|
# VENDOR_TOKEN=
|
||||||
|
|
||||||
GOOSE_DRIVER=sqlite3
|
GOOSE_DRIVER=sqlite3
|
||||||
GOOSE_DBSTRING=data/games.db?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)
|
GOOSE_DBSTRING=data/games.db?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)
|
||||||
GOOSE_MIGRATION_DIR=db/migrations
|
GOOSE_MIGRATION_DIR=db/migrations
|
||||||
|
|||||||
@@ -61,8 +61,13 @@ jobs:
|
|||||||
mkdir -p $DEPLOY_DIR/data
|
mkdir -p $DEPLOY_DIR/data
|
||||||
|
|
||||||
- name: Rebuild and restart
|
- name: Rebuild and restart
|
||||||
|
env:
|
||||||
|
VENDOR_TOKEN: ${{ secrets.VENDOR_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
cd $DEPLOY_DIR
|
cd $DEPLOY_DIR
|
||||||
VERSION=$(git describe --tags --always)
|
VERSION=$(git describe --tags --always)
|
||||||
COMMIT=$(git rev-parse --short HEAD)
|
COMMIT=$(git rev-parse --short HEAD)
|
||||||
VERSION=$VERSION COMMIT=$COMMIT docker compose up -d --build --remove-orphans
|
VERSION=$VERSION COMMIT=$COMMIT VENDOR_TOKEN=$VENDOR_TOKEN docker compose up -d --build --remove-orphans
|
||||||
|
|
||||||
|
- name: Prune unused images
|
||||||
|
run: docker image prune -f
|
||||||
|
|||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -27,6 +27,10 @@
|
|||||||
*_templ.go
|
*_templ.go
|
||||||
assets/css/output.css
|
assets/css/output.css
|
||||||
|
|
||||||
|
# Downloaded client-side libs (fetched by cmd/downloader)
|
||||||
|
assets/js/datastar/*
|
||||||
|
assets/css/daisyui/*
|
||||||
|
|
||||||
# Deploy scripts and configs
|
# Deploy scripts and configs
|
||||||
!deploy/*.sh
|
!deploy/*.sh
|
||||||
!deploy/*.service
|
!deploy/*.service
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ COPY go.mod go.sum ./
|
|||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
|
RUN --mount=type=secret,id=vendor_token \
|
||||||
|
VENDOR_TOKEN=$(cat /run/secrets/vendor_token) \
|
||||||
|
go run cmd/downloader/main.go
|
||||||
|
|
||||||
RUN go tool templ generate
|
RUN go tool templ generate
|
||||||
RUN go tool gotailwind -i assets/css/input.css -o assets/css/output.css --minify
|
RUN go tool gotailwind -i assets/css/input.css -o assets/css/output.css --minify
|
||||||
RUN --mount=type=cache,target=/root/.cache/go-build \
|
RUN --mount=type=cache,target=/root/.cache/go-build \
|
||||||
|
|||||||
@@ -2,9 +2,12 @@ version: "3"
|
|||||||
|
|
||||||
tasks:
|
tasks:
|
||||||
download:
|
download:
|
||||||
desc: Download latest client-side libs
|
desc: Download pinned client-side libs
|
||||||
cmds:
|
cmds:
|
||||||
- go run cmd/downloader/main.go
|
- go run cmd/downloader/main.go
|
||||||
|
status:
|
||||||
|
- test -f assets/js/datastar/datastar.js
|
||||||
|
- test -f assets/css/daisyui/daisyui.js
|
||||||
|
|
||||||
build:templ:
|
build:templ:
|
||||||
desc: Compile .templ files to Go
|
desc: Compile .templ files to Go
|
||||||
@@ -31,6 +34,7 @@ tasks:
|
|||||||
cmds:
|
cmds:
|
||||||
- go build -o bin/games .
|
- go build -o bin/games .
|
||||||
deps:
|
deps:
|
||||||
|
- download
|
||||||
- build:templ
|
- build:templ
|
||||||
- build:styles
|
- build:styles
|
||||||
|
|
||||||
@@ -58,6 +62,7 @@ tasks:
|
|||||||
live:
|
live:
|
||||||
desc: Dev mode with hot-reload
|
desc: Dev mode with hot-reload
|
||||||
deps:
|
deps:
|
||||||
|
- download
|
||||||
- live:templ
|
- live:templ
|
||||||
- live:styles
|
- live:styles
|
||||||
- live:server
|
- live:server
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,8 +1,8 @@
|
|||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
|
|
||||||
@source not "./daisyui{,*}.mjs";
|
@source not "./daisyui/daisyui{,*}.js";
|
||||||
@plugin "./daisyui.mjs";
|
@plugin "./daisyui/daisyui.js";
|
||||||
@plugin "./daisyui-theme.mjs" {
|
@plugin "./daisyui/daisyui-theme.js" {
|
||||||
name: "stealth";
|
name: "stealth";
|
||||||
default: true;
|
default: true;
|
||||||
color-scheme: light;
|
color-scheme: light;
|
||||||
|
|||||||
1
assets/js/README.md
Normal file
1
assets/js/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
Downloaded by cmd/downloader at build time.
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,30 +1,20 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sync"
|
"sync"
|
||||||
)
|
|
||||||
|
|
||||||
// Asset directories, relative to project root.
|
"github.com/ryanhamamura/games/assets"
|
||||||
const (
|
|
||||||
jsDir = "assets/js"
|
|
||||||
cssDir = "assets/css"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// files maps download URLs to local destination paths.
|
|
||||||
var files = map[string]string{
|
|
||||||
"https://raw.githubusercontent.com/starfederation/datastar/main/bundles/datastar.js": jsDir + "/datastar.js",
|
|
||||||
"https://raw.githubusercontent.com/starfederation/datastar/main/bundles/datastar.js.map": jsDir + "/datastar.js.map",
|
|
||||||
"https://github.com/saadeghi/daisyui/releases/latest/download/daisyui.mjs": cssDir + "/daisyui.mjs",
|
|
||||||
"https://github.com/saadeghi/daisyui/releases/latest/download/daisyui-theme.mjs": cssDir + "/daisyui-theme.mjs",
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if err := run(); err != nil {
|
if err := run(); err != nil {
|
||||||
slog.Error("failure", "error", err)
|
slog.Error("failure", "error", err)
|
||||||
@@ -32,16 +22,243 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pinned dependency versions — update these to upgrade.
|
||||||
|
const (
|
||||||
|
datastarVersion = "v1.0.0-RC.8" // Pro build — fetched from private Gitea repo
|
||||||
|
daisyuiVersion = "v5.5.19"
|
||||||
|
)
|
||||||
|
|
||||||
|
// dependencies tracks pinned versions alongside their GitHub coordinates
|
||||||
|
// so the version check can look up the latest release for each.
|
||||||
|
var dependencies = []dependency{
|
||||||
|
{name: "datastar", owner: "starfederation", repo: "datastar", pinnedVersion: datastarVersion},
|
||||||
|
{name: "daisyui", owner: "saadeghi", repo: "daisyui", pinnedVersion: daisyuiVersion},
|
||||||
|
}
|
||||||
|
|
||||||
|
type dependency struct {
|
||||||
|
name string
|
||||||
|
owner string
|
||||||
|
repo string
|
||||||
|
pinnedVersion string
|
||||||
|
}
|
||||||
|
|
||||||
|
// datastar-pro sources, in order of preference.
|
||||||
|
const (
|
||||||
|
giteaRawURL = "https://gitea.adriatica.io/ryan/vendor-libs/raw/branch/main/datastar/datastar.js"
|
||||||
|
localFallbackPath = "../optional/web/resources/static/datastar/datastar.js"
|
||||||
|
)
|
||||||
|
|
||||||
func run() error {
|
func run() error {
|
||||||
dirs := []string{jsDir, cssDir}
|
jsDir := assets.DirectoryPath + "/js/datastar"
|
||||||
|
cssDir := assets.DirectoryPath + "/css/daisyui"
|
||||||
|
|
||||||
for _, dir := range dirs {
|
daisyuiBase := "https://github.com/saadeghi/daisyui/releases/download/" + daisyuiVersion + "/"
|
||||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
|
||||||
return fmt.Errorf("create directory %s: %w", dir, err)
|
downloads := map[string]string{
|
||||||
}
|
daisyuiBase + "daisyui.js": cssDir + "/daisyui.js",
|
||||||
|
daisyuiBase + "daisyui-theme.js": cssDir + "/daisyui-theme.js",
|
||||||
}
|
}
|
||||||
|
|
||||||
return download(files)
|
directories := []string{jsDir, cssDir}
|
||||||
|
|
||||||
|
if err := removeDirectories(directories); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := createDirectories(directories); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := acquireDatastar(jsDir + "/datastar.js"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := download(downloads); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
checkForUpdates()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// acquireDatastar fetches datastar-pro from the private Gitea repo when
|
||||||
|
// GITEA_TOKEN is set, otherwise copies from the local optional project.
|
||||||
|
func acquireDatastar(dest string) error {
|
||||||
|
if token := os.Getenv("VENDOR_TOKEN"); token != "" {
|
||||||
|
slog.Info("downloading datastar-pro from private repo...")
|
||||||
|
return downloadWithAuth(giteaRawURL, dest, token)
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("copying datastar-pro from local fallback...", "src", localFallbackPath)
|
||||||
|
return copyFile(localFallbackPath, dest)
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyFile(src, dest string) error {
|
||||||
|
in, err := os.Open(src) //nolint:gosec // paths are hardcoded constants
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("open %s: %w", src, err)
|
||||||
|
}
|
||||||
|
defer in.Close() //nolint:errcheck
|
||||||
|
|
||||||
|
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.Copy(out, in); err != nil {
|
||||||
|
out.Close() //nolint:errcheck
|
||||||
|
return fmt.Errorf("copy to %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := out.Close(); err != nil {
|
||||||
|
return fmt.Errorf("close %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadWithAuth(rawURL, dest, token string) error {
|
||||||
|
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create request for %s: %w", rawURL, err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "token "+token)
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(req) //nolint:gosec // URL is built from compile-time constants
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("GET %s: %w", rawURL, err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close() //nolint:errcheck
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return fmt.Errorf("GET %s: status %s", rawURL, resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.Copy(out, resp.Body); err != nil {
|
||||||
|
out.Close() //nolint:errcheck
|
||||||
|
return fmt.Errorf("write %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := out.Close(); err != nil {
|
||||||
|
return fmt.Errorf("close %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkForUpdates queries the GitHub releases API for each dependency
|
||||||
|
// and logs a notice if a newer version is available. Failures are
|
||||||
|
// logged but never cause the download to fail.
|
||||||
|
func checkForUpdates() {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
|
for _, dep := range dependencies {
|
||||||
|
wg.Go(func() {
|
||||||
|
latest, err := latestGitHubRelease(dep.owner, dep.repo)
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("could not check for updates", "dependency", dep.name, "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if latest != dep.pinnedVersion {
|
||||||
|
slog.Warn("newer version available",
|
||||||
|
"dependency", dep.name,
|
||||||
|
"pinned", dep.pinnedVersion,
|
||||||
|
"latest", latest,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
// githubRelease is the minimal subset of the GitHub releases API response we need.
|
||||||
|
type githubRelease struct {
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func latestGitHubRelease(owner, repo string) (string, error) {
|
||||||
|
u := &url.URL{
|
||||||
|
Scheme: "https",
|
||||||
|
Host: "api.github.com",
|
||||||
|
Path: fmt.Sprintf("/repos/%s/%s/releases/latest", owner, repo),
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("creating request: %w", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Accept", "application/vnd.github+json")
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(req) //nolint:gosec
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("fetching release: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close() //nolint:errcheck
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return "", fmt.Errorf("unexpected status %s", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
var release githubRelease
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
||||||
|
return "", fmt.Errorf("decoding response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return release.TagName, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeDirectories(dirs []string) error {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errCh := make(chan error, len(dirs))
|
||||||
|
|
||||||
|
for _, path := range dirs {
|
||||||
|
wg.Go(func() {
|
||||||
|
if err := os.RemoveAll(path); err != nil {
|
||||||
|
errCh <- fmt.Errorf("remove directory %s: %w", path, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
close(errCh)
|
||||||
|
|
||||||
|
var errs []error
|
||||||
|
for err := range errCh {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func createDirectories(dirs []string) error {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errCh := make(chan error, len(dirs))
|
||||||
|
|
||||||
|
for _, path := range dirs {
|
||||||
|
wg.Go(func() {
|
||||||
|
if err := os.MkdirAll(path, 0755); err != nil {
|
||||||
|
errCh <- fmt.Errorf("create directory %s: %w", path, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
close(errCh)
|
||||||
|
|
||||||
|
var errs []error
|
||||||
|
for err := range errCh {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func download(files map[string]string) error {
|
func download(files map[string]string) error {
|
||||||
@@ -71,15 +288,15 @@ func download(files map[string]string) error {
|
|||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadFile(url, dest string) error {
|
func downloadFile(rawURL, dest string) error {
|
||||||
resp, err := http.Get(url) //nolint:gosec,noctx // static URLs, simple tool
|
resp, err := http.Get(rawURL) //nolint:gosec,noctx // static URLs, simple tool
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("GET %s: %w", url, err)
|
return fmt.Errorf("GET %s: %w", rawURL, err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close() //nolint:errcheck
|
defer resp.Body.Close() //nolint:errcheck
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return fmt.Errorf("GET %s: status %s", url, resp.Status)
|
return fmt.Errorf("GET %s: status %s", rawURL, resp.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ services:
|
|||||||
args:
|
args:
|
||||||
VERSION: ${VERSION:-dev}
|
VERSION: ${VERSION:-dev}
|
||||||
COMMIT: ${COMMIT:-unknown}
|
COMMIT: ${COMMIT:-unknown}
|
||||||
|
secrets:
|
||||||
|
- vendor_token
|
||||||
container_name: games
|
container_name: games
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
@@ -16,3 +18,7 @@ services:
|
|||||||
- PORT=8080
|
- PORT=8080
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ./data:/data
|
||||||
|
|
||||||
|
secrets:
|
||||||
|
vendor_token:
|
||||||
|
environment: VENDOR_TOKEN
|
||||||
|
|||||||
@@ -3,10 +3,10 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
"github.com/alexedwards/scs/v2"
|
"github.com/alexedwards/scs/v2"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/starfederation/datastar-go/datastar"
|
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/auth"
|
"github.com/ryanhamamura/games/auth"
|
||||||
"github.com/ryanhamamura/games/db/repository"
|
"github.com/ryanhamamura/games/db/repository"
|
||||||
@@ -14,20 +14,15 @@ import (
|
|||||||
appsessions "github.com/ryanhamamura/games/sessions"
|
appsessions "github.com/ryanhamamura/games/sessions"
|
||||||
)
|
)
|
||||||
|
|
||||||
type LoginSignals struct {
|
func HandleLoginPage(sessions *scs.SessionManager) http.HandlerFunc {
|
||||||
Username string `json:"username"`
|
|
||||||
Password string `json:"password"` //nolint:gosec // form input, not stored
|
|
||||||
}
|
|
||||||
|
|
||||||
type RegisterSignals struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
Password string `json:"password"` //nolint:gosec // form input, not stored
|
|
||||||
Confirm string `json:"confirm"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func HandleLoginPage() http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
if err := pages.LoginPage().Render(r.Context(), w); err != nil {
|
// Capture return_url so we can redirect back after login
|
||||||
|
if returnURL := r.URL.Query().Get("return_url"); returnURL != "" {
|
||||||
|
sessions.Put(r.Context(), "return_url", returnURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
errorMsg := r.URL.Query().Get("error")
|
||||||
|
if err := pages.LoginPage(errorMsg).Render(r.Context(), w); err != nil {
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -35,7 +30,8 @@ func HandleLoginPage() http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleRegisterPage() http.HandlerFunc {
|
func HandleRegisterPage() http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
if err := pages.RegisterPage().Render(r.Context(), w); err != nil {
|
errorMsg := r.URL.Query().Get("error")
|
||||||
|
if err := pages.RegisterPage(errorMsg).Render(r.Context(), w); err != nil {
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -43,25 +39,21 @@ func HandleRegisterPage() http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleLogin(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
|
func HandleLogin(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
var signals LoginSignals
|
r.Body = http.MaxBytesReader(w, r.Body, 1024)
|
||||||
if err := datastar.ReadSignals(r, &signals); err != nil {
|
username := r.FormValue("username")
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
password := r.FormValue("password")
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sse := datastar.NewSSE(w, r)
|
user, err := queries.GetUserByUsername(r.Context(), username)
|
||||||
|
|
||||||
user, err := queries.GetUserByUsername(r.Context(), signals.Username)
|
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"error": "Invalid username or password"}) //nolint:errcheck
|
http.Redirect(w, r, "/login?error="+url.QueryEscape("Invalid username or password"), http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"error": "An error occurred"}) //nolint:errcheck
|
http.Redirect(w, r, "/login?error="+url.QueryEscape("An error occurred"), http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !auth.CheckPassword(signals.Password, user.PasswordHash) {
|
if !auth.CheckPassword(password, user.PasswordHash) {
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"error": "Invalid username or password"}) //nolint:errcheck
|
http.Redirect(w, r, "/login?error="+url.QueryEscape("Invalid username or password"), http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,46 +68,43 @@ func HandleLogin(queries *repository.Queries, sessions *scs.SessionManager) http
|
|||||||
redirectURL = returnURL
|
redirectURL = returnURL
|
||||||
}
|
}
|
||||||
|
|
||||||
sse.Redirect(redirectURL) //nolint:errcheck
|
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleRegister(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
|
func HandleRegister(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
var signals RegisterSignals
|
r.Body = http.MaxBytesReader(w, r.Body, 1024)
|
||||||
if err := datastar.ReadSignals(r, &signals); err != nil {
|
username := r.FormValue("username")
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
password := r.FormValue("password")
|
||||||
|
confirm := r.FormValue("confirm")
|
||||||
|
|
||||||
|
if err := auth.ValidateUsername(username); err != nil {
|
||||||
|
http.Redirect(w, r, "/register?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := auth.ValidatePassword(password); err != nil {
|
||||||
|
http.Redirect(w, r, "/register?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if password != confirm {
|
||||||
|
http.Redirect(w, r, "/register?error="+url.QueryEscape("Passwords do not match"), http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sse := datastar.NewSSE(w, r)
|
hash, err := auth.HashPassword(password)
|
||||||
|
|
||||||
if err := auth.ValidateUsername(signals.Username); err != nil {
|
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"error": err.Error()}) //nolint:errcheck
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := auth.ValidatePassword(signals.Password); err != nil {
|
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"error": err.Error()}) //nolint:errcheck
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if signals.Password != signals.Confirm {
|
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"error": "Passwords do not match"}) //nolint:errcheck
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
hash, err := auth.HashPassword(signals.Password)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"error": "An error occurred"}) //nolint:errcheck
|
http.Redirect(w, r, "/register?error="+url.QueryEscape("An error occurred"), http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := queries.CreateUser(r.Context(), repository.CreateUserParams{
|
user, err := queries.CreateUser(r.Context(), repository.CreateUserParams{
|
||||||
ID: uuid.New().String(),
|
ID: uuid.New().String(),
|
||||||
Username: signals.Username,
|
Username: username,
|
||||||
PasswordHash: hash,
|
PasswordHash: hash,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"error": "Username already taken"}) //nolint:errcheck
|
http.Redirect(w, r, "/register?error="+url.QueryEscape("Username already taken"), http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,6 +119,6 @@ func HandleRegister(queries *repository.Queries, sessions *scs.SessionManager) h
|
|||||||
redirectURL = returnURL
|
redirectURL = returnURL
|
||||||
}
|
}
|
||||||
|
|
||||||
sse.Redirect(redirectURL) //nolint:errcheck
|
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
351
features/auth/handlers_test.go
Normal file
351
features/auth/handlers_test.go
Normal file
@@ -0,0 +1,351 @@
|
|||||||
|
package auth_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/alexedwards/scs/v2"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"github.com/ryanhamamura/games/auth"
|
||||||
|
"github.com/ryanhamamura/games/db/repository"
|
||||||
|
featauth "github.com/ryanhamamura/games/features/auth"
|
||||||
|
"github.com/ryanhamamura/games/features/lobby"
|
||||||
|
appsessions "github.com/ryanhamamura/games/sessions"
|
||||||
|
"github.com/ryanhamamura/games/testutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sessionCookieName is the default SCS cookie name used in tests.
|
||||||
|
const sessionCookieName = "session"
|
||||||
|
|
||||||
|
type testSetup struct {
|
||||||
|
db *sql.DB
|
||||||
|
queries *repository.Queries
|
||||||
|
sm *scs.SessionManager
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *testSetup) ctx() context.Context {
|
||||||
|
return context.Background()
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestSetup(t *testing.T) *testSetup {
|
||||||
|
t.Helper()
|
||||||
|
db, queries := testutil.NewTestDB(t)
|
||||||
|
sm := testutil.NewTestSessionManager(t, db)
|
||||||
|
return &testSetup{db: db, queries: queries, sm: sm}
|
||||||
|
}
|
||||||
|
|
||||||
|
// createTestUser inserts a user into the test database and returns the user ID.
|
||||||
|
func createTestUser(t *testing.T, setup *testSetup, username, password string) string {
|
||||||
|
t.Helper()
|
||||||
|
hash, err := auth.HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("hashing password: %v", err)
|
||||||
|
}
|
||||||
|
id := uuid.New().String()
|
||||||
|
_, err = setup.queries.CreateUser(setup.ctx(), repository.CreateUserParams{
|
||||||
|
ID: id,
|
||||||
|
Username: username,
|
||||||
|
PasswordHash: hash,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("creating test user: %v", err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
// postForm sends a POST request with form-encoded body through the session middleware,
|
||||||
|
// forwarding any cookies from a previous response.
|
||||||
|
func postForm(handler http.Handler, path string, values url.Values, cookies []*http.Cookie) *httptest.ResponseRecorder {
|
||||||
|
body := strings.NewReader(values.Encode())
|
||||||
|
req := httptest.NewRequest(http.MethodPost, path, body)
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
for _, c := range cookies {
|
||||||
|
req.AddCookie(c)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
// getPage sends a GET request through the session middleware, forwarding cookies.
|
||||||
|
func getPage(handler http.Handler, path string, cookies []*http.Cookie) *httptest.ResponseRecorder {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||||
|
for _, c := range cookies {
|
||||||
|
req.AddCookie(c)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractSessionValue makes a GET request with the given cookies to a test endpoint
|
||||||
|
// that reads a session value, verifying the session was persisted correctly.
|
||||||
|
func extractSessionValue(t *testing.T, setup *testSetup, cookies []*http.Cookie, key string) string {
|
||||||
|
t.Helper()
|
||||||
|
var value string
|
||||||
|
handler := setup.sm.LoadAndSave(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
value = setup.sm.GetString(r.Context(), key)
|
||||||
|
}))
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/check-session", nil)
|
||||||
|
for _, c := range cookies {
|
||||||
|
req.AddCookie(c)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("session check returned %d", rec.Code)
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleLogin_Success(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
createTestUser(t, setup, "alice", "password123")
|
||||||
|
|
||||||
|
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
||||||
|
rec := postForm(handler, "/auth/login", url.Values{
|
||||||
|
"username": {"alice"},
|
||||||
|
"password": {"password123"},
|
||||||
|
}, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
if loc := rec.Header().Get("Location"); loc != "/" {
|
||||||
|
t.Errorf("expected redirect to /, got %q", loc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify the response sets a session cookie
|
||||||
|
cookies := rec.Result().Cookies()
|
||||||
|
if !hasCookie(cookies, sessionCookieName) {
|
||||||
|
t.Fatal("response did not set a session cookie")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify session contains user data by reading it back
|
||||||
|
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
|
||||||
|
if userID == "" {
|
||||||
|
t.Error("session does not contain user_id after login")
|
||||||
|
}
|
||||||
|
nickname := extractSessionValue(t, setup, cookies, appsessions.KeyNickname)
|
||||||
|
if nickname != "alice" {
|
||||||
|
t.Errorf("expected nickname %q, got %q", "alice", nickname)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleLogin_InvalidPassword(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
createTestUser(t, setup, "alice", "password123")
|
||||||
|
|
||||||
|
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
||||||
|
rec := postForm(handler, "/auth/login", url.Values{
|
||||||
|
"username": {"alice"},
|
||||||
|
"password": {"wrongpassword"},
|
||||||
|
}, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
loc := rec.Header().Get("Location")
|
||||||
|
if !strings.HasPrefix(loc, "/login?error=") {
|
||||||
|
t.Errorf("expected redirect to /login?error=..., got %q", loc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleLogin_UnknownUser(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
|
||||||
|
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
||||||
|
rec := postForm(handler, "/auth/login", url.Values{
|
||||||
|
"username": {"nonexistent"},
|
||||||
|
"password": {"password123"},
|
||||||
|
}, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
loc := rec.Header().Get("Location")
|
||||||
|
if !strings.HasPrefix(loc, "/login?error=") {
|
||||||
|
t.Errorf("expected redirect to /login?error=..., got %q", loc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleLogin_ReturnURL(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
createTestUser(t, setup, "alice", "password123")
|
||||||
|
|
||||||
|
// First, visit the login page with a return_url to store it in the session
|
||||||
|
loginPageHandler := setup.sm.LoadAndSave(featauth.HandleLoginPage(setup.sm))
|
||||||
|
pageRec := getPage(loginPageHandler, "/login?return_url=/games/abc", nil)
|
||||||
|
cookies := pageRec.Result().Cookies()
|
||||||
|
|
||||||
|
// Now log in with those cookies so the handler can read return_url from session
|
||||||
|
loginHandler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
||||||
|
rec := postForm(loginHandler, "/auth/login", url.Values{
|
||||||
|
"username": {"alice"},
|
||||||
|
"password": {"password123"},
|
||||||
|
}, cookies)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
if loc := rec.Header().Get("Location"); loc != "/games/abc" {
|
||||||
|
t.Errorf("expected redirect to /games/abc, got %q", loc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleRegister_Success(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
|
||||||
|
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
||||||
|
rec := postForm(handler, "/auth/register", url.Values{
|
||||||
|
"username": {"newuser"},
|
||||||
|
"password": {"password123"},
|
||||||
|
"confirm": {"password123"},
|
||||||
|
}, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
if loc := rec.Header().Get("Location"); loc != "/" {
|
||||||
|
t.Errorf("expected redirect to /, got %q", loc)
|
||||||
|
}
|
||||||
|
|
||||||
|
cookies := rec.Result().Cookies()
|
||||||
|
if !hasCookie(cookies, sessionCookieName) {
|
||||||
|
t.Fatal("response did not set a session cookie")
|
||||||
|
}
|
||||||
|
|
||||||
|
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
|
||||||
|
if userID == "" {
|
||||||
|
t.Error("session does not contain user_id after registration")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleRegister_PasswordMismatch(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
|
||||||
|
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
||||||
|
rec := postForm(handler, "/auth/register", url.Values{
|
||||||
|
"username": {"newuser"},
|
||||||
|
"password": {"password123"},
|
||||||
|
"confirm": {"differentpassword"},
|
||||||
|
}, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
loc := rec.Header().Get("Location")
|
||||||
|
if !strings.Contains(loc, "Passwords+do+not+match") {
|
||||||
|
t.Errorf("expected error about password mismatch, got %q", loc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleRegister_InvalidUsername(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
|
||||||
|
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
||||||
|
rec := postForm(handler, "/auth/register", url.Values{
|
||||||
|
"username": {"ab"}, // too short
|
||||||
|
"password": {"password123"},
|
||||||
|
"confirm": {"password123"},
|
||||||
|
}, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
loc := rec.Header().Get("Location")
|
||||||
|
if !strings.HasPrefix(loc, "/register?error=") {
|
||||||
|
t.Errorf("expected redirect to /register?error=..., got %q", loc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleRegister_ShortPassword(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
|
||||||
|
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
||||||
|
rec := postForm(handler, "/auth/register", url.Values{
|
||||||
|
"username": {"validuser"},
|
||||||
|
"password": {"short"},
|
||||||
|
"confirm": {"short"},
|
||||||
|
}, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
loc := rec.Header().Get("Location")
|
||||||
|
if !strings.HasPrefix(loc, "/register?error=") {
|
||||||
|
t.Errorf("expected redirect to /register?error=..., got %q", loc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleRegister_DuplicateUsername(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
createTestUser(t, setup, "taken", "password123")
|
||||||
|
|
||||||
|
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
||||||
|
rec := postForm(handler, "/auth/register", url.Values{
|
||||||
|
"username": {"taken"},
|
||||||
|
"password": {"password123"},
|
||||||
|
"confirm": {"password123"},
|
||||||
|
}, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
||||||
|
}
|
||||||
|
loc := rec.Header().Get("Location")
|
||||||
|
if !strings.Contains(loc, "Username+already+taken") {
|
||||||
|
t.Errorf("expected error about duplicate username, got %q", loc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleLogout(t *testing.T) {
|
||||||
|
setup := newTestSetup(t)
|
||||||
|
createTestUser(t, setup, "alice", "password123")
|
||||||
|
|
||||||
|
// Log in first to establish a session
|
||||||
|
loginHandler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
||||||
|
loginRec := postForm(loginHandler, "/auth/login", url.Values{
|
||||||
|
"username": {"alice"},
|
||||||
|
"password": {"password123"},
|
||||||
|
}, nil)
|
||||||
|
cookies := loginRec.Result().Cookies()
|
||||||
|
|
||||||
|
// Verify we're logged in
|
||||||
|
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
|
||||||
|
if userID == "" {
|
||||||
|
t.Fatal("expected to be logged in before testing logout")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now log out
|
||||||
|
logoutHandler := setup.sm.LoadAndSave(lobby.HandleLogout(setup.sm))
|
||||||
|
logoutRec := postForm(logoutHandler, "/logout", nil, cookies)
|
||||||
|
|
||||||
|
if logoutRec.Code != http.StatusSeeOther {
|
||||||
|
t.Errorf("expected status %d, got %d", http.StatusSeeOther, logoutRec.Code)
|
||||||
|
}
|
||||||
|
if loc := logoutRec.Header().Get("Location"); loc != "/" {
|
||||||
|
t.Errorf("expected redirect to /, got %q", loc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify session is cleared — use the cookies from the logout response
|
||||||
|
logoutCookies := logoutRec.Result().Cookies()
|
||||||
|
userID = extractSessionValue(t, setup, logoutCookies, appsessions.KeyUserID)
|
||||||
|
if userID != "" {
|
||||||
|
t.Errorf("expected empty user_id after logout, got %q", userID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasCookie(cookies []*http.Cookie, name string) bool {
|
||||||
|
for _, c := range cookies {
|
||||||
|
if c.Name == name {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -1,45 +1,39 @@
|
|||||||
package pages
|
package pages
|
||||||
|
|
||||||
import (
|
import "github.com/ryanhamamura/games/features/common/layouts"
|
||||||
"github.com/ryanhamamura/games/features/common/layouts"
|
|
||||||
"github.com/starfederation/datastar-go/datastar"
|
|
||||||
)
|
|
||||||
|
|
||||||
templ LoginPage() {
|
templ LoginPage(errorMsg string) {
|
||||||
@layouts.Base("Login") {
|
@layouts.Base("Login") {
|
||||||
<main class="max-w-sm mx-auto mt-8 text-center" data-signals="{username: '', password: '', error: ''}">
|
<main class="max-w-sm mx-auto mt-8 text-center">
|
||||||
<h1 class="text-3xl font-bold">Login</h1>
|
<h1 class="text-3xl font-bold">Login</h1>
|
||||||
<p class="mb-4">Sign in to your account</p>
|
<p class="mb-4">Sign in to your account</p>
|
||||||
<div data-show="$error != ''" class="alert alert-error mb-4" data-text="$error"></div>
|
if errorMsg != "" {
|
||||||
<div>
|
<div class="alert alert-error mb-4">{ errorMsg }</div>
|
||||||
|
}
|
||||||
|
<form method="POST" action="/auth/login">
|
||||||
<fieldset class="fieldset">
|
<fieldset class="fieldset">
|
||||||
<label class="label" for="username">Username</label>
|
<label class="label" for="username">Username</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="username"
|
id="username"
|
||||||
|
name="username"
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Enter your username"
|
placeholder="Enter your username"
|
||||||
data-bind="username"
|
|
||||||
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/login") }
|
|
||||||
autofocus
|
autofocus
|
||||||
/>
|
/>
|
||||||
<label class="label" for="password">Password</label>
|
<label class="label" for="password">Password</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="password"
|
id="password"
|
||||||
|
name="password"
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Enter your password"
|
placeholder="Enter your password"
|
||||||
data-bind="password"
|
|
||||||
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/login") }
|
|
||||||
/>
|
/>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<button
|
<button type="submit" class="btn btn-primary w-full">
|
||||||
class="btn btn-primary w-full"
|
|
||||||
data-on:click={ datastar.PostSSE("/auth/login") }
|
|
||||||
>
|
|
||||||
Login
|
Login
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</form>
|
||||||
<p>
|
<p>
|
||||||
Don't have an account? <a class="link" href="/register">Register</a>
|
Don't have an account? <a class="link" href="/register">Register</a>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,54 +1,47 @@
|
|||||||
package pages
|
package pages
|
||||||
|
|
||||||
import (
|
import "github.com/ryanhamamura/games/features/common/layouts"
|
||||||
"github.com/ryanhamamura/games/features/common/layouts"
|
|
||||||
"github.com/starfederation/datastar-go/datastar"
|
|
||||||
)
|
|
||||||
|
|
||||||
templ RegisterPage() {
|
templ RegisterPage(errorMsg string) {
|
||||||
@layouts.Base("Register") {
|
@layouts.Base("Register") {
|
||||||
<main class="max-w-sm mx-auto mt-8 text-center" data-signals="{username: '', password: '', confirm: '', error: ''}">
|
<main class="max-w-sm mx-auto mt-8 text-center">
|
||||||
<h1 class="text-3xl font-bold">Register</h1>
|
<h1 class="text-3xl font-bold">Register</h1>
|
||||||
<p class="mb-4">Create a new account</p>
|
<p class="mb-4">Create a new account</p>
|
||||||
<div data-show="$error != ''" class="alert alert-error mb-4" data-text="$error"></div>
|
if errorMsg != "" {
|
||||||
<div>
|
<div class="alert alert-error mb-4">{ errorMsg }</div>
|
||||||
|
}
|
||||||
|
<form method="POST" action="/auth/register">
|
||||||
<fieldset class="fieldset">
|
<fieldset class="fieldset">
|
||||||
<label class="label" for="username">Username</label>
|
<label class="label" for="username">Username</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="username"
|
id="username"
|
||||||
|
name="username"
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Choose a username"
|
placeholder="Choose a username"
|
||||||
data-bind="username"
|
|
||||||
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
|
|
||||||
autofocus
|
autofocus
|
||||||
/>
|
/>
|
||||||
<label class="label" for="password">Password</label>
|
<label class="label" for="password">Password</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="password"
|
id="password"
|
||||||
|
name="password"
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Choose a password (min 8 chars)"
|
placeholder="Choose a password (min 8 chars)"
|
||||||
data-bind="password"
|
|
||||||
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
|
|
||||||
/>
|
/>
|
||||||
<label class="label" for="confirm">Confirm Password</label>
|
<label class="label" for="confirm">Confirm Password</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="confirm"
|
id="confirm"
|
||||||
|
name="confirm"
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Confirm your password"
|
placeholder="Confirm your password"
|
||||||
data-bind="confirm"
|
|
||||||
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
|
|
||||||
/>
|
/>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<button
|
<button type="submit" class="btn btn-primary w-full">
|
||||||
class="btn btn-primary w-full"
|
|
||||||
data-on:click={ datastar.PostSSE("/auth/register") }
|
|
||||||
>
|
|
||||||
Register
|
Register
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</form>
|
||||||
<p>
|
<p>
|
||||||
Already have an account? <a class="link" href="/login">Login</a>
|
Already have an account? <a class="link" href="/login">Login</a>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func SetupRoutes(router chi.Router, queries *repository.Queries, sessions *scs.SessionManager) {
|
func SetupRoutes(router chi.Router, queries *repository.Queries, sessions *scs.SessionManager) {
|
||||||
router.Get("/login", HandleLoginPage())
|
router.Get("/login", HandleLoginPage(sessions))
|
||||||
router.Get("/register", HandleRegisterPage())
|
router.Get("/register", HandleRegisterPage())
|
||||||
router.Post("/auth/login", HandleLogin(queries, sessions))
|
router.Post("/auth/login", HandleLogin(queries, sessions))
|
||||||
router.Post("/auth/register", HandleRegister(queries, sessions))
|
router.Post("/auth/register", HandleRegister(queries, sessions))
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ templ GamePage(g *connect4.Game, myColor int, messages []chat.Message, chatCfg c
|
|||||||
}
|
}
|
||||||
|
|
||||||
templ GameContent(g *connect4.Game, myColor int, messages []chat.Message, chatCfg chatcomponents.Config) {
|
templ GameContent(g *connect4.Game, myColor int, messages []chat.Message, chatCfg chatcomponents.Config) {
|
||||||
<div id="game-content">
|
<div id="game-content" class="flex flex-col items-center gap-4">
|
||||||
@sharedcomponents.LiveClock()
|
@sharedcomponents.LiveClock()
|
||||||
@sharedcomponents.BackToLobby()
|
@sharedcomponents.BackToLobby()
|
||||||
@sharedcomponents.StealthTitle("text-3xl font-bold")
|
@sharedcomponents.StealthTitle("text-3xl font-bold")
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ templ Base(title string) {
|
|||||||
<head>
|
<head>
|
||||||
<title>{ title }</title>
|
<title>{ title }</title>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
|
||||||
<script defer type="module" src={ assets.StaticPath("js/datastar.js") }></script>
|
<script defer type="module" src={ assets.StaticPath("js/datastar/datastar.js") }></script>
|
||||||
<link href={ assets.StaticPath("css/output.css") } rel="stylesheet" type="text/css"/>
|
<link href={ assets.StaticPath("css/output.css") } rel="stylesheet" type="text/css"/>
|
||||||
</head>
|
</head>
|
||||||
<body class="flex flex-col h-screen">
|
<body class="flex flex-col h-screen">
|
||||||
|
|||||||
@@ -171,7 +171,6 @@ func HandleLogout(sessions *scs.SessionManager) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sse := datastar.NewSSE(w, r)
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||||
sse.ExecuteScript("window.location.href='/'") //nolint:errcheck
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,13 +20,11 @@ templ LobbyPage(data LobbyData) {
|
|||||||
if data.IsLoggedIn {
|
if data.IsLoggedIn {
|
||||||
<div class="flex justify-center items-center gap-4 mb-4 p-2 bg-base-200 rounded-lg">
|
<div class="flex justify-center items-center gap-4 mb-4 p-2 bg-base-200 rounded-lg">
|
||||||
<span>Logged in as <strong>{ data.Username }</strong></span>
|
<span>Logged in as <strong>{ data.Username }</strong></span>
|
||||||
<button
|
<form method="POST" action="/logout" class="inline">
|
||||||
type="button"
|
<button type="submit" class="btn btn-ghost btn-sm">
|
||||||
class="btn btn-ghost btn-sm"
|
|
||||||
data-on:click={ datastar.PostSSE("/logout") }
|
|
||||||
>
|
|
||||||
Logout
|
Logout
|
||||||
</button>
|
</button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
} else {
|
} else {
|
||||||
<div class="alert text-sm mb-4">
|
<div class="alert text-sm mb-4">
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ templ GamePage(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg
|
|||||||
}
|
}
|
||||||
|
|
||||||
templ GameContent(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg chatcomponents.Config, gameID string) {
|
templ GameContent(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg chatcomponents.Config, gameID string) {
|
||||||
<div id="game-content">
|
<div id="game-content" class="flex flex-col items-center gap-4">
|
||||||
@components.LiveClock()
|
@components.LiveClock()
|
||||||
@components.BackToLobby()
|
@components.BackToLobby()
|
||||||
<h1 class="text-3xl font-bold">~~~~</h1>
|
<h1 class="text-3xl font-bold">~~~~</h1>
|
||||||
|
|||||||
Reference in New Issue
Block a user