- feat(auth): short-lived access tokens plus rotating refresh tokens stored as
SHA-256 hashes; replaying a spent token revokes every session of that user
- feat(auth): is_admin flag; the first registered user is the admin and the
last admin can be neither demoted nor deleted
- feat(api): POST /auth/refresh, /auth/logout, /auth/password and GET /auth/me
- feat(api): admin-only GET/POST /users, PATCH /users/{id}, PUT
/users/{id}/password and DELETE /users/{id}; the admin check reads the role
from the database on every call
- feat(api): starting a library scan is now admin-only
- feat(storage): users and refresh token repositories for SQLite and
PostgreSQL (migration 0004; the oldest existing account becomes admin)
- feat(config): auth.access_ttl_minutes and auth.refresh_ttl_hours replace
auth.token_ttl_hours
- test: rotation, reuse detection, concurrent rotation with a single winner,
admin rules, role changes taking effect immediately
170 lines
4.8 KiB
Go
170 lines
4.8 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"`
|
|
IsAdmin bool `json:"is_admin"`
|
|
}
|
|
|
|
func toUserJSON(u auth.User) userJSON {
|
|
return userJSON{ID: u.ID, Username: u.Username, IsAdmin: u.IsAdmin}
|
|
}
|
|
|
|
func sessionJSON(s auth.Session) gin.H {
|
|
return gin.H{
|
|
"access_token": s.AccessToken,
|
|
"access_expires_at": s.AccessExpiresAt.UTC().Format(time.RFC3339),
|
|
"refresh_token": s.RefreshToken,
|
|
"refresh_expires_at": s.RefreshExpiresAt.UTC().Format(time.RFC3339),
|
|
"user": toUserJSON(s.User),
|
|
}
|
|
}
|
|
|
|
// bindJSON reads the request body, answering 400 itself on failure.
|
|
func bindJSON(c *gin.Context, dst any) bool {
|
|
if err := c.ShouldBindJSON(dst); err != nil {
|
|
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// writeAuthError maps service errors to the standard envelope.
|
|
func writeAuthError(c *gin.Context, err error) {
|
|
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 errors.Is(err, auth.ErrUserNotFound):
|
|
writeError(c, http.StatusNotFound, "user_not_found", err.Error())
|
|
case errors.Is(err, auth.ErrLastAdmin):
|
|
writeError(c, http.StatusConflict, "last_admin", err.Error())
|
|
case errors.Is(err, auth.ErrInvalidCredentials):
|
|
writeError(c, http.StatusUnauthorized, "invalid_credentials", err.Error())
|
|
case errors.Is(err, auth.ErrInvalidRefreshToken):
|
|
writeError(c, http.StatusUnauthorized, "invalid_refresh_token", err.Error())
|
|
default:
|
|
_ = c.Error(err)
|
|
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
|
}
|
|
}
|
|
|
|
// register creates the first user, who becomes the admin. It is closed once any user exists.
|
|
func (h *authHandlers) register(c *gin.Context) {
|
|
var req credentials
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
user, err := h.svc.Register(c.Request.Context(), req.Username, req.Password)
|
|
if err != nil {
|
|
writeAuthError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, toUserJSON(user))
|
|
}
|
|
|
|
func (h *authHandlers) login(c *gin.Context) {
|
|
var req credentials
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
sess, err := h.svc.Login(c.Request.Context(), req.Username, req.Password)
|
|
if err != nil {
|
|
writeAuthError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, sessionJSON(sess))
|
|
}
|
|
|
|
type refreshRequest struct {
|
|
RefreshToken string `json:"refresh_token"`
|
|
}
|
|
|
|
// refresh swaps a refresh token for a new session; the old token is spent.
|
|
func (h *authHandlers) refresh(c *gin.Context) {
|
|
var req refreshRequest
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
sess, err := h.svc.Refresh(c.Request.Context(), req.RefreshToken)
|
|
if err != nil {
|
|
writeAuthError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, sessionJSON(sess))
|
|
}
|
|
|
|
// logout revokes a refresh token. It always answers 204, so it never reveals
|
|
// whether the token was valid.
|
|
func (h *authHandlers) logout(c *gin.Context) {
|
|
var req refreshRequest
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
if err := h.svc.Logout(c.Request.Context(), req.RefreshToken); err != nil {
|
|
writeAuthError(c, err)
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *authHandlers) me(c *gin.Context) {
|
|
user, err := h.svc.User(c.Request.Context(), currentUserID(c))
|
|
if errors.Is(err, auth.ErrUserNotFound) {
|
|
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeAuthError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, toUserJSON(user))
|
|
}
|
|
|
|
type passwordChangeRequest struct {
|
|
CurrentPassword string `json:"current_password"`
|
|
NewPassword string `json:"new_password"`
|
|
}
|
|
|
|
// changePassword needs the current password and signs the user out everywhere.
|
|
func (h *authHandlers) changePassword(c *gin.Context) {
|
|
var req passwordChangeRequest
|
|
if !bindJSON(c, &req) {
|
|
return
|
|
}
|
|
err := h.svc.ChangePassword(c.Request.Context(), currentUserID(c), req.CurrentPassword, req.NewPassword)
|
|
if errors.Is(err, auth.ErrInvalidCredentials) {
|
|
// 403, not 401: the token is fine, and 401 would tell clients to refresh it.
|
|
writeError(c, http.StatusForbidden, "invalid_credentials", "current password is wrong")
|
|
return
|
|
}
|
|
if errors.Is(err, auth.ErrUserNotFound) {
|
|
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeAuthError(c, err)
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|