package handlers import ( "context" "net/http" "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" ) func Logout( s *hws.Server, auth *hwsauth.Authenticator[*db.User, bun.Tx], conn *db.DB, discordAPI *discord.APIClient, ) http.Handler { return http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { 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 } if ok := conn.WithWriteTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) { token, err := user.DeleteDiscordTokens(ctx, tx) if err != nil { return false, errors.Wrap(err, "user.DeleteDiscordTokens") } 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", "/") }, ) }