Files
Kontrollverlust/user.go
T
irrlicht cb237c248e Rewrite backend in Go with JSON API and JS frontend
Reimplements the Flask app as a Go HTTP API (chi + modernc sqlite) with a
minimal vanilla-JS frontend in web/. Endpoints mirror the original Flask
routes but return JSON instead of HTML.

- auth: login/logout/register/sessioninfo/headerbar with crypto/rand tokens
- entry: paginated feed (single JOIN), create with image scaling
- user: profile, userinfo; delete still a stub
- requireAuth middleware passes uid via context
- notes/api.md documents the API and schema

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 10:17:02 +02:00

77 lines
1.9 KiB
Go

package main
import (
"database/sql"
"math/rand/v2"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"golang.org/x/crypto/bcrypt"
)
func createUser(username, password string) error {
uid := int64(rand.IntN(99999999))
now := time.Now().Unix()
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
_, err = db.Exec(
`INSERT INTO user (uid, created_at, username, password) VALUES (?, ?, ?, ?)`,
uid, now, username, hash,
)
return err
}
// idFromUsername liefert die interne id oder 0, wenn der Nutzer nicht existiert.
func idFromUsername(username string) int64 {
var id int64
if err := db.QueryRow(`SELECT id FROM user WHERE username = ?`, username).Scan(&id); err != nil {
return 0
}
return id
}
func handleUserPage(w http.ResponseWriter, r *http.Request) {
username := chi.URLParam(r, "username")
var uid, createdAt int64
err := db.QueryRow(`SELECT uid, created_at FROM user WHERE username = ?`, username).Scan(&uid, &createdAt)
if err != nil {
writeError(w, http.StatusNotFound, "Nutzer nicht gefunden")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"uid": uid,
"username": username,
"created_at": createdAt,
})
}
func handleUserInfo(w http.ResponseWriter, r *http.Request) {
uid := uidFromContext(r.Context())
var createdAt, lastLogin sql.NullInt64
var username string
err := db.QueryRow(
`SELECT created_at, last_login, username FROM user WHERE uid = ?`, uid,
).Scan(&createdAt, &lastLogin, &username)
if err != nil {
writeError(w, http.StatusNotFound, "Nutzer nicht gefunden")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"uid": uid,
"username": username,
"created_at": createdAt.Int64,
"last_login": lastLogin.Int64,
})
}
func handleUserDelete(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotImplemented, "Account-Löschung ist noch nicht implementiert")
}