Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Support silent, post-linked badge grants through the API (#43911)

Mark VanLandingham6d6919f342da
diff --git a/app/controllers/user_badges_controller.rb b/app/controllers/user_badges_controller.rb
index 008abd78ade..a52eb7f2af9 100644
--- a/app/controllers/user_badges_controller.rb
+++ b/app/controllers/user_badges_controller.rb
@@ -90,7 +90,18 @@ class UserBadgesController < ApplicationController
badge = fetch_badge_from_params
post_id = nil
- if params[:reason].present?
+ if params.key?(:post_id)
+ raise Discourse::InvalidParameters.new(:post_id) if params[:reason].present?
+
+ post_id = Integer(params[:post_id].to_s, 10, exception: false)
+ raise Discourse::InvalidParameters.new(:post_id) if post_id.nil? || post_id < 1
+
+ post = Post.find_by(id: post_id)
+ raise Discourse::NotFound if post.blank?
+
+ guardian.ensure_can_see!(post)
+ post_id = post.id
+ elsif params[:reason].present?
unless is_badge_reason_valid? params[:reason]
return(
render json: failed_json.merge(message: I18n.t("invalid_grant_badge_reason_link")),
@@ -111,7 +122,11 @@ class UserBadgesController < ApplicationController
grant_opts_from_params =
DiscoursePluginRegistry.apply_modifier(
:user_badges_badge_grant_opts,
- { granted_by: current_user, post_id: post_id },
+ {
+ granted_by: current_user,
+ post_id: post_id,
+ suppress_notification: params[:suppress_notification].to_s == "true",
+ },
{ param: params },
)
diff --git a/app/services/badge_granter.rb b/app/services/badge_granter.rb
index ddb61cdfe6b..5bb63a551c5 100644
--- a/app/services/badge_granter.rb
+++ b/app/services/badge_granter.rb
@@ -150,7 +150,12 @@ class BadgeGranter
end
skip_new_user_tips = @user.user_option.skip_new_user_tips
- unless self.class.suppress_notification?(@badge, user_badge.granted_at, skip_new_user_tips)
+ unless @opts[:suppress_notification] ||
+ self.class.suppress_notification?(
+ @badge,
+ user_badge.granted_at,
+ skip_new_user_tips,
+ )
notification =
self.class.send_notification(@user.id, @user.username, @user.effective_locale, @badge)
user_badge.update!(notification_id: notification.id)
diff --git a/spec/requests/api/schemas/json/user_badge_grant_request.json b/spec/requests/api/schemas/json/user_badge_grant_request.json
new file mode 100644
index 00000000000..483f64bd88c
--- /dev/null
+++ b/spec/requests/api/schemas/json/user_badge_grant_request.json
@@ -0,0 +1,46 @@
+{
+ "additionalProperties": false,
+ "properties": {
+ "username": {
+ "type": "string",
+ "description": "The username of the user to grant the badge to."
+ },
+ "badge_id": {
+ "type": "integer",
+ "description": "The ID of the badge to grant. Either badge_id or badge_name is required."
+ },
+ "badge_name": {
+ "type": "string",
+ "description": "The name of the badge to grant. Either badge_id or badge_name is required."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Optional URL of a post or topic associated with the grant. Cannot be used together with post_id."
+ },
+ "post_id": {
+ "type": "integer",
+ "minimum": 1,
+ "description": "Optional ID of a visible, non-deleted post associated with the grant. Cannot be used together with reason."
+ },
+ "suppress_notification": {
+ "type": "boolean",
+ "default": false,
+ "description": "Suppress the notification for this grant only. Omit or set to false to preserve normal notification behavior, including existing suppression rules. The badge is still granted and grant events still occur."
+ }
+ },
+ "required": [
+ "username"
+ ],
+ "anyOf": [
+ {
+ "required": [
+ "badge_id"
+ ]
+ },
+ {
+ "required": [
+ "badge_name"
+ ]
+ }
+ ]
+}
diff --git a/spec/requests/api/user_badges_spec.rb b/spec/requests/api/user_badges_spec.rb
index e3198f47126..4b79821645c 100644
--- a/spec/requests/api/user_badges_spec.rb
+++ b/spec/requests/api/user_badges_spec.rb
@@ -3,12 +3,38 @@ require "swagger_helper"
RSpec.describe "user_badges" do
let(:admin) { Fabricate(:admin) }
+ let(:badge) { Fabricate(:badge) }
+ let(:user) { Fabricate(:user) }
+ let(:associated_post) { Fabricate(:post) }
before do
Jobs.run_immediately!
sign_in(admin)
end
+ path "/user_badges.json" do
+ post "Grant a badge to a user" do
+ tags "Badges", "Users"
+ operationId "grantUserBadge"
+ consumes "application/json"
+ expected_request_schema = load_spec_schema("user_badge_grant_request")
+ parameter name: :params, in: :body, schema: expected_request_schema
+
+ produces "application/json"
+ response "200", "badge granted" do
+ expected_response_schema = nil
+ let(:params) do
+ { "username" => user.username, "badge_id" => badge.id, "post_id" => associated_post.id }
+ end
+
+ it_behaves_like "a JSON endpoint", 200 do
+ let(:expected_response_schema) { expected_response_schema }
+ let(:expected_request_schema) { expected_request_schema }
+ end
+ end
+ end
+ end
+
path "/user-badges/{username}.json" do
get "List badges for a user" do
tags "Badges", "Users"
diff --git a/spec/requests/user_badges_controller_spec.rb b/spec/requests/user_badges_controller_spec.rb
index 31c17a8e31c..7fa2cd5739d 100644
--- a/spec/requests/user_badges_controller_spec.rb
+++ b/spec/requests/user_badges_controller_spec.rb
@@ -243,7 +243,12 @@ RSpec.describe UserBadgesController do
it "does not allow regular users to grant badges" do
sign_in(Fabricate(:user))
- post "/user_badges.json", params: { badge_id: badge.id, username: user.username }
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ suppress_notification: true,
+ }
expect(response.status).to eq(403)
end
@@ -270,6 +275,213 @@ RSpec.describe UserBadgesController do
expect(UserHistory.where(acting_user: admin, target_user: user).count).to eq(1)
end
+ it "grants a badge associated with a direct post ID from an authenticated API request" do
+ associated_post = Fabricate(:post, user: Fabricate(:user))
+ api_key = Fabricate(:api_key)
+
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ post_id: associated_post.id,
+ },
+ headers: {
+ HTTP_API_KEY: api_key.key,
+ HTTP_API_USERNAME: "system",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(UserBadge.find_by!(user:, badge:).post_id).to eq(associated_post.id)
+ end
+
+ it "silently grants a multiple-grant badge once for a distinct direct post ID" do
+ badge.update!(multiple_grant: true)
+ first_post = Fabricate(:post, user: user)
+ second_post = Fabricate(:post, user: user)
+ api_key = Fabricate(:api_key)
+ headers = { HTTP_API_KEY: api_key.key, HTTP_API_USERNAME: "system" }
+ granted_badge_notifications =
+ user.notifications.where(notification_type: Notification.types[:granted_badge])
+
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ post_id: first_post.id,
+ },
+ headers: headers
+ expect(response.status).to eq(200)
+ expect(granted_badge_notifications.count).to eq(1)
+
+ %w[true false].each do |suppress_notification|
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ post_id: second_post.id,
+ suppress_notification: suppress_notification,
+ },
+ headers: headers
+ expect(response.status).to eq(200)
+ end
+
+ expect(UserBadge.where(user:, badge:).pluck(:post_id)).to contain_exactly(
+ first_post.id,
+ second_post.id,
+ )
+ expect(granted_badge_notifications.count).to eq(1)
+ expect(
+ UserBadge.find_by!(user:, badge:, post_id: first_post.id).notification_id,
+ ).to be_present
+ expect(UserBadge.find_by!(user:, badge:, post_id: second_post.id).notification_id).to be_nil
+ end
+
+ it "rejects malformed, missing, and deleted direct post IDs without granting a badge" do
+ existing_post = Fabricate(:post)
+ deleted_post = Fabricate(:post)
+ deleted_post.trash!(admin)
+ sign_in(admin)
+
+ [
+ nil,
+ [],
+ [existing_post.id],
+ {},
+ { id: existing_post.id },
+ 0,
+ -1,
+ "1.5",
+ existing_post.id + 0.5,
+ ].each do |post_id|
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ post_id: post_id,
+ },
+ as: :json
+
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ [Post.maximum(:id) + 1, deleted_post.id].each do |post_id|
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ post_id: post_id,
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ expect(UserBadge.exists?(user:, badge:)).to eq(false)
+ end
+
+ it "silently grants a multiple-grant badge associated through a reason URL" do
+ badge.update!(multiple_grant: true)
+ associated_post = Fabricate(:post, user: user)
+ sign_in(admin)
+
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ reason: Discourse.base_url + associated_post.url,
+ suppress_notification: true,
+ }
+
+ expect(response).to have_http_status(:ok)
+ user_badge = UserBadge.find_by!(user:, badge:)
+ expect(user_badge.post_id).to eq(associated_post.id)
+ expect(user_badge.notification_id).to be_nil
+ expect(
+ user.notifications.where(notification_type: Notification.types[:granted_badge]),
+ ).to be_empty
+ end
+
+ it "rejects a direct post ID together with a nonblank reason" do
+ associated_post = Fabricate(:post)
+ sign_in(admin)
+
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ post_id: associated_post.id,
+ reason: Discourse.base_url + associated_post.url,
+ }
+
+ expect(response).to have_http_status(:bad_request)
+ expect(UserBadge.exists?(user:, badge:)).to eq(false)
+ end
+
+ it "only allows a moderator to associate posts they can see" do
+ moderator = Fabricate(:moderator)
+ private_message_post = Fabricate(:private_message_post)
+ group = Fabricate(:group)
+ restricted_category = Fabricate(:private_category, group: group)
+ restricted_post = Fabricate(:post, topic: Fabricate(:topic, category: restricted_category))
+ accessible_post = Fabricate(:post)
+ sign_in(moderator)
+
+ [private_message_post, restricted_post].each do |inaccessible_post|
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ post_id: inaccessible_post.id,
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ expect(UserBadge.exists?(user:, badge:)).to eq(false)
+
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ post_id: accessible_post.id,
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(UserBadge.find_by!(user:, badge:).post_id).to eq(accessible_post.id)
+ end
+
+ it "does not suppress notifications for the string false" do
+ sign_in(admin)
+
+ post "/user_badges.json",
+ params: {
+ badge_id: badge.id,
+ username: user.username,
+ suppress_notification: "false",
+ }
+
+ expect(response.status).to eq(200)
+ expect(
+ user.notifications.where(notification_type: Notification.types[:granted_badge]).count,
+ ).to eq(1)
+ end
+
+ it "suppresses notifications for JSON true" do
+ sign_in(admin)
+
+ post "/user_badges.json",
+ params: {
+ badge_name: badge.name,
+ username: user.username,
+ suppress_notification: true,
+ },
+ as: :json
+
+ expect(response.status).to eq(200)
+ expect(UserBadge.exists?(user:, badge:)).to eq(true)
+ expect(
+ user.notifications.where(notification_type: Notification.types[:granted_badge]),
+ ).to be_empty
+ end
+
it "does not grant badges from regular api calls" do
api_key = Fabricate(:api_key, user: user)
diff --git a/spec/services/badge_granter_spec.rb b/spec/services/badge_granter_spec.rb
index 6e18bc0329a..80abe76315e 100644
--- a/spec/services/badge_granter_spec.rb
+++ b/spec/services/badge_granter_spec.rb
@@ -379,6 +379,27 @@ RSpec.describe BadgeGranter do
expect(Notification.where(user:).count).to eq(0)
end
+ it "suppresses notifications without changing grant side effects" do
+ events =
+ DiscourseEvent.track_events { BadgeGranter.grant(badge, user, suppress_notification: true) }
+
+ expect(UserBadge.exists?(badge:, user:)).to eq(true)
+ expect(badge.reload.grant_count).to eq(1)
+ expect(user.user_stat.reload.distinct_badge_count).to eq(1)
+ expect(Notification.where(user:)).to be_empty
+ expect(events.map { |event| event[:event_name] }).to include(:user_badge_granted)
+ end
+
+ it "does not override existing notification suppression when false" do
+ freeze_time
+ bronze_badge = Fabricate(:badge, badge_type: BadgeType.find(BadgeType::Bronze))
+
+ BadgeGranter.grant(bronze_badge, user, created_at: 1.year.ago, suppress_notification: false)
+
+ expect(UserBadge.exists?(badge: bronze_badge, user:)).to eq(true)
+ expect(Notification.where(user:)).to be_empty
+ end
+
it "handles deleted badge" do
freeze_time
user_badge = BadgeGranter.grant(nil, user, created_at: 1.year.ago)