sonda/internal/api/http/handlers_auth.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

170 lines
4.7 KiB
Go

package httpapi
import (
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/auth"
)
type authHandlers struct{ svc authService }
type credentials struct {
Email string `json:"email"`
Password string `json:"password"`
}
type userJSON struct {
ID int64 `json:"id"`
Email string `json:"email"`
IsAdmin bool `json:"is_admin"`
}
func toUserJSON(u auth.User) userJSON {
return userJSON{ID: u.ID, Email: u.Email, 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.ErrEmailTaken):
writeError(c, http.StatusConflict, "email_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.Email, 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.Email, 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)
}