- feat(config): TOML config with env overrides, strict parsing and validation - feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun, embedded per-driver SQL migrations with a transactional runner - feat(schema): catalog tables (artists, albums, tracks, audio_files with per-root paths), users and listening events with idempotency keys - feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only registration and login - feat(api): gin REST API under /api/v1 (health, register, login, listens) with a consistent error envelope, body limit and request logging - feat(sondad): zap logger, graceful shutdown, composition root in main - chore: example config, .gitignore for secrets, DB files, IDE and agent files
68 lines
2 KiB
Go
68 lines
2 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"codeberg.org/squidd/sonda/internal/auth"
|
|
)
|
|
|
|
type authHandlers struct{ svc authService }
|
|
|
|
type credentials struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
type userJSON struct {
|
|
ID int64 `json:"id"`
|
|
Username string `json:"username"`
|
|
}
|
|
|
|
// register creates the first user. It is closed once any user exists.
|
|
func (h *authHandlers) register(c *gin.Context) {
|
|
var req credentials
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body")
|
|
return
|
|
}
|
|
user, err := h.svc.Register(c.Request.Context(), req.Username, req.Password)
|
|
switch {
|
|
case errors.Is(err, auth.ErrInvalidInput):
|
|
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
|
|
case errors.Is(err, auth.ErrRegistrationClosed):
|
|
writeError(c, http.StatusForbidden, "registration_closed", err.Error())
|
|
case errors.Is(err, auth.ErrUsernameTaken):
|
|
writeError(c, http.StatusConflict, "username_taken", err.Error())
|
|
case err != nil:
|
|
_ = c.Error(err)
|
|
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
|
default:
|
|
c.JSON(http.StatusCreated, userJSON{ID: user.ID, Username: user.Username})
|
|
}
|
|
}
|
|
|
|
func (h *authHandlers) login(c *gin.Context) {
|
|
var req credentials
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body")
|
|
return
|
|
}
|
|
res, err := h.svc.Login(c.Request.Context(), req.Username, req.Password)
|
|
switch {
|
|
case errors.Is(err, auth.ErrInvalidCredentials):
|
|
writeError(c, http.StatusUnauthorized, "invalid_credentials", err.Error())
|
|
case err != nil:
|
|
_ = c.Error(err)
|
|
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
|
default:
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"token": res.Token,
|
|
"expires_at": res.ExpiresAt.UTC().Format(time.RFC3339),
|
|
"user": userJSON{ID: res.User.ID, Username: res.User.Username},
|
|
})
|
|
}
|
|
}
|