A platform for community discussion. Free, open, simple.
FEATURE: Prompt anonymous users to sign up after engagement clicks (#40256)
Régis Hanolfba56920b584
diff --git a/app/controllers/anonymous_actions_controller.rb b/app/controllers/anonymous_actions_controller.rbnew file mode 100644index 00000000000..db08c28d841--- /dev/null+++ b/app/controllers/anonymous_actions_controller.rb@@ -0,0 +1,26 @@+# frozen_string_literal: true++class AnonymousActionsController < ApplicationController+ MAX_PARAMS_BYTES = 512++ def create+ raise Discourse::InvalidAccess if current_user++ RateLimiter.new(nil, "anonymous-action-min-#{request.remote_ip}", 10, 1.minute).performed!+ RateLimiter.new(nil, "anonymous-action-hr-#{request.remote_ip}", 60, 1.hour).performed!++ type = params.require(:type)+ raise Discourse::InvalidParameters.new(:type) if !AnonymousAction.registered?(type)++ raw_params = params[:params]+ action_params = raw_params.is_a?(ActionController::Parameters) ? raw_params.permit!.to_h : {}++ if action_params.to_json.bytesize > MAX_PARAMS_BYTES+ raise Discourse::InvalidParameters.new(:params)+ end++ AnonymousAction.set(cookies, type:, params: action_params)++ head :no_content+ end+enddiff --git a/app/controllers/invites_controller.rb b/app/controllers/invites_controller.rbindex fa55cef53da..c6ccd2e25cf 100644--- a/app/controllers/invites_controller.rb+++ b/app/controllers/invites_controller.rb@@ -393,7 +393,9 @@ class InvitesController < ApplicationController)end- log_on_user(user) if !redeeming_user && user.active? && user.guardian.can_access_forum?+ if !redeeming_user && user.active? && user.guardian.can_access_forum?+ log_on_user(user, replay_anonymous_action: true)+ enduser.update_timezone_if_missing(params[:timezone])post_process_invite(user)diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rbindex 362715ab2aa..e2fd62e38fa 100644--- a/app/controllers/session_controller.rb+++ b/app/controllers/session_controller.rb@@ -323,7 +323,7 @@ class SessionController < ApplicationControllerconnect_verbose_warn do"Verbose SSO log: User was logged on #{user.username}\n\n#{sso.diagnostics}"end- log_on_user(user) if user.id != current_user&.id+ log_on_user(user, replay_anonymous_action: true) if user.id != current_user&.idenddef create@@ -479,7 +479,7 @@ class SessionController < ApplicationControllerreturn render json: payloadelseuser.update_timezone_if_missing(params[:timezone])- log_on_user(user)+ log_on_user(user, replay_anonymous_action: true)return render json: success_jsonendend@@ -495,7 +495,7 @@ class SessionController < ApplicationControllerDiscourse.redis.del "otp_#{params[:token]}"return redirect_to path("/")elsif request.post?- log_on_user(user)+ log_on_user(user, replay_anonymous_action: true)Discourse.redis.del "otp_#{params[:token]}"return redirect_to path("/")else@@ -849,7 +849,7 @@ class SessionController < ApplicationControllerdef login(user, passkey_login: false, second_factor_auth_result: nil)session.delete(ACTIVATE_USER_KEY)user.update_timezone_if_missing(params[:timezone])- log_on_user(user)+ log_on_user(user, replay_anonymous_action: true)if payload = cookies.delete(:sso_payload)confirmed_2fa_during_login =diff --git a/app/controllers/users/omniauth_callbacks_controller.rb b/app/controllers/users/omniauth_callbacks_controller.rbindex 528d412b1f5..dd96ee1957a 100644--- a/app/controllers/users/omniauth_callbacks_controller.rb+++ b/app/controllers/users/omniauth_callbacks_controller.rb@@ -206,7 +206,7 @@ class Users::OmniauthCallbacksController < ApplicationControllerreturnend- log_on_user(user, { authenticated_with_oauth: true })+ log_on_user(user, { authenticated_with_oauth: true }, replay_anonymous_action: true)Invite.invalidate_for_email(user.email) # invite link can't be used to log in anymoreserver_session.delete(:authentication) # don't carry around old auth info@auth_result.authenticated = truediff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex 589abc40af9..87e0d9dd343 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -999,7 +999,7 @@ class UsersController < ApplicationControllermessage =if Guardian.new(@user).can_access_forum?# Log in the user- log_on_user(@user)+ log_on_user(@user, replay_anonymous_action: true)"password_reset.success"else@requires_approval = true@@ -1139,7 +1139,7 @@ class UsersController < ApplicationController# Log in the user unless they need to be approvedif Guardian.new(@user).can_access_forum?@user.enqueue_welcome_message("welcome_user") if @user.send_welcome_message- log_on_user(@user)+ log_on_user(@user, replay_anonymous_action: true)# invites#perform_accept_invitation already sets destination_url, but# sometimes it is lost (user changes browser, uses incognito, etc)diff --git a/app/services/user_activator.rb b/app/services/user_activator.rbindex 6a43f8f1e65..b5e2c0f2b38 100644--- a/app/services/user_activator.rb+++ b/app/services/user_activator.rb@@ -67,7 +67,11 @@ class LoginActivator < UserActivatorinclude CurrentUserdef activate- log_on_user(user, { authenticated_with_oauth: session[:authenticated_with_oauth] })+ log_on_user(+ user,+ { authenticated_with_oauth: session[:authenticated_with_oauth] },+ replay_anonymous_action: true,+ )user.enqueue_welcome_message("welcome_user")success_messageenddiff --git a/config/initializers/100-anonymous_actions.rb b/config/initializers/100-anonymous_actions.rbnew file mode 100644index 00000000000..9fec35dab8b--- /dev/null+++ b/config/initializers/100-anonymous_actions.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++require "anonymous_action"++AnonymousAction.register("like_post") do |user, params|+ post = Post.find_by(id: params["post_id"])+ next if !post || !user.guardian.can_see?(post)+ PostActionCreator.like(user, post)+enddiff --git a/config/routes.rb b/config/routes.rbindex 5a6f7dc5778..d9b8fc1cf8a 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -1426,6 +1426,8 @@ Discourse::Application.routes.draw doget "search" => "search#show"post "search/click" => "search#click"+ post "anonymous-action" => "anonymous_actions#create"+# Nested replies routesscope "n/:slug/:topic_id", constraints: { topic_id: /\d+/ } doget "/children/:post_number" => "nested_topics#children",diff --git a/frontend/discourse/app/components/post/menu.gjs b/frontend/discourse/app/components/post/menu.gjsindex 913afd8638a..edd51bb5180 100644--- a/frontend/discourse/app/components/post/menu.gjs+++ b/frontend/discourse/app/components/post/menu.gjs@@ -11,6 +11,7 @@ import DeleteTopicDisallowedModal from "discourse/components/modal/delete-topic-import PluginOutlet from "discourse/components/plugin-outlet";import UserTip from "discourse/components/user-tip";import lazyHash from "discourse/helpers/lazy-hash";+import { deferAnonymousAction } from "discourse/lib/anonymous-action";import DAG from "discourse/lib/dag";import {applyBehaviorTransformer,@@ -82,7 +83,6 @@ const defaultDagOptions = {export default class PostMenu extends Component {@service capabilities;@service currentUser;- @service keyValueStore;@service modal;@service menu;@service siteSettings;@@ -455,14 +455,14 @@ export default class PostMenu extends Component {"post-menu-toggle-like-action",async () => {if (!this.currentUser) {- this.keyValueStore &&- this.keyValueStore.set({- key: "likedPostId",- value: this.args.post.id,- });-- this.args.showLogin();- return;+ // Archived topics reject likes server-side; closed topics still+ // accept them, so let anon defer-and-replay after login.+ if (this.args.post.topic?.archived) {+ return;+ }+ return deferAnonymousAction(this, "like_post", {+ post_id: this.args.post.id,+ });}if (diff --git a/frontend/discourse/app/components/post/menu/buttons/like.gjs b/frontend/discourse/app/components/post/menu/buttons/like.gjsindex fe32c6b2fc4..da7f3983bbe 100644--- a/frontend/discourse/app/components/post/menu/buttons/like.gjs+++ b/frontend/discourse/app/components/post/menu/buttons/like.gjs@@ -21,7 +21,12 @@ export default class PostMenuLikeButton extends Component {@tracked isAnimated = false;get disabled() {- return this.currentUser && !this.args.post.canToggleLike;+ if (!this.currentUser) {+ // Archived topics reject likes server-side; closed topics still accept+ // them, so let anon defer-and-replay after login.+ return !!this.args.post.topic?.archived;+ }+ return !this.args.post.canToggleLike;}get title() {@@ -80,7 +85,7 @@ export default class PostMenuLikeButton extends Component {}}...attributesdata-post-id={{@post.id}}- disabled={{this.disabled}}+ @disabled={{this.disabled}}@action={{this.toggleLike}}@icon={{this.likeButtonIcon}}@label={{if @showLabel "post.controls.like_action"}}diff --git a/frontend/discourse/app/lib/anonymous-action.js b/frontend/discourse/app/lib/anonymous-action.jsnew file mode 100644index 00000000000..3575f60c015--- /dev/null+++ b/frontend/discourse/app/lib/anonymous-action.js@@ -0,0 +1,29 @@+import { getOwner } from "@ember/owner";+import { ajax } from "discourse/lib/ajax";++/**+ * Saves an anonymous user's intended action server-side (in a short-lived+ * signed cookie) and redirects them to login. After they authenticate, the+ * matching `AnonymousAction` handler runs against their account and the+ * cookie is cleared.+ *+ * Example:+ *+ * if (!this.currentUser) {+ * return deferAnonymousAction(this, "like_post", {+ * post_id: this.args.post.id,+ * });+ * }+ */+export async function deferAnonymousAction(caller, type, params = {}) {+ try {+ await ajax("/anonymous-action", {+ type: "POST",+ data: { type, params },+ });+ } catch {+ // If saving the intent fails, the user can still authenticate — they'll+ // just have to re-trigger the action after login.+ }+ getOwner(caller).lookup("route:application").send("showLogin");+}diff --git a/frontend/discourse/tests/helpers/create-pretender.js b/frontend/discourse/tests/helpers/create-pretender.jsindex f8af25d53af..6f61244b4d1 100644--- a/frontend/discourse/tests/helpers/create-pretender.js+++ b/frontend/discourse/tests/helpers/create-pretender.js@@ -739,6 +739,8 @@ export function applyDefaultHandlers() {pretender.post("/u/action/send_activation_email", success);pretender.put("/u/update-activation-email", success);+ pretender.post("/anonymous-action", success);+pretender.get("/session/hp.json", function () {return response({value: "32faff1b1ef1ac3",diff --git a/lib/anonymous_action.rb b/lib/anonymous_action.rbnew file mode 100644index 00000000000..3e1b3d52af7--- /dev/null+++ b/lib/anonymous_action.rb@@ -0,0 +1,81 @@+# frozen_string_literal: true++# Lets anonymous users initiate actions that require an account.+#+# Clicking such an action stores the intent in a signed, short-lived cookie,+# then redirects to login/signup. When `CurrentUser#log_on_user` completes the+# authentication, the matching handler runs against the freshly-authed user+# and the cookie is cleared.+#+# Handlers are registered by name. Each handler receives `(user, params)` and+# must reuse the same service the user-initiated path would use, so guardian+# and policy checks remain authoritative.+#+# Example:+# AnonymousAction.register("like_post") do |user, params|+# post = Post.find_by(id: params["post_id"])+# next if !post || !user.guardian.can_see?(post)+# PostActionCreator.like(user, post)+# end+class AnonymousAction+ COOKIE = :_pending_anonymous_action+ EXPIRES_IN = 5.minutes++ class << self+ def register(type, &handler)+ handlers[type.to_s] = handler+ end++ def registered?(type)+ handlers.key?(type.to_s)+ end++ def handler_for(type)+ handlers[type.to_s]+ end++ def set(cookies, type:, params: {})+ raise Discourse::InvalidParameters.new(:type) if !registered?(type)++ cookies.signed[COOKIE] = cookie_options.merge(+ value: {+ "type" => type.to_s,+ "params" => params.to_h,+ },+ expires: EXPIRES_IN.from_now,+ )+ end++ def consume(user, cookies)+ data = cookies.signed[COOKIE]+ return if !data.is_a?(Hash)++ cookies.delete(COOKIE, **cookie_options)++ type = data["type"]+ handler = handler_for(type)+ return if !handler++ handler.call(user, data["params"] || {})+ rescue => e+ Discourse.warn_exception(+ e,+ message: "AnonymousAction handler failed for type: #{type.inspect}",+ )+ end++ def unregister(type)+ handlers.delete(type.to_s)+ end++ private++ def handlers+ @handlers ||= {}+ end++ def cookie_options+ { path: "/", httponly: true, same_site: :lax, secure: SiteSetting.force_https }+ end+ end+enddiff --git a/lib/current_user.rb b/lib/current_user.rbindex e5d94513a0a..6a8b684a95d 100644--- a/lib/current_user.rb+++ b/lib/current_user.rb@@ -14,9 +14,10 @@ module CurrentUser@current_user_provider = Discourse.current_user_provider.new({})end- def log_on_user(user, opts = {})+ def log_on_user(user, opts = {}, replay_anonymous_action: false)current_user_provider.log_on_user(user, session, cookies, opts)user.logged_in+ AnonymousAction.consume(user, cookies) if replay_anonymous_actionenddef log_off_user(push_subscription: nil)diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rbindex f83c1d30c03..3ea87917a5a 100644--- a/lib/plugin/instance.rb+++ b/lib/plugin/instance.rb@@ -243,6 +243,12 @@ class Plugin::InstanceDiscoursePluginRegistry.register_modifier(self, modifier_name, &blk)end+ # Register a handler for an action initiated by an anonymous user, to be+ # replayed against their account after they authenticate. See AnonymousAction.+ def register_anonymous_action(type, &block)+ reloadable_patch { AnonymousAction.register(type, &block) }+ end+# Applies to all sites in a multisite environment. Ignores plugin.enabled?def add_report(name, &block)reloadable_patch { |plugin| Report.add_report(name, &block) }diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjsindex 4de5332e747..3ded821b68f 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs@@ -42,6 +42,7 @@ export default class DiscoursePostEvent extends Component {@service currentUser;@service discoursePostEventApi;@service messageBus;+ @service siteSettings;@tracked event;@@ -93,6 +94,19 @@ export default class DiscoursePostEvent extends Component {return this.event.status === "public";}+ get showStatus() {+ if (this.currentUser) {+ return this.event.canUpdateAttendance;+ }+ // Anonymous users can RSVP on public events unless the site is+ // invite-only without requiring login (in which case they can't+ // complete the signup flow anyway).+ if (this.siteSettings.invite_only && !this.siteSettings.login_required) {+ return false;+ }+ return this.event.isPublic && !this.event.isClosed && !this.event.isExpired;+ }+get isStandaloneEvent() {return this.event.status === "standalone";}@@ -293,7 +307,7 @@ export default class DiscoursePostEvent extends Component {/>{{/if}}- {{#if @event.canUpdateAttendance}}+ {{#if this.showStatus}}<Status @event={{event}} />{{/if}}</PluginOutlet>diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/status.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/status.gjsindex 5a3926a2950..ce998e4d1e3 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/status.gjs+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/status.gjs@@ -6,6 +6,7 @@ import PluginOutlet from "discourse/components/plugin-outlet";import DMenu from "discourse/float-kit/components/d-menu";import lazyHash from "discourse/helpers/lazy-hash";import { popupAjaxError } from "discourse/lib/ajax-error";+import { deferAnonymousAction } from "discourse/lib/anonymous-action";import DButton from "discourse/ui-kit/d-button";import DComboButton from "discourse/ui-kit/d-combo-button";import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";@@ -56,6 +57,7 @@ const GoingDropdown = <template>export default class DiscoursePostEventStatus extends Component {@service appEvents;+ @service currentUser;@service discoursePostEventApi;@service site;@service siteSettings;@@ -173,6 +175,17 @@ export default class DiscoursePostEventStatus extends Component {}async _setAttendance(payload) {+ if (!this.currentUser) {+ if (!payload.status) {+ return;+ }+ return deferAnonymousAction(this, "rsvp_event", {+ event_id: this.args.event.id,+ status: payload.status,+ recurring: payload.recurring ?? false,+ });+ }+try {const event = this.args.event;const data = { status: payload.status, postId: event.id };diff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rbindex 70fdb205b8b..be31cc572d9 100644--- a/plugins/discourse-calendar/plugin.rb+++ b/plugins/discourse-calendar/plugin.rb@@ -773,4 +773,32 @@ after_initialize doreport.data = (group_usernames & on_holiday_usernames).map { |username| { username: username } }report.total = report.data.countend++ register_anonymous_action("rsvp_event") do |user, params|+ event_id = params["event_id"]+ recurring = ActiveModel::Type::Boolean.new.cast(params["recurring"])+ existing_invitee = DiscoursePostEvent::Invitee.find_by(post_id: event_id, user_id: user.id)++ if existing_invitee+ DiscoursePostEvent::UpdateInvitee.call(+ params: {+ event_id: event_id,+ invitee_id: existing_invitee.id,+ status: params["status"],+ recurring: recurring,+ },+ guardian: user.guardian,+ )+ else+ DiscoursePostEvent::CreateInvitee.call(+ params: {+ event_id: event_id,+ status: params["status"],+ recurring: recurring,+ user_id: user.id,+ },+ guardian: user.guardian,+ )+ end+ endenddiff --git a/plugins/discourse-calendar/spec/system/anonymous_user_rsvp_event_spec.rb b/plugins/discourse-calendar/spec/system/anonymous_user_rsvp_event_spec.rbnew file mode 100644index 00000000000..68443f691e8--- /dev/null+++ b/plugins/discourse-calendar/spec/system/anonymous_user_rsvp_event_spec.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++describe "Anonymous user RSVPing to an event" do+ fab!(:admin)+ fab!(:user) { Fabricate(:user, username: "testuser", password: "supersecurepassword") }+ fab!(:topic) { Fabricate(:topic, user: admin) }++ let(:post_event_page) { PageObjects::Pages::DiscourseCalendar::PostEvent.new }+ let(:login_page) { PageObjects::Pages::Login.new }++ before do+ SiteSetting.calendar_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ SiteSetting.discourse_post_event_allowed_on_groups = Group::AUTO_GROUPS[:staff]+ EmailToken.confirm(Fabricate(:email_token, user:).token)+ PostCreator.create!(+ admin,+ topic_id: topic.id,+ raw: "[event start='2222-02-22 14:22' status='public']\n[/event]",+ )+ end++ it "automatically saves the RSVP after login" do+ visit(topic.url)++ expect(post_event_page).to have_going_button++ post_event_page.going++ expect(login_page).to be_open++ login_page.fill(username: user.username, password: "supersecurepassword").click_login++ expect(page).to have_current_path(topic.url)+ expect(post_event_page).to have_going_status+ end++ it "overwrites an existing RSVP when an anon clicks a different status and logs in" do+ event = DiscoursePostEvent::Event.find(topic.first_post.id)+ DiscoursePostEvent::Invitee.create_attendance!(user.id, event.id, :not_going)++ visit(topic.url)+ post_event_page.going++ expect(login_page).to be_open+ login_page.fill(username: user.username, password: "supersecurepassword").click_login++ expect(page).to have_current_path(topic.url)+ expect(post_event_page).to have_going_status++ invitee = DiscoursePostEvent::Invitee.find_by(user_id: user.id, post_id: event.id)+ expect(invitee.status).to eq(DiscoursePostEvent::Invitee.statuses[:going])+ end++ context "when the site is invite-only without login required" do+ before do+ SiteSetting.invite_only = true+ SiteSetting.login_required = false+ end++ it "does not show RSVP buttons to anonymous users" do+ visit(topic.url)+ expect(post_event_page).to have_no_going_menu+ expect(page).to have_no_css(".going-button")+ end+ end+enddiff --git a/plugins/discourse-post-voting/assets/javascripts/discourse/components/post-voting-vote-controls.gjs b/plugins/discourse-post-voting/assets/javascripts/discourse/components/post-voting-vote-controls.gjsindex b79ff709143..1ab3f219624 100644--- a/plugins/discourse-post-voting/assets/javascripts/discourse/components/post-voting-vote-controls.gjs+++ b/plugins/discourse-post-voting/assets/javascripts/discourse/components/post-voting-vote-controls.gjs@@ -4,6 +4,7 @@ import { action } from "@ember/object";import { service } from "@ember/service";import DMenu from "discourse/float-kit/components/d-menu";import { popupAjaxError } from "discourse/lib/ajax-error";+import { deferAnonymousAction } from "discourse/lib/anonymous-action";import { i18n } from "discourse-i18n";import { castVote, removeVote } from "../lib/post-voting-utilities";import PostVotingButton from "./post-voting-button";@@ -45,7 +46,10 @@ export default class PostVotingVoteControls extends Component {@actionasync vote(direction) {if (!this.currentUser) {- return this.args.showLogin();+ return deferAnonymousAction(this, "vote_post", {+ post_id: this.args.post.id,+ direction,+ });}const post = this.args.post;diff --git a/plugins/discourse-post-voting/lib/post_voting/guardian_extension.rb b/plugins/discourse-post-voting/lib/post_voting/guardian_extension.rbindex 39be3e8a933..4dc82a8e7fe 100644--- a/plugins/discourse-post-voting/lib/post_voting/guardian_extension.rb+++ b/plugins/discourse-post-voting/lib/post_voting/guardian_extension.rb@@ -2,6 +2,23 @@module PostVotingmodule GuardianExtension+ def can_vote_on_post?(post, direction: nil)+ return false if !user+ return false if !post+ return false if !post.is_post_voting_topic?+ return false if !can_see?(post)+ return false if post.user_id == user.id+ return false if post.topic.archived?+ return false if post.topic.closed?+ if direction+ if PostVotingVote.exists?(votable: post, user_id: user.id, direction: direction)+ return false+ end+ return false if !PostVoting::VoteManager.can_undo(post, user)+ end+ true+ end+def can_edit_comment?(comment)return false if !userreturn true if comment.user_id == user.iddiff --git a/plugins/discourse-post-voting/plugin.rb b/plugins/discourse-post-voting/plugin.rbindex 56ad0675a8e..b667438fc37 100644--- a/plugins/discourse-post-voting/plugin.rb+++ b/plugins/discourse-post-voting/plugin.rb@@ -271,4 +271,14 @@ after_initialize doPostVoting::VoteManager.bulk_remove_votes_by(user)end,)++ register_anonymous_action("vote_post") do |user, params|+ direction = params["direction"].to_s+ next if direction != "up" && direction != "down"++ post = Post.find_by(id: params["post_id"])+ next if !user.guardian.can_vote_on_post?(post, direction: direction)++ PostVoting::VoteManager.vote(post, user, direction:)+ endenddiff --git a/plugins/discourse-post-voting/spec/lib/post_voting/guardian_extension_spec.rb b/plugins/discourse-post-voting/spec/lib/post_voting/guardian_extension_spec.rbnew file mode 100644index 00000000000..2968d9c55d8--- /dev/null+++ b/plugins/discourse-post-voting/spec/lib/post_voting/guardian_extension_spec.rb@@ -0,0 +1,69 @@+# frozen_string_literal: true++RSpec.describe PostVoting::GuardianExtension do+ fab!(:user)+ fab!(:other_user, :user)+ fab!(:topic) { Fabricate(:topic, subtype: Topic::POST_VOTING_SUBTYPE, user: other_user) }+ fab!(:post) { Fabricate(:post, topic:, user: other_user) }++ before { SiteSetting.post_voting_enabled = true }++ describe "#can_vote_on_post?" do+ it "returns true for a valid post-voting post" do+ expect(Guardian.new(user).can_vote_on_post?(post)).to eq(true)+ end++ it "returns false for anonymous users" do+ expect(Guardian.new(nil).can_vote_on_post?(post)).to eq(false)+ end++ it "returns false when the post is missing" do+ expect(Guardian.new(user).can_vote_on_post?(nil)).to eq(false)+ end++ it "returns false when the topic is not a post-voting topic" do+ regular_topic = Fabricate(:topic, user: other_user)+ regular_post = Fabricate(:post, topic: regular_topic, user: other_user)+ expect(Guardian.new(user).can_vote_on_post?(regular_post)).to eq(false)+ end++ it "returns false when the user owns the post" do+ own_post = Fabricate(:post, topic:, user: user)+ expect(Guardian.new(user).can_vote_on_post?(own_post)).to eq(false)+ end++ it "returns false when the topic is archived" do+ topic.update!(archived: true)+ expect(Guardian.new(user).can_vote_on_post?(post)).to eq(false)+ end++ it "returns false when the topic is closed" do+ topic.update!(closed: true)+ expect(Guardian.new(user).can_vote_on_post?(post)).to eq(false)+ end++ context "with a direction" do+ it "returns false when the user has already voted in that direction" do+ Fabricate(:post_voting_vote, votable: post, user: user, direction: "up")+ expect(Guardian.new(user).can_vote_on_post?(post, direction: "up")).to eq(false)+ end++ it "allows voting in the opposite direction within the undo window" do+ Fabricate(:post_voting_vote, votable: post, user: user, direction: "up")+ expect(Guardian.new(user).can_vote_on_post?(post, direction: "down")).to eq(true)+ end++ it "blocks direction switching after the undo window closes" do+ SiteSetting.post_voting_undo_vote_action_window = 5+ Fabricate(+ :post_voting_vote,+ votable: post,+ user: user,+ direction: "up",+ created_at: 10.minutes.ago,+ )+ expect(Guardian.new(user).can_vote_on_post?(post, direction: "down")).to eq(false)+ end+ end+ end+enddiff --git a/plugins/discourse-post-voting/spec/system/anonymous_user_vote_post_spec.rb b/plugins/discourse-post-voting/spec/system/anonymous_user_vote_post_spec.rbnew file mode 100644index 00000000000..1b10fa2b47c--- /dev/null+++ b/plugins/discourse-post-voting/spec/system/anonymous_user_vote_post_spec.rb@@ -0,0 +1,29 @@+# frozen_string_literal: true++RSpec.describe "Anonymous user voting on a post" do+ fab!(:user) { Fabricate(:user, username: "testuser", password: "supersecurepassword") }+ fab!(:topic_author) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:topic) { Fabricate(:topic, subtype: Topic::POST_VOTING_SUBTYPE, user: topic_author) }+ fab!(:question) { Fabricate(:post, topic:, user: topic_author) }+ fab!(:answer) { Fabricate(:post, topic:, user: topic_author) }++ let(:login_page) { PageObjects::Pages::Login.new }++ before do+ SiteSetting.post_voting_enabled = true+ EmailToken.confirm(Fabricate(:email_token, user:).token)+ end++ it "casts the upvote automatically after login" do+ visit(topic.url)++ find("#post_#{answer.post_number} .post-voting-post button.post-voting-button.--upvote").click++ expect(login_page).to be_open++ login_page.fill(username: user.username, password: "supersecurepassword").click_login++ expect(page).to have_current_path(topic.url)+ expect(PostVotingVote.exists?(votable: answer, user: user, direction: "up")).to eq(true)+ end+enddiff --git a/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-actions.gjs b/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-actions.gjsindex 6e30047ce53..f9ea1e2f58d 100644--- a/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-actions.gjs+++ b/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-actions.gjs@@ -18,6 +18,7 @@ import curryComponent from "ember-curry-component";import $ from "jquery";import { Promise } from "rsvp";import lazyHash from "discourse/helpers/lazy-hash";+import { deferAnonymousAction } from "discourse/lib/anonymous-action";import { isRailsTesting, isTesting } from "discourse/lib/environment";import { emojiUrlFor } from "discourse/lib/text";import { and, eq, not } from "discourse/truth-helpers";@@ -140,6 +141,29 @@ export default class DiscourseReactionsActions extends Component {return this.args.post;}+ get topicArchived() {+ // Archived topics reject reactions server-side. Closed topics still+ // accept them (see Guardian#post_can_act?), so don't gate on closed.+ return !!this.data?.topic?.archived;+ }++ get canReact() {+ if (this.topicArchived) {+ return false;+ }++ // Anonymous users can pick a reaction — it gets deferred until login.+ if (!this.currentUser) {+ return true;+ }++ return (+ (!this.data.current_user_reaction ||+ this.data.current_user_reaction.can_undo) &&+ this.data.likeAction?.canToggle+ );+ }+get classes() {if (!this.data?.reactions) {return;@@ -176,11 +200,7 @@ export default class DiscourseReactionsActions extends Component {classes.push("has-used-main-reaction");}- if (- (!this.data.current_user_reaction ||- this.data.current_user_reaction.can_undo) &&- this.data.likeAction?.canToggle- ) {+ if (this.canReact) {classes.push("can-toggle-reaction");}@@ -294,11 +314,15 @@ export default class DiscourseReactionsActions extends Component {}@action- toggle(params) {+ async toggle(params) {if (!this.currentUser) {- if (this.args.showLogin) {- return this.args.showLogin();+ if (!this.canReact) {+ return;}+ return deferAnonymousAction(this, "react_to_post", {+ post_id: this.data.id,+ reaction: params.reaction,+ });}if (@@ -490,11 +514,15 @@ export default class DiscourseReactionsActions extends Component {}@action- toggleFromButton(attrs) {+ async toggleFromButton(attrs) {if (!this.currentUser) {- if (this.args.showLogin) {- return this.args.showLogin();+ if (!this.canReact) {+ return;}+ return deferAnonymousAction(this, "react_to_post", {+ post_id: this.data.id,+ reaction: attrs.reaction,+ });}this.collapseAllPanels();@@ -760,11 +788,16 @@ export default class DiscourseReactionsActions extends Component {}get showReactionsPicker() {- return (- this.currentUser &&- this.data.user_id !== this.currentUser.id &&- this.reactionsPickerExpanded- );+ if (!this.reactionsPickerExpanded) {+ return false;+ }++ // Anonymous users can pick a reaction — it gets deferred until they log in.+ if (!this.currentUser) {+ return this.canReact;+ }++ return this.data.user_id !== this.currentUser.id;}@actiondiff --git a/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-picker.gjs b/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-picker.gjsindex d91145c474d..beb7fa32d93 100644--- a/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-picker.gjs+++ b/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-picker.gjs@@ -10,6 +10,7 @@ import dEmoji from "discourse/ui-kit/helpers/d-emoji";import { i18n } from "discourse-i18n";export default class DiscourseReactionsPicker extends Component {+ @service currentUser;@service siteSettings;emojiPickerIsOpen = false;@@ -62,7 +63,12 @@ export default class DiscourseReactionsPicker extends Component {isUsed = currentUserReaction && currentUserReaction.id === reaction;}- if (currentUserReaction) {+ if (!this.currentUser) {+ // Anonymous users can pick a reaction — it gets deferred until login.+ // Disallow on archived/closed topics where no one can react.+ const topic = post.topic;+ canUndo = !(topic?.archived || topic?.closed);+ } else if (currentUserReaction) {canUndo = currentUserReaction.can_undo && post.likeAction?.canToggle;} else {canUndo = post.likeAction?.canToggle;diff --git a/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-reaction-button.gjs b/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-reaction-button.gjsindex 2d0660d6556..f9c9d0cee7e 100644--- a/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-reaction-button.gjs+++ b/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-reaction-button.gjs@@ -37,6 +37,17 @@ export default class ReactionsReactionButton extends Component {this.args.cancelCollapse();+ // Anonymous users haven't authenticated yet — they can still pick a+ // reaction, it gets deferred until login. Archived topics reject+ // reactions server-side; closed topics still accept them.+ if (!this.currentUser) {+ if (this.args.post.topic?.archived) {+ return;+ }+ this.args.toggleReactions(event);+ return;+ }+const likeAction = this.args.post.likeAction;if (!likeAction?.canToggle) {return;diff --git a/plugins/discourse-reactions/plugin.rb b/plugins/discourse-reactions/plugin.rbindex 9a10dfa5c1f..004407c7835 100644--- a/plugins/discourse-reactions/plugin.rb+++ b/plugins/discourse-reactions/plugin.rb@@ -62,6 +62,14 @@ after_initialize doNotification.singleton_class.prepend DiscourseReactions::NotificationExtensionend+ register_anonymous_action("react_to_post") do |user, params|+ post = Post.find_by(id: params["post_id"])+ next if !post || !user.guardian.can_see?(post)+ reaction_value = params["reaction"].to_s+ next if !DiscourseReactions::Reaction.valid?(reaction_value)+ DiscourseReactions::ReactionManager.new(reaction_value:, user:, post:).toggle!+ end+Discourse::Application.routes.append { mount DiscourseReactions::Engine, at: "/" }TopicView.on_preload do |topic_view|diff --git a/plugins/discourse-reactions/spec/system/anonymous_user_react_post_spec.rb b/plugins/discourse-reactions/spec/system/anonymous_user_react_post_spec.rbnew file mode 100644index 00000000000..d2427104031--- /dev/null+++ b/plugins/discourse-reactions/spec/system/anonymous_user_react_post_spec.rb@@ -0,0 +1,37 @@+# frozen_string_literal: true++describe "Anonymous user reacting to a post" do+ fab!(:user) { Fabricate(:user, username: "testuser", password: "supersecurepassword") }+ fab!(:topic)+ fab!(:post) { Fabricate(:post, topic:) }++ let(:login_page) { PageObjects::Pages::Login.new }++ before do+ SiteSetting.discourse_reactions_enabled = true+ EmailToken.confirm(Fabricate(:email_token, user:).token)+ end++ shared_examples "replays the reaction after login" do+ it "applies the main reaction automatically after login" do+ visit(topic.url)++ find("#post_#{post.post_number} .discourse-reactions-reaction-button").click++ expect(login_page).to be_open++ login_page.fill(username: user.username, password: "supersecurepassword").click_login++ expect(page).to have_current_path(topic.url)+ expect(post.reload.like_count).to eq(1)+ end+ end++ include_examples "replays the reaction after login"++ context "when the topic is closed" do+ before { topic.update!(closed: true) }++ include_examples "replays the reaction after login"+ end+enddiff --git a/plugins/discourse-topic-voting/assets/javascripts/discourse/components/vote-button.gjs b/plugins/discourse-topic-voting/assets/javascripts/discourse/components/vote-button.gjsindex 34205bb0471..f09f8fb2725 100644--- a/plugins/discourse-topic-voting/assets/javascripts/discourse/components/vote-button.gjs+++ b/plugins/discourse-topic-voting/assets/javascripts/discourse/components/vote-button.gjs@@ -4,6 +4,7 @@ import { action } from "@ember/object";import { service } from "@ember/service";import DMenu from "discourse/float-kit/components/d-menu";import DTooltip from "discourse/float-kit/components/d-tooltip";+import { deferAnonymousAction } from "discourse/lib/anonymous-action";import { NotificationLevels } from "discourse/lib/notification-levels";import { applyBehaviorTransformer } from "discourse/lib/transformer";import { and, eq, not } from "discourse/truth-helpers";@@ -14,7 +15,6 @@ import { i18n } from "discourse-i18n";export default class VoteBox extends Component {@service currentUser;- @service router;@tracked hasVoted = false;@tracked hasSeenSuccessMenu = false;@@ -70,9 +70,14 @@ export default class VoteBox extends Component {this.hasSeenSuccessMenu = false;}- applyBehaviorTransformer("topic-vote-button-click", () => {+ applyBehaviorTransformer("topic-vote-button-click", async () => {if (!this.currentUser) {- return this.router.transitionTo("login");+ if (this.topic.archived || this.topic.closed) {+ return;+ }+ return deferAnonymousAction(this, "vote_topic", {+ topic_id: this.topic.id,+ });}if (this.currentUser.vote_limit === 0) {diff --git a/plugins/discourse-topic-voting/plugin.rb b/plugins/discourse-topic-voting/plugin.rbindex 212c0cfb77a..8cc735c782f 100755--- a/plugins/discourse-topic-voting/plugin.rb+++ b/plugins/discourse-topic-voting/plugin.rb@@ -240,4 +240,13 @@ after_initialize dousername: RouteFormat.username,}end++ register_anonymous_action("vote_topic") do |user, params|+ DiscourseTopicVoting::Votes::Cast.call(+ params: {+ topic_id: params["topic_id"],+ },+ guardian: user.guardian,+ )+ endenddiff --git a/plugins/discourse-topic-voting/spec/system/anonymous_user_vote_topic_spec.rb b/plugins/discourse-topic-voting/spec/system/anonymous_user_vote_topic_spec.rbnew file mode 100644index 00000000000..29c8a41139f--- /dev/null+++ b/plugins/discourse-topic-voting/spec/system/anonymous_user_vote_topic_spec.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++RSpec.describe "Anonymous user voting on a topic" do+ fab!(:user) { Fabricate(:user, username: "testuser", password: "supersecurepassword") }+ fab!(:category) { Fabricate(:category, name: "voting category") }+ fab!(:topic) { Fabricate(:topic, category:) }+ fab!(:post) { Fabricate(:post, topic:) }++ let(:topic_page) { PageObjects::Pages::Topic.new }+ let(:login_page) { PageObjects::Pages::Login.new }++ before do+ SiteSetting.topic_voting_enabled = true+ DiscourseTopicVoting::CategorySetting.create!(category_id: category.id)+ Category.reset_voting_cache+ EmailToken.confirm(Fabricate(:email_token, user:).token)+ end++ it "casts the vote automatically after login" do+ topic_page.visit_topic(topic)++ topic_page.vote++ expect(login_page).to be_open++ login_page.fill(username: user.username, password: "supersecurepassword").click_login++ expect(page).to have_current_path(topic.url)+ expect(DiscourseTopicVoting::Vote.exists?(user: user, topic: topic)).to eq(true)+ end+enddiff --git a/plugins/poll/assets/javascripts/discourse/components/poll-options.gjs b/plugins/poll/assets/javascripts/discourse/components/poll-options.gjsindex ab440fa84b5..4be738f5513 100644--- a/plugins/poll/assets/javascripts/discourse/components/poll-options.gjs+++ b/plugins/poll/assets/javascripts/discourse/components/poll-options.gjs@@ -2,8 +2,6 @@ import Component from "@glimmer/component";import { fn } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";-import { service } from "@ember/service";-import routeAction from "discourse/helpers/route-action";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";@@ -11,8 +9,6 @@ import decoratePollOption from "../modifiers/decorate-poll-option";import PollOptionRankedChoice from "./poll-option-ranked-choice";export default class PollOptionsComponent extends Component {- @service currentUser;-isChosen = (option) => {return this.args.votes.includes(option.id);};@@ -75,47 +71,25 @@ export default class PollOptionsComponent extends Component {/>{{else}}<li data-poll-option-id={{option.id}}>- {{#if this.currentUser}}- <button {{on "click" (fn this.sendClick option)}}>- {{#if (this.isChosen option)}}- {{#if @isCheckbox}}- {{dIcon "far-square-check"}}- {{else}}- {{dIcon "circle"}}- {{/if}}+ <button {{on "click" (fn this.sendClick option)}}>+ {{#if (this.isChosen option)}}+ {{#if @isCheckbox}}+ {{dIcon "far-square-check"}}{{else}}- {{#if @isCheckbox}}- {{dIcon "far-square"}}- {{else}}- {{dIcon "far-circle"}}- {{/if}}+ {{dIcon "circle"}}{{/if}}- <span- class="option-text"- {{decoratePollOption option.html}}- ></span>- </button>- {{else}}- <button {{on "click" (routeAction "showLogin")}}>- {{#if (this.isChosen option)}}- {{#if @isCheckbox}}- {{dIcon "far-square-check"}}- {{else}}- {{dIcon "circle"}}- {{/if}}+ {{else}}+ {{#if @isCheckbox}}+ {{dIcon "far-square"}}{{else}}- {{#if @isCheckbox}}- {{dIcon "far-square"}}- {{else}}- {{dIcon "far-circle"}}- {{/if}}+ {{dIcon "far-circle"}}{{/if}}- <span- class="option-text"- {{decoratePollOption option.html}}- ></span>- </button>- {{/if}}+ {{/if}}+ <span+ class="option-text"+ {{decoratePollOption option.html}}+ ></span>+ </button></li>{{/if}}{{/each}}diff --git a/plugins/poll/assets/javascripts/discourse/components/poll.gjs b/plugins/poll/assets/javascripts/discourse/components/poll.gjsindex 2f59661f0ba..dc1ee39b9b5 100644--- a/plugins/poll/assets/javascripts/discourse/components/poll.gjs+++ b/plugins/poll/assets/javascripts/discourse/components/poll.gjs@@ -2,12 +2,14 @@ import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { on } from "@ember/modifier";import { action } from "@ember/object";+import { getOwner } from "@ember/owner";import { trackedObject } from "@ember/reactive/collections";import didUpdate from "@ember/render-modifiers/modifiers/did-update";import { service } from "@ember/service";import { trustHTML } from "@ember/template";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";+import { deferAnonymousAction } from "discourse/lib/anonymous-action";import round from "discourse/lib/round";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";@@ -320,13 +322,28 @@ export default class PollComponent extends Component {}@action- toggleOption(option, rank = 0) {+ async toggleOption(option, rank = 0) {if (this.closed) {return;}if (!this.currentUser) {- // unlikely, handled by template logic+ // Archived topics reject votes server-side, so don't queue them.+ // Closed topics still accept votes from regular users, so let anon+ // queue and replay after login.+ if (this.post?.topic?.archived) {+ return;+ }+ if (!this.isMultiple && !this.isRankedChoice) {+ return deferAnonymousAction(this, "vote_poll", {+ post_id: this.post.id,+ poll_name: this.poll.name,+ options: [option.id],+ });+ }+ // Multi-choice / ranked-choice anonymous votes can't be saved on a+ // single click since the selection isn't complete until "Cast Votes".+ getOwner(this).lookup("route:application").send("showLogin");return;}diff --git a/plugins/poll/plugin.rb b/plugins/poll/plugin.rbindex 542b838992c..571840dcc39 100644--- a/plugins/poll/plugin.rb+++ b/plugins/poll/plugin.rb@@ -262,4 +262,17 @@ after_initialize dopostsendend++ # Only single-choice (regular) polls are supported for anonymous voting.+ # Multi-choice and ranked-choice polls require accumulating selections+ # client-side, which is out of scope for the current anonymous flow.+ register_anonymous_action("vote_poll") do |user, params|+ options = params["options"]+ next if !options.is_a?(Array) || options.size != 1++ DiscoursePoll::Poll.vote(user, params["post_id"], params["poll_name"], options)+ rescue DiscoursePoll::Error+ # Expected business-logic failures (poll closed, group-restricted, etc.)+ # — silently drop. Unexpected exceptions still bubble to AnonymousAction.consume.+ endenddiff --git a/plugins/poll/spec/system/anonymous_user_vote_poll_spec.rb b/plugins/poll/spec/system/anonymous_user_vote_poll_spec.rbnew file mode 100644index 00000000000..8b74ff97b10--- /dev/null+++ b/plugins/poll/spec/system/anonymous_user_vote_poll_spec.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++describe "Anonymous user voting on a poll" do+ fab!(:user) { Fabricate(:user, username: "testuser", password: "supersecurepassword") }+ fab!(:topic)+ fab!(:post) { Fabricate(:post, topic:, raw: <<~RAW) }+ [poll type=regular results=always]+ * Option A+ * Option B+ [/poll]+ RAW++ let(:topic_page) { PageObjects::Pages::Topic.new }+ let(:poll_page) { PageObjects::Pages::Poll.new(topic_page:) }+ let(:login_page) { PageObjects::Pages::Login.new }++ before do+ SiteSetting.poll_enabled = true+ EmailToken.confirm(Fabricate(:email_token, user:).token)+ end++ shared_examples "replays the vote after login" do+ it "casts the vote automatically after login (single-choice poll)" do+ topic_page.visit_topic(topic)++ poll_page.vote_for_option(post, "Option A")++ expect(login_page).to be_open++ login_page.fill(username: user.username, password: "supersecurepassword").click_login++ expect(page).to have_current_path(topic.url)+ expect(PollVote.where(user: user).count).to eq(1)+ end+ end++ include_examples "replays the vote after login"++ context "when the topic is closed" do+ before { topic.update!(closed: true) }++ include_examples "replays the vote after login"+ end+enddiff --git a/spec/lib/anonymous_action_spec.rb b/spec/lib/anonymous_action_spec.rbnew file mode 100644index 00000000000..af2fc599485--- /dev/null+++ b/spec/lib/anonymous_action_spec.rb@@ -0,0 +1,96 @@+# frozen_string_literal: true++RSpec.describe AnonymousAction do+ fab!(:user)++ # Minimal stand-in for ActionDispatch::Cookies::CookieJar that the lib+ # interacts with via `cookies.signed[key]`/`cookies.delete(key, **opts)`.+ let(:cookies) do+ Class+ .new do+ def initialize+ @store = {}+ end++ def signed+ @store+ end++ def delete(key, **_opts)+ @store.delete(key)+ end+ end+ .new+ end++ before do+ AnonymousAction.register("anon_action_spec_test") do |handler_user, params|+ post = Post.find_by(id: params["post_id"])+ PostActionCreator.like(handler_user, post) if post+ end+ end++ after { AnonymousAction.unregister("anon_action_spec_test") }++ describe ".registered?" do+ it "returns true for registered types" do+ expect(AnonymousAction.registered?("anon_action_spec_test")).to eq(true)+ end++ it "returns false for unknown types" do+ expect(AnonymousAction.registered?("unknown_action")).to eq(false)+ end+ end++ describe ".set" do+ it "raises for an unregistered type" do+ expect { AnonymousAction.set(cookies, type: "ghost_action", params: {}) }.to raise_error(+ Discourse::InvalidParameters,+ )+ end+ end++ describe ".consume" do+ fab!(:post)++ it "runs the matching handler and clears the cookie" do+ cookies.signed[AnonymousAction::COOKIE] = {+ "type" => "anon_action_spec_test",+ "params" => {+ "post_id" => post.id,+ },+ }++ expect { AnonymousAction.consume(user, cookies) }.to change {+ PostAction.where(post: post, user: user).count+ }.by(1)++ expect(cookies.signed[AnonymousAction::COOKIE]).to be_nil+ end++ it "no-ops without a cookie" do+ expect { AnonymousAction.consume(user, cookies) }.not_to raise_error+ end++ it "ignores unknown handler types and clears the cookie" do+ cookies.signed[AnonymousAction::COOKIE] = { "type" => "ghost", "params" => {} }++ expect { AnonymousAction.consume(user, cookies) }.not_to raise_error+ expect(cookies.signed[AnonymousAction::COOKIE]).to be_nil+ end++ it "swallows handler exceptions" do+ AnonymousAction.register("anon_action_spec_boom") { |_, _| raise "kaboom" }+ cookies.signed[AnonymousAction::COOKIE] = {+ "type" => "anon_action_spec_boom",+ "params" => {+ },+ }++ expect { AnonymousAction.consume(user, cookies) }.not_to raise_error+ expect(cookies.signed[AnonymousAction::COOKIE]).to be_nil+ ensure+ AnonymousAction.unregister("anon_action_spec_boom")+ end+ end+enddiff --git a/spec/requests/anonymous_actions_controller_spec.rb b/spec/requests/anonymous_actions_controller_spec.rbnew file mode 100644index 00000000000..cd4667a189e--- /dev/null+++ b/spec/requests/anonymous_actions_controller_spec.rb@@ -0,0 +1,65 @@+# frozen_string_literal: true++RSpec.describe AnonymousActionsController do+ let(:type) { "anon_actions_controller_spec_test" }++ before { AnonymousAction.register(type) { |_, _| } }+ after { AnonymousAction.unregister(type) }++ def do_post(payload = { type:, params: {} })+ post "/anonymous-action.json", params: payload+ end++ describe "#create" do+ it "sets a signed cookie for a registered type" do+ do_post(type:, params: { post_id: 42 })++ expect(response.status).to eq(204)+ expect(response.cookies[AnonymousAction::COOKIE.to_s]).to be_present+ end++ it "rejects unknown action types" do+ do_post(type: "ghost_action", params: {})++ expect(response.status).to eq(400)+ end++ it "requires the type param" do+ do_post(params: { post_id: 1 })++ expect(response.status).to eq(400)+ end++ it "rejects logged-in users" do+ sign_in(Fabricate(:user))++ do_post(type:, params: { post_id: 42 })++ expect(response.status).to eq(403)+ expect(response.cookies[AnonymousAction::COOKIE.to_s]).to be_nil+ end++ it "rejects oversized params" do+ do_post(type:, params: { junk: "x" * (AnonymousActionsController::MAX_PARAMS_BYTES + 1) })++ expect(response.status).to eq(400)+ expect(response.cookies[AnonymousAction::COOKIE.to_s]).to be_nil+ end++ context "when rate-limited" do+ before { RateLimiter.enable }++ it "returns 429 after exceeding the per-minute limit" do+ 10.times do+ do_post+ expect(response.status).to eq(204)+ end++ do_post++ expect(response.status).to eq(429)+ expect(response.parsed_body["error_type"]).to eq("rate_limit")+ end+ end+ end+enddiff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rbindex 6376f702a72..91c392abfc8 100644--- a/spec/requests/session_controller_spec.rb+++ b/spec/requests/session_controller_spec.rb@@ -587,6 +587,14 @@ RSpec.describe SessionController doexpect(response.body).to include("User #{user.username} is not active")expect(session[:current_user_id]).to be_blankend++ it "does not replay a queued anonymous action" do+ AnonymousAction.expects(:consume).never++ get "/session/#{user.username}/become"++ expect(response).to be_redirect+ endendenddiff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rbindex 0973713ad4c..446ff7d6906 100644--- a/spec/requests/users_controller_spec.rb+++ b/spec/requests/users_controller_spec.rb@@ -797,6 +797,16 @@ RSpec.describe UsersController doexpect(response.status).to eq(200)expect(session[:current_user_id]).to eq(user.id)end++ it "does not replay queued anonymous actions on toggle" do+ SiteSetting.allow_anonymous_mode = true+ sign_in(Fabricate(:user, trust_level: TrustLevel[1]))++ AnonymousAction.expects(:consume).never++ post "/u/toggle-anon.json"+ expect(response.status).to eq(200)+ endenddescribe "#create" dodiff --git a/spec/system/anonymous_user_like_post_spec.rb b/spec/system/anonymous_user_like_post_spec.rbnew file mode 100644index 00000000000..8e44c863d89--- /dev/null+++ b/spec/system/anonymous_user_like_post_spec.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true++describe "Anonymous user liking a post" do+ fab!(:user) { Fabricate(:user, username: "testuser", password: "supersecurepassword") }+ fab!(:topic)+ fab!(:post) { Fabricate(:post, topic:) }++ let(:topic_page) { PageObjects::Pages::Topic.new }+ let(:login_page) { PageObjects::Pages::Login.new }++ before { EmailToken.confirm(Fabricate(:email_token, user:).token) }++ shared_examples "replays the like after login" do+ it "automatically likes the post after login" do+ topic_page.visit_topic(topic)+ topic_page.click_post_action_button(post, :like)++ expect(login_page).to be_open++ login_page.fill(username: user.username, password: "supersecurepassword").click_login++ expect(page).to have_current_path(topic.url)+ expect(topic_page).to have_post_action_button(post, :like_count)+ expect(post.reload.like_count).to eq(1)+ end+ end++ include_examples "replays the like after login"++ context "when the topic is closed" do+ before { topic.update!(closed: true) }++ include_examples "replays the like after login"+ end+end