refactored for maintainability

This commit is contained in:
2026-02-08 17:19:45 +11:00
parent 7125683e6a
commit ac38025b77
40 changed files with 1211 additions and 920 deletions

View File

@@ -3,12 +3,12 @@ package handlers
import (
"context"
"net/http"
"time"
"git.haelnorr.com/h/golib/hws"
"git.haelnorr.com/h/golib/hwsauth"
"git.haelnorr.com/h/oslstats/internal/db"
"git.haelnorr.com/h/oslstats/internal/discord"
"git.haelnorr.com/h/oslstats/internal/throw"
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
@@ -21,42 +21,31 @@ func Logout(
) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
throwInternalServiceError(s, w, r, "Database error", errors.Wrap(err, "conn.BeginTx"))
return
}
defer func() { _ = tx.Rollback() }()
user := db.CurrentUser(r.Context())
if user == nil {
// JIC - should be impossible to get here if route is protected by LoginReq
w.Header().Set("HX-Redirect", "/")
return
}
token, err := user.DeleteDiscordTokens(ctx, tx)
if err != nil {
throwInternalServiceError(s, w, r, "Database error", errors.Wrap(err, "user.DeleteDiscordTokens"))
return
}
if token != nil {
err = discordAPI.RevokeToken(token.Convert())
if ok := db.WithWriteTx(s, w, r, conn, func(ctx context.Context, tx bun.Tx) (bool, error) {
token, err := user.DeleteDiscordTokens(ctx, tx)
if err != nil {
throwInternalServiceError(s, w, r, "Discord API error", errors.Wrap(err, "discordAPI.RevokeToken"))
return
return false, errors.Wrap(err, "user.DeleteDiscordTokens")
}
}
err = auth.Logout(tx, w, r)
if err != nil {
throwInternalServiceError(s, w, r, "Logout failed", errors.Wrap(err, "auth.Logout"))
return
}
err = tx.Commit()
if err != nil {
throwInternalServiceError(s, w, r, "Logout failed", errors.Wrap(err, "tx.Commit"))
if token != nil {
err = discordAPI.RevokeToken(token.Convert())
if err != nil {
throw.InternalServiceError(s, w, r, "Discord API error", errors.Wrap(err, "discordAPI.RevokeToken"))
return false, nil
}
}
err = auth.Logout(tx, w, r)
if err != nil {
throw.InternalServiceError(s, w, r, "Logout failed", errors.Wrap(err, "auth.Logout"))
return false, nil
}
return true, nil
}); !ok {
return
}
w.Header().Set("HX-Redirect", "/")