repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/settings/main/user_policy.rb | app/policies/settings/main/user_policy.rb | # frozen_string_literal: true
class Settings::Main::UserPolicy < ApplicationPolicy
def show?
user.role_admin_for?(seller)
end
def update?
user.role_owner_for?(seller)
end
def resend_confirmation_email?
update?
end
def invalidate_active_sessions?
update?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/settings/third_party_analytics/user_policy.rb | app/policies/settings/third_party_analytics/user_policy.rb | # frozen_string_literal: true
class Settings::ThirdPartyAnalytics::UserPolicy < ApplicationPolicy
def show?
user.role_admin_for?(seller)
end
def update?
show?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/settings/authorized_applications/oauth_application_policy.rb | app/policies/settings/authorized_applications/oauth_application_policy.rb | # frozen_string_literal: true
class Settings::AuthorizedApplications::OauthApplicationPolicy < ApplicationPolicy
def index?
user.role_admin_for?(seller)
end
def create?
index?
end
def edit?
index?
end
def update?
index?
end
def destroy?
index?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/admin/impersonators/user_policy.rb | app/policies/admin/impersonators/user_policy.rb | # frozen_string_literal: true
class Admin::Impersonators::UserPolicy < ApplicationPolicy
def create?
return false if record.is_team_member? || record.deleted?
true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/admin/charges/charge_policy.rb | app/policies/admin/charges/charge_policy.rb | # frozen_string_literal: true
class Admin::Charges::ChargePolicy < ApplicationPolicy
def sync_status_with_charge_processor?
record.purchases.where(purchase_state: %w(in_progress failed)).exists?
end
def refund?
record.successful_purchases.non_free.not_fully_refunded.exists?
end
def refund_for_fraud?
refund?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/admin/products/staff_picked/link_policy.rb | app/policies/admin/products/staff_picked/link_policy.rb | # frozen_string_literal: true
class Admin::Products::StaffPicked::LinkPolicy < ApplicationPolicy
def create?
return false if record.staff_picked_product&.not_deleted?
record.recommendable?
end
def destroy?
record.staff_picked_product&.not_deleted? || false
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/checkout/offer_code_policy.rb | app/policies/checkout/offer_code_policy.rb | # frozen_string_literal: true
class Checkout::OfferCodePolicy < ApplicationPolicy
def index?
user.role_accountant_for?(seller) ||
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller) ||
user.role_support_for?(seller)
end
def paged?
index?
end
def statistics?
index?
end
def create?
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller)
end
def update?
create? && record.user == seller
end
def destroy?
update?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/checkout/form_policy.rb | app/policies/checkout/form_policy.rb | # frozen_string_literal: true
class Checkout::FormPolicy < ApplicationPolicy
def show?
user.role_accountant_for?(seller) ||
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller) ||
user.role_support_for?(seller)
end
def update?
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller)
end
def permitted_attributes
{
user: [:display_offer_code_field, :recommendation_type, :tipping_enabled],
custom_fields: [[:id, :type, :name, :required, :global, :collect_per_product, { products: [] }]]
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/checkout/upsell_policy.rb | app/policies/checkout/upsell_policy.rb | # frozen_string_literal: true
class Checkout::UpsellPolicy < ApplicationPolicy
def index?
user.role_accountant_for?(seller) ||
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller) ||
user.role_support_for?(seller)
end
def paged?
index?
end
def cart_item?
index?
end
def statistics?
index?
end
def create?
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller)
end
def update?
create? && record.seller == seller
end
def destroy?
update?
end
def pause?
update?
end
def unpause?
update?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/product_duplicates/link_policy.rb | app/policies/product_duplicates/link_policy.rb | # frozen_string_literal: true
# Products section
#
class ProductDuplicates::LinkPolicy < ApplicationPolicy
def create?
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller)
end
def show?
create?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/products/collabs_policy.rb | app/policies/products/collabs_policy.rb | # frozen_string_literal: true
class Products::CollabsPolicy < ApplicationPolicy
def index?
user.role_accountant_for?(seller) ||
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller) ||
user.role_support_for?(seller)
end
def products_paged?
index?
end
def memberships_paged?
index?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/products/affiliated_policy.rb | app/policies/products/affiliated_policy.rb | # frozen_string_literal: true
class Products::AffiliatedPolicy < ApplicationPolicy
def index?
user.role_accountant_for?(seller) ||
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller) ||
user.role_support_for?(seller)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/products/variants/link_policy.rb | app/policies/products/variants/link_policy.rb | # frozen_string_literal: true
# Products
# Audience > Customers
#
class Products::Variants::LinkPolicy < ApplicationPolicy
def index?
user.role_accountant_for?(seller) ||
user.role_admin_for?(seller) ||
user.role_marketing_for?(seller) ||
user.role_support_for?(seller)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/products/archived/link_policy.rb | app/policies/products/archived/link_policy.rb | # frozen_string_literal: true
class Products::Archived::LinkPolicy < ApplicationPolicy
def index?
Pundit.policy!(@context, Link).index?
end
def create?
Pundit.policy!(@context, Link).new? &&
record.not_archived?
end
def destroy?
Pundit.policy!(@context, Link).new? &&
record.archived?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/policies/gumroad_blog/posts_policy.rb | app/policies/gumroad_blog/posts_policy.rb | # frozen_string_literal: true
class GumroadBlog::PostsPolicy < ApplicationPolicy
allow_anonymous_user_access!
def index?
true
end
def show?
return false unless record.alive?
return false unless record.shown_on_profile?
return false if record.workflow_id.present?
return false unless record.audience_type?
if !record.published?
return false unless seller&.id == record.seller_id
end
true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/validators/isbn_validator.rb | app/validators/isbn_validator.rb | # frozen_string_literal: true
class IsbnValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return if value.nil? && options[:allow_nil]
return if value.blank? && options[:allow_blank]
isbn_digits = value.delete("-")
valid =
if isbn_digits.length == 10
validate_with_isbn10(isbn_digits)
elsif isbn_digits.length == 13
validate_with_isbn13(isbn_digits)
else
false
end
record.errors.add(attribute, options[:message] || "is not a valid ISBN-10 or ISBN-13") unless valid
end
private
def validate_with_isbn10(isbn)
check_digit = isbn[-1] == "X" ? 10 : isbn[-1].to_i
sum = isbn[0...-1].chars.each_with_index.sum { |d, i| (i + 1) * d.to_i }
sum % 11 == check_digit
end
def validate_with_isbn13(isbn)
digits = isbn.chars.map(&:to_i)
sum = digits.each_with_index.sum { |d, i| i.even? ? d : 3 * d } # 100
sum.multiple_of?(10)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/validators/json_validator.rb | app/validators/json_validator.rb | # frozen_string_literal: true
class JsonValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless JSON::Validator.validate(options[:schema], value)
record.errors.add(attribute, options[:message] || "invalid.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/validators/not_reserved_email_domain_validator.rb | app/validators/not_reserved_email_domain_validator.rb | # frozen_string_literal: true
class NotReservedEmailDomainValidator < ActiveModel::EachValidator
RESERVED_EMAIL_DOMAINS = %w[gumroad.com gumroad.org gumroad.dev].freeze
class << self
def domain_reserved?(email)
return false if email.blank?
domain = Mail::Address.new(email).domain
domain&.downcase&.in?(RESERVED_EMAIL_DOMAINS)
rescue Mail::Field::ParseError
false
end
end
def validate_each(record, attribute, value)
if self.class.domain_reserved?(value)
record.errors.add(attribute, options[:message] || "is reserved")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/validators/email_format_validator.rb | app/validators/email_format_validator.rb | # frozen_string_literal: true
class EmailFormatValidator < ActiveModel::EachValidator
# To reduce invalid email address errors, we enforcing the same email regex as the front end
EMAIL_REGEX = /\A(?=.{3,255}$)( # between 3 and 255 characters
([^@\s()\[\],.<>;:\\"]+(\.[^@\s()\[\],.<>;:\\"]+)*) # cannot start with or have consecutive .
| # or
(".+")) # local part can be in quotes
@
((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]) # IP address
| # or
(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}) # domain can only alphabets and . -
)\z/x
class << self
def valid?(email)
return false if email.blank?
email.to_s.match?(EMAIL_REGEX)
end
end
def validate_each(record, attribute, value)
return if value.nil? && options[:allow_nil]
return if value.blank? && options[:allow_blank]
unless self.class.valid?(value)
record.errors.add(attribute, options[:message] || :invalid)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/product_duplicates_controller.rb | app/controllers/product_duplicates_controller.rb | # frozen_string_literal: true
class ProductDuplicatesController < Sellers::BaseController
before_action :fetch_product_and_enforce_ownership
def create
authorize [:product_duplicates, @product]
if @product.is_duplicating
render(json: { success: false, error_message: "Duplication in progress..." }) && (return)
end
DuplicateProductWorker.perform_async(@product.id)
@product.update!(is_duplicating: true)
render json: { success: true }
end
def show
authorize [:product_duplicates, @product]
if @product.is_duplicating
render(json: { success: false, status: ProductDuplicatorService::DUPLICATING, error_message: "Duplication in progress..." }) && return
end
duplicated_product = ProductDuplicatorService.new(@product.id).recently_duplicated_product
unless duplicated_product
# Product is not duplicating and we can't find it in redis
render(json: { success: false, status: ProductDuplicatorService::DUPLICATION_FAILED }) && return
end
if duplicated_product.is_recurring_billing?
page_props = DashboardProductsPagePresenter.new(
pundit_user:,
memberships: [duplicated_product],
memberships_pagination: nil,
products: [],
products_pagination: nil
).page_props
duplicated_product = page_props[:memberships].first
is_membership = true
else
page_props = DashboardProductsPagePresenter.new(
pundit_user:,
memberships: [],
memberships_pagination: nil,
products: [duplicated_product],
products_pagination: nil
).page_props
duplicated_product = page_props[:products].first
is_membership = false
end
render json: {
success: true,
status: ProductDuplicatorService::DUPLICATED,
product: @product,
duplicated_product:,
is_membership:
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/utm_links_controller.rb | app/controllers/utm_links_controller.rb | # frozen_string_literal: true
class UtmLinksController < Sellers::BaseController
before_action :set_body_id_as_app
def index
authorize UtmLink
end
private
def set_title
@title = "UTM Links"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/licenses_controller.rb | app/controllers/licenses_controller.rb | # frozen_string_literal: true
class LicensesController < Sellers::BaseController
def update
license = License.find_by_external_id!(params[:id])
authorize [:audience, license.purchase], :manage_license?
if ActiveModel::Type::Boolean.new.cast(params[:enabled])
license.enable!
else
license.disable!
end
head :no_content
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/media_locations_controller.rb | app/controllers/media_locations_controller.rb | # frozen_string_literal: true
class MediaLocationsController < ApplicationController
include RecordMediaLocation
skip_before_action :check_suspended
def create
render json: { success: record_media_location(params) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/utm_link_tracking_controller.rb | app/controllers/utm_link_tracking_controller.rb | # frozen_string_literal: true
class UtmLinkTrackingController < ApplicationController
def show
utm_link = UtmLink.active.find_by!(permalink: params[:permalink])
e404 unless Feature.active?(:utm_links, utm_link.seller)
redirect_to utm_link.utm_url, allow_other_host: true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/thumbnails_controller.rb | app/controllers/thumbnails_controller.rb | # frozen_string_literal: true
class ThumbnailsController < Sellers::BaseController
before_action :find_product
def create
authorize Thumbnail
thumbnail = @product.thumbnail || @product.build_thumbnail
if permitted_params[:signed_blob_id].present?
thumbnail.file.attach(permitted_params[:signed_blob_id])
thumbnail.file.analyze
thumbnail.unsplash_url = nil
end
# Mark alive if previously deleted
thumbnail.deleted_at = nil
if thumbnail.save
render(json: { success: true, thumbnail: @product.thumbnail })
else
render(json: { success: false, error: thumbnail.errors.any? ? thumbnail.errors.full_messages.to_sentence : "Could not process your preview, please try again." })
end
rescue *INTERNET_EXCEPTIONS
render(json: { success: false, error: "Could not process your thumbnail, please try again." })
end
def destroy
authorize Thumbnail
thumbnail = @product.thumbnail&.guid == params[:id] ? @product.thumbnail : nil
if thumbnail&.mark_deleted!
render(json: { success: true, thumbnail: @product.thumbnail })
else
render(json: { success: false })
end
end
private
def find_product
@product = Link.fetch(params[:link_id], user: current_seller) || e404
end
def permitted_params
params.require(:thumbnail).permit(:signed_blob_id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/test_controller.rb | app/controllers/test_controller.rb | # frozen_string_literal: true
# Controller containing actions for endpoints that are used by Pingdom and alike to check that
# certain functionality is working and alive.
class TestController < ApplicationController
# Public: Action that tests that outgoing traffic is possible.
# Tests outgoing traffic by attempting to read an object from S3.
def outgoing_traffic
temp_file = Tempfile.new
Aws::S3::Resource.new.bucket("gumroad").object("outgoing-traffic-healthcheck.txt").get(response_target: temp_file)
temp_file.rewind
render plain: temp_file.read
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/bundles_controller.rb | app/controllers/bundles_controller.rb | # frozen_string_literal: true
class BundlesController < Sellers::BaseController
include SearchProducts, Product::BundlesMarketing
PER_PAGE = 10
def show
bundle = Link.can_be_bundle.find_by_external_id!(params[:id])
authorize bundle
@title = bundle.name
@props = BundlePresenter.new(bundle:).bundle_props
end
def create_from_email
authorize Link, :create?
bundle = current_seller.products.build(
name: BUNDLE_NAMES[create_from_email_permitted_params[:type]],
is_bundle: true,
native_type: Link::NATIVE_TYPE_BUNDLE,
price_cents: create_from_email_permitted_params[:price],
price_currency_type: current_seller.currency_type,
from_bundle_marketing: true,
draft: true,
)
products = current_seller.products.by_external_ids(create_from_email_permitted_params[:products])
products.each do |product|
bundle.bundle_products.build(bundle:, product:, variant: product.alive_variants.first, quantity: 1)
end
bundle.save!
redirect_to bundle_path(bundle.external_id)
end
def products
authorize Link, :index?
options = {
query: products_permitted_params[:query],
from: products_permitted_params[:from],
sort: ProductSortKey::FEATURED,
user_id: current_seller.id,
is_subscription: false,
is_bundle: false,
is_alive: true,
is_call: false,
exclude_ids: [ObfuscateIds.decrypt(products_permitted_params[:product_id])],
}
options[:size] = PER_PAGE unless products_permitted_params[:all] == "true"
products = search_products(options)[:products].map { BundlePresenter.bundle_product(product: _1) }
render json: { products: }
end
def update_purchases_content
@bundle = Link.is_bundle.find_by_external_id!(params[:id])
authorize @bundle, :update?
return render json: { error: "This bundle has no purchases with outdated content." }, status: :forbidden unless @bundle.has_outdated_purchases?
UpdateBundlePurchasesContentJob.perform_async(@bundle.id)
head :no_content
end
def update
@bundle = Link.can_be_bundle.find_by_external_id!(params[:id])
authorize @bundle
begin
@bundle.is_bundle = true
@bundle.native_type = Link::NATIVE_TYPE_BUNDLE
@bundle.assign_attributes(bundle_permitted_params.except(
:products, :custom_button_text_option, :custom_summary, :custom_attributes, :tags, :covers, :refund_policy, :product_refund_policy_enabled,
:seller_refund_policy_enabled, :section_ids, :installment_plan)
)
@bundle.save_custom_button_text_option(bundle_permitted_params[:custom_button_text_option]) unless bundle_permitted_params[:custom_button_text_option].nil?
@bundle.save_custom_summary(bundle_permitted_params[:custom_summary]) unless bundle_permitted_params[:custom_summary].nil?
@bundle.save_custom_attributes(bundle_permitted_params[:custom_attributes]) unless bundle_permitted_params[:custom_attributes].nil?
@bundle.save_tags!(bundle_permitted_params[:tags]) unless bundle_permitted_params[:tags].nil?
@bundle.reorder_previews(bundle_permitted_params[:covers].map.with_index.to_h) if bundle_permitted_params[:covers].present?
if !current_seller.account_level_refund_policy_enabled?
@bundle.product_refund_policy_enabled = bundle_permitted_params[:product_refund_policy_enabled]
if bundle_permitted_params[:refund_policy].present? && bundle_permitted_params[:product_refund_policy_enabled]
@bundle.find_or_initialize_product_refund_policy.update!(bundle_permitted_params[:refund_policy])
end
end
@bundle.show_in_sections!(bundle_permitted_params[:section_ids]) if bundle_permitted_params[:section_ids]
update_installment_plan
update_bundle_products(bundle_permitted_params[:products]) unless bundle_permitted_params[:products].nil?
@bundle.save!
rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid, Link::LinkInvalid => e
error_message = @bundle.errors.full_messages.first || e.message
return render json: { error_message: }, status: :unprocessable_entity
end
head :no_content
end
private
def bundle_permitted_params
params.permit(policy(@bundle).bundle_permitted_attributes)
end
def create_from_email_permitted_params
params.permit(:type, :price, products: [])
end
def products_permitted_params
params.permit(:query, :from, :all, :product_id)
end
def update_bundle_products(new_bundle_products)
bundle_products = @bundle.bundle_products.includes(:product)
bundle_products.each do |bundle_product|
new_bundle_product = new_bundle_products.find { _1[:product_id] == bundle_product.product.external_id }
if new_bundle_product.present?
bundle_product.update(variant: BaseVariant.find_by_external_id(new_bundle_product[:variant_id]), quantity: new_bundle_product[:quantity], deleted_at: nil, position: new_bundle_product[:position])
new_bundle_products.delete(new_bundle_product)
update_has_outdated_purchases
else
bundle_product.mark_deleted!
end
end
update_has_outdated_purchases if new_bundle_products.present?
new_bundle_products.each do |new_bundle_product|
product = Link.find_by_external_id!(new_bundle_product[:product_id])
variant = BaseVariant.find_by_external_id(new_bundle_product[:variant_id])
@bundle.bundle_products.create!(product:, variant:, quantity: new_bundle_product[:quantity], position: new_bundle_product[:position])
end
end
def update_has_outdated_purchases
return if @bundle.has_outdated_purchases?
@bundle.has_outdated_purchases = true if @bundle.successful_sales_count > 0
end
def update_installment_plan
return unless @bundle.eligible_for_installment_plans?
if @bundle.installment_plan && bundle_permitted_params[:installment_plan].present?
@bundle.installment_plan.assign_attributes(bundle_permitted_params[:installment_plan])
return unless @bundle.installment_plan.changed?
end
@bundle.installment_plan&.destroy_if_no_payment_options!
@bundle.reset_installment_plan
if bundle_permitted_params[:installment_plan].present?
@bundle.create_installment_plan!(bundle_permitted_params[:installment_plan])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/product_files_utility_controller.rb | app/controllers/product_files_utility_controller.rb | # frozen_string_literal: true
class ProductFilesUtilityController < ApplicationController
include SignedUrlHelper
before_action :authenticate_user!
before_action :set_product, only: %i[download_product_files download_folder_archive]
def external_link_title
response = SsrfFilter.get(params.require(:url))
title = Nokogiri::HTML(response.body).title
title = "Untitled" if title.blank?
render json: {
success: true,
title:
}
rescue
render json: { success: false }
end
def download_product_files
product_files = current_seller.alive_product_files_preferred_for_product(@product).by_external_ids(params[:product_file_ids])
e404 if product_files.blank?
url_redirect = @product.url_redirects.build
if request.format.json?
render(json: { files: product_files.map { { url: url_redirect.signed_location_for_file(_1), filename: _1.s3_filename } } })
else
# Non-JSON requests to this controller route pass an array with a single product file ID for `product_file_ids`
redirect_to(url_redirect.signed_location_for_file(product_files.first), allow_other_host: true)
end
end
def download_folder_archive
variant = @product.alive_variants.find_by_external_id(params[:variant_id]) if params[:variant_id].present?
archive = (variant || @product).product_files_archives.latest_ready_folder_archive(params[:folder_id])
if request.format.json?
# The frontend appends Google Analytics query parameters to the signed S3 URL
# in staging and production (which breaks the URL), so we instead return the
# controller route that can be used to be redirected to the signed URL
url = download_folder_archive_url(params[:folder_id], { variant_id: params[:variant_id], product_id: params[:product_id] }) if archive.present?
render json: { url: }
else
e404 if archive.nil?
redirect_to(signed_download_url_for_s3_key_and_filename(archive.s3_key, archive.s3_filename), allow_other_host: true)
end
end
private
def set_product
@product = current_seller.products.find_by_external_id(params[:product_id])
e404 if @product.nil?
authorize @product, :edit?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/posts_controller.rb | app/controllers/posts_controller.rb | # frozen_string_literal: true
class PostsController < ApplicationController
include CustomDomainConfig
before_action :authenticate_user!, only: %i[send_for_purchase]
after_action :verify_authorized, only: %i[send_for_purchase]
before_action :fetch_post, only: %i[send_for_purchase]
before_action :ensure_seller_is_eligible_to_send_emails, only: %i[send_for_purchase]
before_action :set_user_and_custom_domain_config, only: %i[show]
before_action :check_if_needs_redirect, only: %i[show]
def show
# Skip fetching post again if it's already fetched in check_if_needs_redirect
@post || fetch_post(false)
@title = "#{@post.name} - #{@post.user.name_or_username}"
@hide_layouts = true
@show_user_favicon = true
@body_class = "post-page"
@body_id = "post_page"
@on_posts_page = true
# Set @user instance variable to apply third-party analytics config in layouts/_head partial.
@user = @post.seller
seller_context = SellerContext.new(
user: logged_in_user,
seller: (logged_in_user && policy(@post).preview?) ? current_seller : logged_in_user
)
@post_presenter = PostPresenter.new(
pundit_user: seller_context,
post: @post,
purchase_id_param: params[:purchase_id]
)
purchase = @post_presenter.purchase
if purchase
@subscription = purchase.subscription
end
e404 if @post_presenter.e404?
end
def redirect_from_purchase_id
authorize Installment
# redirects legacy installment paths like /library/purchase/:purchase_id
# to the new path /:username/p/:slug
fetch_post(false)
redirect_to build_view_post_route(post: @post, purchase_id: params[:purchase_id])
end
def send_for_purchase
authorize @post
purchase = current_seller.sales.find_by_external_id!(params[:purchase_id])
# Limit the number of emails sent per post to avoid abuse.
Rails.cache.fetch("post_email:#{@post.id}:#{purchase.id}", expires_in: 8.hours) do
CreatorContactingCustomersEmailInfo.where(purchase:, installment: @post).destroy_all
PostEmailApi.process(
post: @post,
recipients: [
{
email: purchase.email,
purchase:,
url_redirect: purchase.url_redirect,
subscription: purchase.subscription,
}.compact_blank
])
true
end
head :no_content
end
def increment_post_views
fetch_post(false)
skip = is_bot?
skip |= logged_in_user.present? && (@post.seller_id == current_seller.id || logged_in_user.is_team_member?)
skip |= impersonating_user&.id
create_post_event(@post) unless skip
render json: { success: true }
end
private
def fetch_post(viewed_by_seller = true)
if params[:slug]
@post = Installment.find_by_slug(params[:slug])
elsif params[:id]
@post = Installment.find_by_external_id(params[:id])
else
e404
end
e404 if @post.blank?
if viewed_by_seller
e404 if @post.seller != current_seller
end
if @post.seller_id?
e404 if @post.seller.suspended?
elsif @post.link_id?
e404 if @post.link.seller&.suspended?
end
end
def check_if_needs_redirect
fetch_post(false)
if !@is_user_custom_domain && @user.subdomain_with_protocol.present?
redirect_to custom_domain_view_post_url(slug: @post.slug, host: @user.subdomain_with_protocol,
params: request.query_parameters),
status: :moved_permanently, allow_other_host: true
end
end
def ensure_seller_is_eligible_to_send_emails
seller = @post.seller || @post.link.seller
unless seller&.eligible_to_send_emails?
render json: { message: "You are not eligible to resend this email." }, status: :unauthorized
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/subscriptions_controller.rb | app/controllers/subscriptions_controller.rb | # frozen_string_literal: true
class SubscriptionsController < ApplicationController
PUBLIC_ACTIONS = %i[manage unsubscribe_by_user magic_link send_magic_link].freeze
before_action :authenticate_user!, except: PUBLIC_ACTIONS
after_action :verify_authorized, except: PUBLIC_ACTIONS
before_action :fetch_subscription, only: %i[unsubscribe_by_seller unsubscribe_by_user magic_link send_magic_link]
before_action :hide_layouts, only: [:manage, :magic_link, :send_magic_link]
before_action :set_noindex_header, only: [:manage]
before_action :check_can_manage, only: [:manage, :unsubscribe_by_user]
SUBSCRIPTION_COOKIE_EXPIRY = 1.week
def unsubscribe_by_seller
authorize @subscription
@subscription.cancel!(by_seller: true)
head :no_content
end
def unsubscribe_by_user
@subscription.cancel!(by_seller: false)
render json: { success: true }
rescue ActiveRecord::RecordInvalid => e
render json: { success: false, error: e.message }
end
def manage
@product = @subscription.link
@card = @subscription.credit_card_to_charge
@card_data_handling_mode = CardDataHandlingMode.get_card_data_handling_mode(@product.user)
@title = @subscription.is_installment_plan ? "Manage installment plan" : "Manage membership"
@body_id = "product_page"
@is_on_product_page = true
set_subscription_confirmed_redirect_cookie
end
def magic_link
@react_component_props = SubscriptionsPresenter.new(subscription: @subscription).magic_link_props
end
def send_magic_link
@subscription.refresh_token
emails = @subscription.emails
email_source = params[:email_source].to_sym
email = emails[email_source]
e404 if email.nil?
CustomerMailer.subscription_magic_link(@subscription.id, email).deliver_later(queue: "critical")
head :no_content
end
private
def check_can_manage
(@subscription = Subscription.find_by_external_id(params[:id])) || e404
e404 if @subscription.ended?
e404 if @subscription.is_installment_plan? && @subscription.charges_completed?
cookie = cookies.encrypted[@subscription.cookie_key]
return if cookie.present? && ActiveSupport::SecurityUtils.secure_compare(cookie, @subscription.external_id)
return if user_signed_in? && logged_in_user.is_team_member?
return if user_signed_in? && logged_in_user == @subscription.user
return if user_signed_in? && gifter_user.present? && logged_in_user == gifter_user
token = params[:token]
if token.present?
return if @subscription.token.present? && ActiveSupport::SecurityUtils.secure_compare(token, @subscription.token) && @subscription.token_expires_at > Time.current
return redirect_to magic_link_subscription_path(params[:id], { invalid: true })
end
respond_to do |format|
format.html { redirect_to magic_link_subscription_path(params[:id]) }
format.json { render json: { success: false, redirect_to: magic_link_subscription_path(params[:id]) } }
end
end
def gifter_user
return unless @subscription.gift?
@subscription.true_original_purchase.gift_given&.gifter_purchase&.purchaser
end
def set_subscription_confirmed_redirect_cookie
cookies.encrypted[@subscription.cookie_key] = {
value: @subscription.external_id,
httponly: true,
expires: Rails.env.test? ? nil : SUBSCRIPTION_COOKIE_EXPIRY.from_now
}
end
def fetch_subscription
@subscription = Subscription.find_by_external_id(params[:id] || params[:subscription_id])
render json: { success: false } if @subscription.nil?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/paypal_controller.rb | app/controllers/paypal_controller.rb | # frozen_string_literal: true
class PaypalController < ApplicationController
before_action :authenticate_user!, only: [:connect, :disconnect]
before_action :validate_paypal_connect_allowed, only: %i[connect]
before_action :validate_paypal_disconnect_allowed, only: %i[disconnect]
after_action :verify_authorized, only: [:connect, :disconnect]
def billing_agreement_token
begin
Rails.logger.info("Generate billing agreement token params - #{params}")
billing_agreement_token_id = PaypalChargeProcessor.generate_billing_agreement_token(shipping: params[:shipping] == "true")
rescue ChargeProcessorError => e
Rails.logger.error("PAYPAL BUYER UX AFFECTING ERROR-in #{__method__}-#{e.message}")
end
render json: { billing_agreement_token_id: }
end
def billing_agreement
begin
Rails.logger.info("Create billing agreement params - #{params}")
response = PaypalChargeProcessor.create_billing_agreement(billing_agreement_token_id: params[:billing_agreement_token_id])
rescue ChargeProcessorError => e
Rails.logger.error("PAYPAL BUYER UX AFFECTING ERROR-in #{__method__}-#{e.message}")
end
render json: response
end
def order
begin
product = Link.find_by_external_id(params[:product][:external_id])
affiliate = fetch_affiliate(product)
if affiliate&.eligible_for_purchase_credit?(product:, was_recommended: !!params[:product][:was_recommended])
params[:product][:affiliate_id] = affiliate.id
end
order_id = PaypalChargeProcessor.create_order_from_product_info(params[:product])
rescue ChargeProcessorError => e
Rails.logger.error("PAYPAL BUYER UX AFFECTING ERROR-in #{__method__}-#{e.message}")
end
render json: { order_id: }
end
def fetch_order
begin
api_response = PaypalChargeProcessor.fetch_order(order_id: params[:order_id])
rescue ChargeProcessorError => e
Rails.logger.error("PAYPAL BUYER UX AFFECTING ERROR-in #{__method__}-#{e.message}")
end
render json: api_response || {}
end
def update_order
begin
success = PaypalChargeProcessor.update_order_from_product_info(params[:order_id], params[:product])
rescue ChargeProcessorError => e
Rails.logger.error("PAYPAL BUYER UX AFFECTING ERROR-in #{__method__}-#{e.message}")
end
render json: { success: !!success }
end
def connect
authorize [:settings, :payments, current_seller], :paypal_connect?
paypal_merchant_account_manager = PaypalMerchantAccountManager.new
response = paypal_merchant_account_manager.create_partner_referral(current_seller, paypal_connect_settings_payments_url)
if response[:success]
redirect_to response[:redirect_url], allow_other_host: true
else
redirect_to settings_payments_path, notice: response[:error_message]
end
end
def disconnect
authorize [:settings, :payments, current_seller], :paypal_connect?
render json: { success: PaypalMerchantAccountManager.new.disconnect(user: current_seller) }
end
private
def validate_paypal_connect_allowed
return if current_seller.paypal_connect_enabled? && current_seller.paypal_connect_allowed?
alert = if !current_seller.paypal_connect_enabled?
"Your PayPal account could not be connected because this PayPal integration is not supported in your country."
elsif !current_seller.paypal_connect_allowed?
"Your PayPal account could not be connected because you do not meet the eligibility requirements."
end
redirect_to settings_payments_path, alert:
end
def validate_paypal_disconnect_allowed
return if current_seller.paypal_disconnect_allowed?
redirect_to settings_payments_path, notice: "You cannot disconnect your PayPal account because it is being used for active subscription or preorder payments."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/github_stars_controller.rb | app/controllers/github_stars_controller.rb | # frozen_string_literal: true
class GithubStarsController < ApplicationController
def show
expires_in 1.hour, public: true
render json: { stars: fetch_cached_stars }
end
private
def fetch_cached_stars
Rails.cache.fetch(
"github_stars_antiwork/gumroad",
expires_in: 1.hour,
race_condition_ttl: 10.seconds
) do
fetch_stars
end
end
def fetch_stars
response = HTTParty.get(
"https://api.github.com/repos/antiwork/gumroad",
headers: { "X-GitHub-Api-Version" => "2022-11-28" }
)
if response.success?
response.parsed_response["stargazers_count"]
else
Rails.logger.error("GitHub API request failed: status=#{response.code}, message=#{response.message}, body=#{response.body}")
nil
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/affiliate_requests_controller.rb | app/controllers/affiliate_requests_controller.rb | # frozen_string_literal: true
class AffiliateRequestsController < ApplicationController
include CustomDomainConfig
PUBLIC_ACTIONS = %i[new create]
before_action :authenticate_user!, except: PUBLIC_ACTIONS
before_action :set_user_and_custom_domain_config, only: %i[new create]
before_action :check_if_needs_redirect, only: :new
before_action :ensure_creator_has_enabled_affiliate_requests, only: %i[new create]
before_action :set_affiliate_request, only: %i[approve ignore]
def new
@title = "Become an affiliate for #{@user.display_name}"
@profile_presenter = ProfilePresenter.new(
pundit_user:,
seller: @user,
)
@hide_layouts = true
end
def create
@affiliate_request = @user.affiliate_requests.new(permitted_create_params)
@affiliate_request.locale = params[:locale] || "en"
if @affiliate_request.save
@affiliate_request.approve! if Feature.active?(:auto_approve_affiliates, @user)
update_logged_in_user_name_if_needed(permitted_create_params[:name])
render json: { success: true, requester_has_existing_account: User.exists?(email: @affiliate_request.email) }
else
render json: { success: false, error: @affiliate_request.errors.full_messages.first }
end
end
def update
affiliate_request = current_seller.affiliate_requests.find_by_external_id!(params[:id])
authorize affiliate_request
action_name = permitted_update_params[:action]
unless affiliate_request.can_perform_action?(action_name)
render json: { success: false, error: "#{affiliate_request.name}'s affiliate request has been already processed." }
return
end
begin
if action_name == AffiliateRequest::ACTION_APPROVE
affiliate_request.approve!
elsif action_name == AffiliateRequest::ACTION_IGNORE
affiliate_request.ignore!
else
render json: { success: false, error: "#{action_name} is not a valid affiliate request action" }
return
end
render json: { success: true, affiliate_request:, requester_has_existing_account: User.exists?(email: affiliate_request.email) }
rescue ActiveRecord::RecordInvalid => e
render json: { success: false, error: e.message }
end
end
def approve
begin
perform_action_if_permitted(AffiliateRequest::ACTION_APPROVE) do
@affiliate_request.approve!
@message = "Approved #{@affiliate_request.name}'s affiliate request."
end
rescue ActiveRecord::RecordInvalid => e
@message = "An error encountered while approving #{@affiliate_request.name}'s affiliate request - #{e.message}."
end
render :email_link_status
end
def ignore
begin
perform_action_if_permitted(AffiliateRequest::ACTION_IGNORE) do
@affiliate_request.ignore!
@message = "Ignored #{@affiliate_request.name}'s affiliate request."
end
rescue ActiveRecord::RecordInvalid => e
@message = "An error encountered while ignoring #{@affiliate_request.name}'s affiliate request - #{e.message}."
end
render :email_link_status
end
def approve_all
authorize AffiliateRequest
pending_requests = current_seller.affiliate_requests.unattended
pending_requests.find_each(&:approve!)
render json: { success: true }
rescue ActiveRecord::RecordInvalid, StateMachines::InvalidTransition
render json: { success: false }
end
private
def ensure_creator_has_enabled_affiliate_requests
respond_with_404 unless @user.self_service_affiliate_products.enabled.exists?
end
def check_if_needs_redirect
if !@is_user_custom_domain && @user.subdomain_with_protocol.present?
redirect_to custom_domain_new_affiliate_request_url(host: @user.subdomain_with_protocol),
status: :moved_permanently, allow_other_host: true
end
end
def set_affiliate_request
@affiliate_request = current_seller.affiliate_requests.find_by_external_id!(params[:id])
end
def permitted_create_params
params.require(:affiliate_request).permit(:name, :email, :promotion_text)
end
def permitted_update_params
params.require(:affiliate_request).permit(:action)
end
def perform_action_if_permitted(action)
if @affiliate_request.can_perform_action?(action)
yield
else
@message = "#{@affiliate_request.name}'s affiliate request has been already processed."
end
end
def respond_with_404
respond_to do |format|
format.html { e404 }
format.json { return e404_json }
end
end
def update_logged_in_user_name_if_needed(name)
return if logged_in_user.blank?
return if logged_in_user.name.present?
# Do a best effort to update name if possible;
# Do not raise if record cannot be saved as the user cannot fix the issue within this context
logged_in_user.update(name:)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/asset_previews_controller.rb | app/controllers/asset_previews_controller.rb | # frozen_string_literal: true
class AssetPreviewsController < ApplicationController
before_action :find_product
after_action :verify_authorized
def create
authorize AssetPreview
asset_preview = @product.asset_previews.build
if permitted_params[:signed_blob_id].present?
asset_preview.file.attach(permitted_params[:signed_blob_id])
else
asset_preview.url = permitted_params[:url]
end
asset_preview.analyze_file
if asset_preview.save
render(json: { success: true, asset_previews: @product.display_asset_previews, active_preview_id: asset_preview.guid })
else
asset_preview.file&.blob&.purge
render(json: { success: false, error: asset_preview.errors.any? ? asset_preview.errors.full_messages.to_sentence : "Could not process your preview, please try again." })
end
rescue *INTERNET_EXCEPTIONS
render(json: { success: false, error: "Could not process your preview, please try again." })
end
def destroy
asset_preview = @product.asset_previews.where(guid: params[:id]).first
authorize asset_preview
if asset_preview&.mark_deleted!
render(json: { success: true, asset_previews: @product.display_asset_previews, active_preview_id: @product.main_preview && @product.main_preview.guid })
else
render(json: { success: false })
end
end
private
def find_product
e404 unless user_signed_in?
@product = Link.fetch(params[:link_id], user: current_seller) || e404
end
def permitted_params
params.require(:asset_preview).permit(:signed_blob_id, :url)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/emails_controller.rb | app/controllers/emails_controller.rb | # frozen_string_literal: true
class EmailsController < Sellers::BaseController
layout "inertia"
before_action :set_installment, only: %i[edit update destroy]
def index
authorize Installment
if current_seller.installments.alive.not_workflow_installment.scheduled.exists?
redirect_to scheduled_emails_path, status: :moved_permanently
else
redirect_to published_emails_path, status: :moved_permanently
end
end
def published
authorize Installment, :index?
create_user_event("emails_view")
presenter = PaginatedInstallmentsPresenter.new(
seller: current_seller,
type: Installment::PUBLISHED,
page: params[:page],
query: params[:query],
)
props = presenter.props
render inertia: "Emails/Published", props: {
installments: InertiaRails.merge { props[:installments] },
pagination: props[:pagination],
has_posts: props[:has_posts],
}
end
def scheduled
authorize Installment, :index?
create_user_event("emails_view")
presenter = PaginatedInstallmentsPresenter.new(
seller: current_seller,
type: Installment::SCHEDULED,
page: params[:page],
query: params[:query],
)
props = presenter.props
render inertia: "Emails/Scheduled", props: {
installments: InertiaRails.merge { props[:installments] },
pagination: props[:pagination],
has_posts: props[:has_posts],
}
end
def drafts
authorize Installment, :index?
create_user_event("emails_view")
presenter = PaginatedInstallmentsPresenter.new(
seller: current_seller,
type: Installment::DRAFT,
page: params[:page],
query: params[:query],
)
props = presenter.props
render inertia: "Emails/Drafts", props: {
installments: InertiaRails.merge { props[:installments] },
pagination: props[:pagination],
has_posts: props[:has_posts],
}
end
def new
authorize Installment
from_tab = case request.referer
when published_emails_url then "published"
when scheduled_emails_url then "scheduled"
when drafts_emails_url then "drafts"
else "drafts"
end
presenter = InstallmentPresenter.new(seller: current_seller, from_tab:)
render inertia: "Emails/New", props: presenter.new_page_props(copy_from: params[:copy_from])
end
def edit
authorize @installment
presenter = InstallmentPresenter.new(seller: current_seller, installment: @installment)
render inertia: "Emails/Edit", props: presenter.edit_page_props
end
def create
authorize Installment
save_installment
end
def update
authorize @installment
save_installment
end
def destroy
authorize @installment
@installment.update(deleted_at: Time.current)
redirect_back_or_to emails_path, notice: "Email deleted!", status: :see_other
end
private
def set_title
@title = "Emails"
end
def set_installment
@installment = current_seller.installments.alive.find_by_external_id(params[:id])
e404 unless @installment
end
def save_installment
service = SaveInstallmentService.new(
seller: current_seller,
params:,
installment: @installment,
preview_email_recipient: impersonating_user || logged_in_user
)
is_new_record = @installment.nil?
if service.process
if params[:save_action_name] == "save_and_preview_post"
redirect_to edit_email_path(service.installment.external_id, preview_post: true), notice: "Preview link opened.", status: :see_other
elsif params[:save_action_name] == "save_and_preview_email"
redirect_to edit_email_path(service.installment.external_id), notice: "A preview has been sent to your email.", status: :see_other
elsif params[:save_action_name] == "save_and_publish"
redirect_to published_emails_path, notice: service.installment.send_emails? ? "Email successfully sent!" : "Email successfully published!", status: :see_other
elsif params[:save_action_name] == "save_and_schedule"
redirect_to scheduled_emails_path, notice: "Email successfully scheduled!", status: :see_other
elsif is_new_record
redirect_to edit_email_path(service.installment.external_id), notice: "Email created!", status: :see_other
else
redirect_to edit_email_path(service.installment.external_id), notice: "Changes saved!", status: :see_other
end
elsif @installment
redirect_to edit_email_path(@installment.external_id), alert: service.error
else
redirect_to new_email_path, alert: service.error
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/two_factor_authentication_controller.rb | app/controllers/two_factor_authentication_controller.rb | # frozen_string_literal: true
class TwoFactorAuthenticationController < ApplicationController
before_action :redirect_to_signed_in_path, if: -> { user_signed_in? && skip_two_factor_authentication?(logged_in_user) }
before_action :fetch_user
before_action :check_presence_of_user, except: :verify
before_action :redirect_to_login_path, only: :verify, if: -> { @user.blank? }
before_action :validate_user_id_from_params, except: :new
# Get /two-factor
def new
@hide_layouts = true
end
# POST /two-factor.json
def create
verify_auth_token_and_redirect(params[:token])
end
# GET /two-factor/verify.html
def verify
verify_auth_token_and_redirect(params[:token])
end
def resend_authentication_token
@user.send_authentication_token!
head :no_content
end
private
def redirect_to_login_path
redirect_to login_url(next: request.fullpath)
end
def verify_auth_token_and_redirect(token)
if @user.token_authenticated?(token)
sign_in_with_two_factor_authentication(@user)
flash[:notice] = "Successfully logged in!"
respond_to do |format|
format.html { redirect_to login_path_for(@user) }
format.json { render json: { redirect_location: login_path_for(@user) } }
end
else
respond_to do |format|
format.html do
flash[:alert] = "Invalid token, please try again."
redirect_to two_factor_authentication_path
end
format.json { render json: { error_message: "Invalid token, please try again." }, status: :unprocessable_entity }
end
end
end
def validate_user_id_from_params
# We require params[:user_id] to be present in the request. This param is used in Rack::Attack to
# throttle token verification and resend token attempts.
unless User.find_by_encrypted_external_id(params[:user_id]) == @user
respond_to do |format|
format.html { e404 }
format.json { e404_json }
end
end
end
def redirect_to_signed_in_path
respond_to do |format|
format.html { redirect_to login_path_for(logged_in_user) }
format.json { render json: { success: true, redirect_location: login_path_for(logged_in_user) } }
end
end
def fetch_user
@user = user_for_two_factor_authentication
end
def check_presence_of_user
if @user.blank?
respond_to do |format|
format.html { e404 }
format.json { e404_json }
end
end
end
def sign_in_with_two_factor_authentication(user)
sign_in(user) unless user_signed_in?
user.confirm unless user.confirmed?
remember_two_factor_auth
reset_two_factor_auth_login_session
merge_guest_cart_with_user_cart
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/purchase_custom_fields_controller.rb | app/controllers/purchase_custom_fields_controller.rb | # frozen_string_literal: true
class PurchaseCustomFieldsController < ApplicationController
def create
purchase = Purchase.find_by_external_id!(permitted_params.require(:purchase_id))
custom_field = purchase.link.custom_fields.is_post_purchase.where(type: CustomField::FIELD_TYPE_TO_NODE_TYPE_MAPPING.keys).find_by_external_id!(permitted_params.require(:custom_field_id))
purchase_custom_field = purchase.purchase_custom_fields.find_by(custom_field_id: custom_field.id)
if purchase_custom_field.blank?
purchase_custom_field = PurchaseCustomField.build_from_custom_field(custom_field:, value: permitted_params[:value])
purchase.purchase_custom_fields << purchase_custom_field
end
purchase_custom_field.value = permitted_params[:value]
if custom_field.type == CustomField::TYPE_FILE
purchase_custom_field.files.attach(permitted_params[:file_signed_ids])
end
purchase_custom_field.save!
head :no_content
end
private
def permitted_params
params.permit(:purchase_id, :custom_field_id, :value, file_signed_ids: [])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/test_pings_controller.rb | app/controllers/test_pings_controller.rb | # frozen_string_literal: true
class TestPingsController < Sellers::BaseController
def create
authorize([:settings, :advanced, current_seller], :test_ping?)
unless /\A#{URI::DEFAULT_PARSER.make_regexp}\z/.match?(params[:url])
render json: { success: false, error_message: "That URL seems to be invalid." }
return
end
message = if current_seller.send_test_ping params[:url]
"Your last sale's data has been sent to your Ping URL."
else
"There are no sales on your account to test with. Please make a test purchase and try again."
end
render json: { success: true, message: }
rescue *INTERNET_EXCEPTIONS
render json: { success: false, error_message: "That URL seems to be invalid." }
rescue Exception
render json: { success: false, error_message: "Sorry, something went wrong. Please try again." }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/home_controller.rb | app/controllers/home_controller.rb | # frozen_string_literal: true
class HomeController < ApplicationController
layout "home"
before_action :set_meta_data
before_action :set_layout_and_title
private
def set_layout_and_title
@hide_layouts = true
@title = @meta_data[action_name]&.fetch(:title) || "Gumroad"
end
def set_meta_data
@meta_data = {
"about" => {
url: :about_url,
title: "Earn your first dollar online with Gumroad",
description: "Start selling what you know, see what sticks, and get paid. Simple and effective."
},
"features" => {
url: :features_url,
title: "Gumroad features: Simple and powerful e-commerce tools",
description: "Sell books, memberships, courses, and more with Gumroad's simple e-commerce tools. Everything you need to grow your audience."
},
"hackathon" => {
url: :hackathon_url,
title: "Gumroad $100K Niche Marketplace Hackathon",
description: "Build a niche marketplace using Gumroad OSS. $100K in prizes for the best marketplace ideas and implementations."
},
"pricing" => {
url: :pricing_url,
title: "Gumroad pricing: 10% flat fee",
description: "No monthly fees, just a simple 10% cut per sale. Gumroad's pricing is transparent and creator-friendly."
},
"privacy" => {
url: :privacy_url,
title: "Gumroad privacy policy: how we protect your data",
description: "Learn how Gumroad collects, uses, and protects your personal information. Your privacy matters to us."
},
"prohibited" => {
url: :prohibited_url,
title: "Prohibited products on Gumroad",
description: "Understand what products and activities are not allowed on Gumroad to comply with our policies."
},
"terms" => {
url: :terms_url,
title: "Gumroad terms of service",
description: "Review the rules and guidelines for using Gumroad's services. Stay informed and compliant."
},
"small_bets" => {
url: :small_bets_url,
title: "Small Bets by Gumroad",
description: "Explore the Small Bets initiative by Gumroad. Learn, experiment, and grow with small, actionable projects."
}
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/product_reviews_controller.rb | app/controllers/product_reviews_controller.rb | # frozen_string_literal: true
class ProductReviewsController < ApplicationController
include Pagy::Backend
PER_PAGE = 10
before_action :fetch_product, only: [:set]
def index
product = Link.find_by_external_id(permitted_params[:product_id])
return head :not_found unless product.present?
return head :forbidden unless product.display_product_reviews || current_seller == product.user
pagination, reviews = pagy(
product.product_reviews
.alive
.visible_on_product_page
.includes(:response, approved_video: :video_file, purchase: :purchaser)
.order(rating: :desc, created_at: :desc, id: :desc),
page: [permitted_params[:page].to_i, 1].max,
limit: PER_PAGE
)
render json: {
pagination: PagyPresenter.new(pagination).props,
reviews: reviews.map { ProductReviewPresenter.new(_1).product_review_props }
}
end
def show
review = ProductReview
.alive
.visible_on_product_page
.includes(:response, purchase: :purchaser, link: :user)
.find_by_external_id!(permitted_params[:id])
product = review.link
return head :forbidden unless product.display_product_reviews || current_seller == product.user
render json: {
review: ProductReviewPresenter.new(review).product_review_props
}
end
def set
post_review
end
private
def post_review
purchase = @product.sales.find_by_external_id!(params[:purchase_id])
if !ActiveSupport::SecurityUtils.secure_compare(purchase.email_digest, params[:purchase_email_digest].to_s)
render json: { success: false, message: "Sorry, you are not authorized to review this product." }
return
end
if purchase.created_at < 1.year.ago && @product.user.disable_reviews_after_year?
render json: { success: false, message: "Sorry, something went wrong." }
return
end
review = purchase.post_review(
rating: set_params[:rating].to_i,
message: set_params[:message],
video_options: set_params[:video_options] || {}
)
render json: {
success: true,
review: ProductReviewPresenter.new(review.reload).review_form_props
}
rescue ActiveRecord::RecordInvalid => e
render json: { success: false, message: e.message }
rescue StandardError
render json: { success: false, message: "Sorry, something went wrong." }
end
def permitted_params
params.permit(:product_id, :page, :id)
end
def set_params
params.permit(
:rating, :message,
video_options: [
{ destroy: [:id] },
{ create: [:url, :thumbnail_signed_id] }
]
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/support_controller.rb | app/controllers/support_controller.rb | # frozen_string_literal: true
class SupportController < ApplicationController
include ValidateRecaptcha
include HelperWidget
layout "inertia"
def index
return redirect_to help_center_root_path(params.permit(:new_ticket)) unless user_signed_in?
e404 if helper_widget_host.blank?
render inertia: "Support/Index", props: {
host: helper_widget_host,
session: helper_session,
}
end
def create_unauthenticated_ticket
return unless validate_request_params
return render json: { error: "reCAPTCHA verification failed" }, status: :unprocessable_entity unless valid_recaptcha_response?(site_key: GlobalConfig.get("RECAPTCHA_LOGIN_SITE_KEY"))
email = params[:email].strip.downcase
subject = params[:subject].strip
message = params[:message].strip
begin
conversation_slug = create_helper_conversation(email: email, subject: subject, message: message)
render json: { success: true, conversation_slug: conversation_slug }
rescue
render json: { error: "Failed to create support ticket" }, status: :internal_server_error
end
end
private
def set_title
@title = "Support"
end
def validate_request_params
missing_params = []
missing_params << "email" if params[:email].blank?
missing_params << "subject" if params[:subject].blank?
missing_params << "message" if params[:message].blank?
missing_params << "g-recaptcha-response" if params["g-recaptcha-response"].blank? && !Rails.env.test?
if missing_params.any?
render json: { error: "Missing required parameters: #{missing_params.join(', ')}" }, status: :bad_request
return false
end
unless valid_email?(params[:email].strip.downcase)
render json: { error: "Invalid email address" }, status: :bad_request
return false
end
true
end
def valid_email?(email)
email.match?(URI::MailTo::EMAIL_REGEXP)
end
def create_helper_conversation(email:, subject:, message:)
timestamp = (Time.current.to_f * 1000).to_i
email_hash = helper_widget_email_hmac(timestamp, email: email)
response = create_conversation_via_api(
subject: subject,
from_email: email,
message: message,
timestamp: timestamp,
email_hash: email_hash
)
if response.success?
response.parsed_response["conversation_slug"]
else
raise "Helper API error: #{response.code} - #{response.body}"
end
end
def create_conversation_via_api(params)
helper_host = GlobalConfig.get("HELPER_WIDGET_HOST")
raise "Helper widget host not configured" unless helper_host.present?
guest_session = {
email: params[:from_email],
emailHash: params[:email_hash],
timestamp: params[:timestamp]
}
session_response = HTTParty.post(
"#{helper_host}/api/widget/session",
body: guest_session.to_json
)
unless session_response.success?
raise "Helper session creation failed: #{session_response.code}"
end
helper_token = session_response.parsed_response["token"]
conversation_response = HTTParty.post(
"#{helper_host}/api/chat/conversation",
headers: {
"Authorization" => "Bearer #{helper_token}"
},
body: { subject: params[:subject] }.to_json
)
unless conversation_response.success?
raise "Helper conversation creation failed: #{conversation_response.code}"
end
conversation_slug = conversation_response.parsed_response["conversationSlug"]
message_response = HTTParty.post(
"#{helper_host}/api/chat/conversation/#{conversation_slug}/message",
headers: {
"Authorization" => "Bearer #{helper_token}"
},
body: {
content: params[:message],
customerInfoUrl: user_info_api_internal_helper_users_url(host: API_DOMAIN)
}.to_json
)
unless message_response.success?
raise "Helper message creation failed: #{message_response.code}"
end
OpenStruct.new(
success?: true,
parsed_response: { "conversation_slug" => conversation_slug }
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/links_controller.rb | app/controllers/links_controller.rb | # frozen_string_literal: true
class LinksController < ApplicationController
include ProductsHelper, SearchProducts, PreorderHelper, ActionView::Helpers::TextHelper,
ActionView::Helpers::AssetUrlHelper, CustomDomainConfig, AffiliateCookie,
CreateDiscoverSearch, DiscoverCuratedProducts, FetchProductByUniquePermalink
DEFAULT_PRICE = 500
PER_PAGE = 50
skip_before_action :check_suspended, only: %i[index show edit destroy increment_views track_user_action]
PUBLIC_ACTIONS = %i[show search increment_views track_user_action cart_items_count].freeze
before_action :authenticate_user!, except: PUBLIC_ACTIONS
after_action :verify_authorized, except: PUBLIC_ACTIONS
before_action :fetch_product_for_show, only: :show
before_action :check_banned, only: :show
before_action :set_x_robots_tag_header, only: :show
before_action :check_payment_details, only: :index
before_action :set_affiliate_cookie, only: [:show]
before_action :hide_layouts, only: %i[show]
before_action :fetch_product, only: %i[increment_views track_user_action]
before_action :ensure_seller_is_not_deleted, only: [:show]
before_action :check_if_needs_redirect, only: [:show]
before_action :prepare_product_page, only: %i[show]
before_action :set_frontend_performance_sensitive, only: %i[show]
before_action :ensure_domain_belongs_to_seller, only: [:show]
before_action :fetch_product_and_enforce_ownership, only: %i[destroy]
before_action :fetch_product_and_enforce_access, only: %i[update publish unpublish release_preorder update_sections]
layout "inertia", only: [:index, :new]
def index
authorize Link
@guid = SecureRandom.hex
@title = "Products"
@memberships_pagination, @memberships = paginated_memberships(page: 1)
@products_pagination, @products = paginated_products(page: 1)
@price = current_seller.links.last.try(:price_formatted_without_dollar_sign) ||
Money.new(DEFAULT_PRICE, current_seller.currency_type).format(
no_cents_if_whole: true, symbol: false
)
@user_compliance_info = current_seller.fetch_or_build_user_compliance_info
@react_products_page_props = DashboardProductsPagePresenter.new(
pundit_user:,
memberships: @memberships,
memberships_pagination: @memberships_pagination,
products: @products,
products_pagination: @products_pagination
).page_props
render inertia: "Products/Index",
props: { react_products_page_props: @react_products_page_props }
end
def memberships_paged
authorize Link, :index?
pagination, memberships = paginated_memberships(page: paged_params[:page].to_i, query: params[:query])
react_products_page_props = DashboardProductsPagePresenter.new(
pundit_user:,
memberships:,
memberships_pagination: pagination,
products: nil,
products_pagination: nil)
.memberships_table_props
render json: {
pagination: react_products_page_props[:memberships_pagination],
entries: react_products_page_props[:memberships]
}
end
def products_paged
authorize Link, :index?
pagination, products = paginated_products(page: paged_params[:page].to_i, query: params[:query])
react_products_page_props = DashboardProductsPagePresenter.new(
pundit_user:,
memberships: nil,
memberships_pagination: nil,
products:,
products_pagination: pagination
).products_table_props
render json: {
pagination: react_products_page_props[:products_pagination],
entries: react_products_page_props[:products]
}
end
def new
authorize Link
props = ProductPresenter.new_page_props(current_seller:)
@title = "What are you creating?"
render inertia: "Products/New", props:
end
def create
authorize Link
if params[:link][:is_physical]
return head :forbidden unless current_seller.can_create_physical_products?
params[:link][:quantity_enabled] = true
end
@product = current_seller.links.build(link_params)
@product.price_range = params[:link][:price_range]
@product.save_custom_summary(params[:link][:custom_summary]) if params[:link][:custom_summary].present?
@product.draft = true
@product.purchase_disabled_at = Time.current
@product.require_shipping = true if @product.is_physical
@product.display_product_reviews = true
@product.is_tiered_membership = @product.is_recurring_billing
@product.should_show_all_posts = @product.is_tiered_membership
@product.set_template_properties_if_needed
@product.taxonomy = Taxonomy.find_by(slug: "other")
@product.is_bundle = @product.native_type == Link::NATIVE_TYPE_BUNDLE
@product.json_data[:custom_button_text_option] = "donate_prompt" if @product.native_type == Link::NATIVE_TYPE_COFFEE
begin
@product.save!
if params[:link][:ai_prompt].present? && Feature.active?(:ai_product_generation, current_seller)
generate_product_details_using_ai
end
rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid, Link::LinkInvalid
@error_message = if @product&.errors&.any?
@product.errors.full_messages.first
elsif @preorder_link&.errors&.any?
@preorder_link.errors.full_messages[0]
else
"Sorry, something went wrong."
end
return respond_to do |format|
response = { success: false, error_message: @error_message }
format.json { render json: response }
format.html { render html: "<textarea>#{response.to_json}</textarea>" }
end
end
create_user_event("add_product")
respond_to do |format|
response = { success: true, redirect_to: edit_link_path(@product) }
format.html { render plain: response.to_json.to_s }
format.json { render json: response }
end
end
def show
return redirect_to custom_domain_coffee_path if @product.native_type == Link::NATIVE_TYPE_COFFEE
ActiveRecord::Base.connection.stick_to_primary!
# Force a preload of all association data used in rendering
preload_product
@show_user_favicon = true
if params[:wanted] == "true"
params[:option] ||= params[:variant] && @product.options.find { |o| o[:name] == params[:variant] }&.[](:id)
BasePrice::Recurrence::ALLOWED_RECURRENCES.each do |r|
params[:recurrence] ||= r if params[r] == "true"
end
params[:price] = (params[:price].to_f * 100).to_i if params[:price].present?
cart_item = @product.cart_item(params)
unless (@product.customizable_price || cart_item[:option]&.[](:is_pwyw)) &&
(params[:price].blank? || params[:price] < cart_item[:price])
redirect_to checkout_index_url(**params.permit!, host: DOMAIN, product: @product.unique_permalink,
rent: cart_item[:rental], recurrence: cart_item[:recurrence],
price: cart_item[:price],
code: params[:offer_code] || params[:code],
affiliate_id: params[:affiliate_id] || params[:a],
referrer: params[:referrer] || request.referrer),
allow_other_host: true
end
end
@card_data_handling_mode = CardDataHandlingMode.get_card_data_handling_mode(@product.user)
@paypal_merchant_currency = @product.user.native_paypal_payment_enabled? ?
@product.user.merchant_account_currency(PaypalChargeProcessor.charge_processor_id) :
ChargeProcessor::DEFAULT_CURRENCY_CODE
@pay_with_card_enabled = @product.user.pay_with_card_enabled?
presenter = ProductPresenter.new(pundit_user:, product: @product, request:)
presenter_props = { recommended_by: params[:recommended_by], discount_code: params[:offer_code] || params[:code], quantity: (params[:quantity] || 1).to_i, layout: params[:layout], seller_custom_domain_url: }
@product_props = params[:embed] || params[:overlay] ? presenter.product_props(**presenter_props) : presenter.product_page_props(**presenter_props)
@body_class = "iframe" if params[:overlay] || params[:embed]
if ["search", "discover"].include?(params[:recommended_by])
create_discover_search!(
clicked_resource: @product,
query: params[:query],
autocomplete: params[:autocomplete] == "true"
)
end
if params[:layout] == Product::Layout::DISCOVER
@discover_props = { taxonomy_path: @product.taxonomy&.ancestry_path&.join("/"), taxonomies_for_nav: }
end
set_noindex_header if !@product.alive?
respond_to do |format|
format.html
format.json { render json: @product.as_json }
format.any { e404 }
end
end
def cart_items_count
@hide_layouts = true
@disable_third_party_analytics = true
end
def search
search_params = params
on_profile = search_params[:user_id].present?
if on_profile
user = User.find_by_external_id(search_params[:user_id])
section = user && user.seller_profile_products_sections.on_profile.find_by_external_id(search_params[:section_id])
return render json: { total: 0, filetypes_data: [], tags_data: [], products: [] } if section.nil?
search_params[:section] = section
search_params[:is_alive_on_profile] = true
search_params[:user_id] = user.id
search_params[:sort] = section.default_product_sort if search_params[:sort].nil?
search_params[:sort] = ProductSortKey::PAGE_LAYOUT if search_params[:sort] == "default"
search_params[:ids]&.map! { ObfuscateIds.decrypt(_1) }
else
search_params[:sort] = ProductSortKey::FEATURED if search_params[:sort] == "default"
search_params[:include_rated_as_adult] = logged_in_user&.show_nsfw_products?
search_params[:curated_product_ids] = params[:curated_product_ids]&.map { ObfuscateIds.decrypt(_1) }
end
if search_params[:taxonomy].present?
search_params[:taxonomy_id] = Taxonomy.find_by_path(params[:taxonomy].split("/"))&.id
search_params[:include_taxonomy_descendants] = true
end
if on_profile
recommended_by = search_params[:recommended_by]
else
recommended_by = RecommendationType::GUMROAD_SEARCH_RECOMMENDATION
create_discover_search!(query: search_params[:query], taxonomy_id: search_params[:taxonomy_id])
end
results = search_products(search_params)
results[:products] = results[:products].includes(ProductPresenter::ASSOCIATIONS_FOR_CARD).map do |product|
ProductPresenter.card_for_web(
product:,
request:,
recommended_by:,
target: on_profile ? Product::Layout::PROFILE : Product::Layout::DISCOVER,
show_seller: !on_profile,
query: (search_params[:query] unless on_profile),
offer_code: (search_params[:offer_code] unless on_profile)
)
end
render json: results
end
def check_if_needs_redirect
# If the request is for the product's custom domain, don't redirect
return if product_by_custom_domain.present?
# Else, redirect to the creator's subdomain, if it exists.
# E.g., we want to redirect gumroad.com/l/id to username.gumroad.com/l/id
creator_subdomain_with_protocol = @product.user.subdomain_with_protocol
target_host = !@is_user_custom_domain && creator_subdomain_with_protocol.present? ? creator_subdomain_with_protocol : request.host
target_permalink = @product.general_permalink
searched_id = params[:id] || params[:link_id]
if target_host != request.host || target_permalink != searched_id
target_product_url = if params[:code].present?
short_link_offer_code_url(target_permalink, code: params[:code], host: target_host, format: params[:format])
else
short_link_url(target_permalink, host: target_host, format: params[:format])
end
# Attaching raw query string to the redirect URL to preserve the original encoding in the request.
# For example, we use '%20' instead of '+' in query string when the variant name contains space.
# If we use request.query_parameters while redirecting, it would convert '%20' to '+' which would break
# variant auto selection.
query_string = "?#{request.query_string}" if request.query_string.present?
redirect_to "#{target_product_url}#{query_string}", status: :moved_permanently, allow_other_host: true
end
end
def set_x_robots_tag_header
set_noindex_header if params[:code].present?
end
def increment_views
skip = is_bot?
skip |= logged_in_user.present? && (@product.user_id == current_seller.id || logged_in_user.is_team_member?)
skip |= impersonating_user&.id
unless skip
create_product_page_view(
user_id: logged_in_user&.id,
referrer: Array.wrap(params[:referrer]).compact_blank.last || request.referrer,
was_product_recommended: ActiveModel::Type::Boolean.new.cast(params[:was_product_recommended]),
view_url: params[:view_url] || request.env["PATH_INFO"]
)
end
render json: { success: true }
end
def track_user_action
create_user_event(params[:event_name]) unless logged_in_user == @product.user
render json: { success: true }
end
def edit
fetch_product_by_unique_permalink
authorize @product
redirect_to bundle_path(@product.external_id) if @product.is_bundle?
@title = @product.name
@presenter = ProductPresenter.new(product: @product, pundit_user:)
end
def update
authorize @product
begin
ActiveRecord::Base.transaction do
@product.assign_attributes(product_permitted_params.except(
:products,
:description,
:cancellation_discount,
:custom_button_text_option,
:custom_summary,
:custom_attributes,
:file_attributes,
:covers,
:refund_policy,
:product_refund_policy_enabled,
:seller_refund_policy_enabled,
:integrations,
:variants,
:tags,
:section_ids,
:availabilities,
:custom_domain,
:rich_content,
:files,
:public_files,
:shipping_destinations,
:call_limitation_info,
:installment_plan,
:community_chat_enabled
))
@product.description = SaveContentUpsellsService.new(seller: @product.user, content: product_permitted_params[:description], old_content: @product.description_was).from_html
@product.skus_enabled = false
@product.save_custom_button_text_option(product_permitted_params[:custom_button_text_option]) unless product_permitted_params[:custom_button_text_option].nil?
@product.save_custom_summary(product_permitted_params[:custom_summary]) unless product_permitted_params[:custom_summary].nil?
@product.save_custom_attributes((product_permitted_params[:custom_attributes] || []).filter { _1[:name].present? || _1[:description].present? })
@product.save_tags!(product_permitted_params[:tags] || [])
@product.reorder_previews((product_permitted_params[:covers] || []).map.with_index.to_h)
if !current_seller.account_level_refund_policy_enabled?
@product.product_refund_policy_enabled = product_permitted_params[:product_refund_policy_enabled]
if product_permitted_params[:refund_policy].present? && product_permitted_params[:product_refund_policy_enabled]
@product.find_or_initialize_product_refund_policy.update!(product_permitted_params[:refund_policy])
end
end
@product.show_in_sections!(product_permitted_params[:section_ids] || [])
@product.save_shipping_destinations!(product_permitted_params[:shipping_destinations] || []) if @product.is_physical
if Feature.active?(:cancellation_discounts, @product.user) && (product_permitted_params[:cancellation_discount].present? || @product.cancellation_discount_offer_code.present?)
begin
Product::SaveCancellationDiscountService.new(@product, product_permitted_params[:cancellation_discount]).perform
rescue ActiveRecord::RecordInvalid => e
return render json: { error_message: e.record.errors.full_messages.first }, status: :unprocessable_entity
end
end
if @product.native_type === Link::NATIVE_TYPE_COFFEE
@product.suggested_price_cents = product_permitted_params[:variants].map { _1[:price_difference_cents] }.max
end
# TODO clean this up
rich_content = product_permitted_params[:rich_content] || []
rich_content_params = [*rich_content]
product_permitted_params[:variants].each { rich_content_params.push(*_1[:rich_content]) } if product_permitted_params[:variants].present?
rich_content_params = rich_content_params.flat_map { _1[:description] = _1.dig(:description, :content) }
rich_contents_to_keep = []
SaveFilesService.perform(@product, product_permitted_params, rich_content_params)
existing_rich_contents = @product.alive_rich_contents.to_a
rich_content.each.with_index do |product_rich_content, index|
rich_content = existing_rich_contents.find { |c| c.external_id === product_rich_content[:id] } || @product.alive_rich_contents.build
product_rich_content[:description] = SaveContentUpsellsService.new(seller: @product.user, content: product_rich_content[:description], old_content: rich_content.description || []).from_rich_content
rich_content.update!(title: product_rich_content[:title].presence, description: product_rich_content[:description].presence || [], position: index)
rich_contents_to_keep << rich_content
end
(existing_rich_contents - rich_contents_to_keep).each(&:mark_deleted!)
Product::SaveIntegrationsService.perform(@product, product_permitted_params[:integrations])
update_variants
update_removed_file_attributes
update_custom_domain
update_availabilities
update_call_limitation_info
update_installment_plan
Product::SavePostPurchaseCustomFieldsService.new(@product).perform
@product.is_licensed = @product.has_embedded_license_key?
unless @product.is_licensed
@product.is_multiseat_license = false
end
@product.description = SavePublicFilesService.new(resource: @product, files_params: product_permitted_params[:public_files], content: @product.description).process
@product.save!
toggle_community_chat!(product_permitted_params[:community_chat_enabled])
@product.generate_product_files_archives!
end
rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid, Link::LinkInvalid => e
if @product.errors.details[:custom_fields].present?
error_message = "You must add titles to all of your inputs"
else
error_message = @product.errors.full_messages.first || e.message
end
return render json: { error_message: }, status: :unprocessable_entity
end
invalid_currency_offer_codes = @product.product_and_universal_offer_codes.reject do |offer_code|
offer_code.is_currency_valid?(@product)
end.map(&:code)
invalid_amount_offer_codes = @product.product_and_universal_offer_codes.reject { _1.is_amount_valid?(@product) }.map(&:code)
all_invalid_offer_codes = (invalid_currency_offer_codes + invalid_amount_offer_codes).uniq
if all_invalid_offer_codes.any?
# Determine the main issue type for the message
has_currency_issues = invalid_currency_offer_codes.any?
has_amount_issues = invalid_amount_offer_codes.any?
if has_currency_issues && has_amount_issues
issue_description = "#{"has".pluralize(all_invalid_offer_codes.count)} currency mismatches or would discount this product below #{@product.min_price_formatted}"
elsif has_currency_issues
issue_description = "#{"has".pluralize(all_invalid_offer_codes.count)} currency #{"mismatch".pluralize(all_invalid_offer_codes.count)} with this product"
else
issue_description = "#{all_invalid_offer_codes.count > 1 ? "discount" : "discounts"} this product below #{@product.min_price_formatted}, but not to #{MoneyFormatter.format(0, @product.price_currency_type.to_sym, no_cents_if_whole: true, symbol: true)}"
end
return render json: {
warning_message: "The following offer #{"code".pluralize(all_invalid_offer_codes.count)} #{issue_description}: #{all_invalid_offer_codes.join(", ")}. Please update #{all_invalid_offer_codes.length > 1 ? "them or they" : "it or it"} will not work at checkout."
}
end
head :no_content
end
def unpublish
authorize @product
@product.unpublish!
render json: { success: true }
end
def publish
authorize @product
if @product.user.email.blank?
return render json: { success: false, error_message: "<span>To publish a product, we need you to have an email. <a href=\"#{settings_main_url}\">Set an email</a> to continue.</span>" }
end
begin
@product.publish!
rescue Link::LinkInvalid, ActiveRecord::RecordInvalid
return render json: { success: false, error_message: @product.errors.full_messages[0] }
rescue => e
Bugsnag.notify(e)
return render json: { success: false, error_message: "Something broke. We're looking into what happened. Sorry about this!" }
end
render json: { success: true }
end
def destroy
authorize @product
@product.delete!
render json: { success: true }
end
def update_sections
authorize @product
ActiveRecord::Base.transaction do
@product.sections = Array(params[:sections]).map! { ObfuscateIds.decrypt(_1) }
@product.main_section_index = params[:main_section_index].to_i
@product.save!
@product.seller_profile_sections.where.not(id: @product.sections).destroy_all
end
end
def release_preorder
authorize @product
preorder_link = @product.preorder_link
preorder_link.is_being_manually_released_by_the_seller = true
released_successfully = preorder_link.release!
if released_successfully
render json: { success: true }
else
render json: { success: false,
error_message: !@product.has_content? ? "Sorry, your pre-order was not released due to no file or redirect URL being specified. Please do that and try again!" : "Your pre-order was released successfully." }
end
end
def send_sample_price_change_email
fetch_product_by_unique_permalink
authorize @product, :update?
tier = @product.tiers.find_by_external_id(params.require(:tier_id))
return e404_json unless tier.present?
CustomerLowPriorityMailer.sample_subscription_price_change_notification(
user: logged_in_user,
tier:,
effective_date: params[:effective_date].present? ? Date.parse(params[:effective_date]) : tier.subscription_price_change_effective_date,
recurrence: params.require(:recurrence),
new_price: (params.require(:amount).to_f * 100).to_i,
custom_message: strip_tags(params[:custom_message]).present? ? params[:custom_message] : nil,
).deliver_later
render json: { success: true }
end
private
def fetch_product_for_show
fetch_product_by_custom_domain || fetch_product_by_general_permalink
end
def fetch_product_by_custom_domain
@product = product_by_custom_domain
end
# *** DO NOT USE THIS METHOD for actions that respond to non-subdomain URLs ***
#
# Used for actions where a product's general (custom or unique) permalink is used to identify the product.
# Usually these are public-facing URLs with permalink as part of the URL.
#
# Since custom permalinks aren't globally unique, this method is only guaranteed to fetch the unique product
# if the owner of the product can be identified by the URL's subdomain.
#
# To support legacy (non-subdomain) URLs, when no creator can be identify via subdomain, this method will fetch the
# oldest product with given unique or custom permalink.
def fetch_product_by_general_permalink
custom_or_unique_permalink = params[:id] || params[:link_id]
e404 if custom_or_unique_permalink.blank?
@product = Link.fetch_leniently(custom_or_unique_permalink, user: user_by_domain(request.host)) || e404
end
def preload_product
@product = Link.includes(
:variant_categories_alive,
:alive_prices,
{ display_asset_previews: [:file_attachment, :file_blob] },
:alive_third_party_analytics
).find(@product.id)
end
def product_permitted_params
@_product_permitted_params ||= params.permit(policy(@product).product_permitted_attributes)
end
def check_banned
e404 if @product.banned?
end
def ensure_seller_is_not_deleted
e404_page if @product.user.deleted?
end
def ensure_domain_belongs_to_seller
if @is_user_custom_domain
e404_page unless @product.user == user_by_domain(request.host)
end
end
def prepare_product_page
@user = @product.user
@title = @product.name
@body_id = "product_page"
@is_on_product_page = true
@debug = params[:debug] && !Rails.env.production?
end
def link_params
# These attributes are derived from a combination of attr_accessible on Link and other attributes as needed
params.require(:link).permit(:name, :price_range, :rental_price_range, :price_currency_type, :price_cents, :rental_price_cents,
:preview_url, :description, :unique_permalink, :native_type,
:max_purchase_count, :require_shipping, :custom_receipt,
:filetype, :filegroup, :size, :duration, :bitrate, :framerate,
:pagelength, :width, :height, :custom_permalink,
:suggested_price, :suggested_price_cents, :banned_at,
:risk_score, :risk_score_updated_at, :customizable_price,
:is_recurring_billing, :subscription_duration, :json_data,
:is_physical, :skus_enabled, :block_access_after_membership_cancellation, :purchase_type,
:should_include_last_post, :should_show_all_posts, :should_show_sales_count, :duration_in_months,
:free_trial_enabled, :free_trial_duration_amount, :free_trial_duration_unit,
:is_adult, :is_epublication, :product_refund_policy_enabled, :seller_refund_policy_enabled,
:refund_policy, :taxonomy_id)
end
def paged_params
params.permit(:page, sort: [:key, :direction])
end
def paginated_memberships(page:, query: nil)
memberships = current_seller.products.membership.visible_and_not_archived
memberships = memberships.where("name like ?", "%#{query}%") if query.present?
sort_and_paginate_products(**paged_params[:sort].to_h.symbolize_keys, page:, collection: memberships, per_page: PER_PAGE, user_id: current_seller.id)
end
def paginated_products(page:, query: nil)
products = current_seller
.products
.includes([
thumbnail: { file_attachment: { blob: { variant_records: { image_attachment: :blob } } } },
thumbnail_alive: { file_attachment: { blob: { variant_records: { image_attachment: :blob } } } },
])
.non_membership
.visible_and_not_archived
products = products.where("links.name like ?", "%#{query}%") if query.present?
sort_and_paginate_products(**paged_params[:sort].to_h.symbolize_keys, page:, collection: products, per_page: PER_PAGE, user_id: current_seller.id)
end
def update_removed_file_attributes
current = @product.file_info_for_product_page.keys.map(&:to_s)
updated = (product_permitted_params[:file_attributes] || []).map { _1[:name] }
@product.add_removed_file_info_attributes(current - updated)
end
def update_variants
variant_category = @product.variant_categories_alive.first
variants = product_permitted_params[:variants] || []
if variants.any? || @product.is_tiered_membership?
variant_category_params = variant_category.present? ?
{
id: variant_category.external_id,
name: variant_category.title,
} :
{ name: @product.is_tiered_membership? ? "Tier" : "Version" }
Product::VariantsUpdaterService.new(
product: @product,
variants_params: [
{
**variant_category_params,
options: variants,
}
],
).perform
elsif variant_category.present?
Product::VariantsUpdaterService.new(
product: @product,
variants_params: [
{
id: variant_category.external_id,
options: nil,
}
]).perform
end
end
def update_custom_domain
if product_permitted_params[:custom_domain].present?
custom_domain = @product.custom_domain || @product.build_custom_domain
custom_domain.domain = product_permitted_params[:custom_domain]
custom_domain.verify(allow_incrementing_failed_verification_attempts_count: false)
custom_domain.save!
elsif product_permitted_params[:custom_domain] == "" && @product.custom_domain.present?
@product.custom_domain.mark_deleted!
end
end
def update_availabilities
return unless @product.native_type == Link::NATIVE_TYPE_CALL
existing_availabilities = @product.call_availabilities
availabilities_to_keep = []
(product_permitted_params[:availabilities] || []).each do |availability_params|
availability = existing_availabilities.find { _1.id == availability_params[:id] } || @product.call_availabilities.build
availability.update!(availability_params.except(:id))
availabilities_to_keep << availability
end
(existing_availabilities - availabilities_to_keep).each(&:destroy!)
end
def update_call_limitation_info
return unless @product.native_type == Link::NATIVE_TYPE_CALL
@product.call_limitation_info.update!(product_permitted_params[:call_limitation_info])
end
def update_installment_plan
return unless @product.eligible_for_installment_plans?
if @product.installment_plan && product_permitted_params[:installment_plan].present?
@product.installment_plan.assign_attributes(product_permitted_params[:installment_plan])
return unless @product.installment_plan.changed?
end
@product.installment_plan&.destroy_if_no_payment_options!
@product.reset_installment_plan
if product_permitted_params[:installment_plan].present?
@product.create_installment_plan!(product_permitted_params[:installment_plan])
end
end
def toggle_community_chat!(enabled)
return unless Feature.active?(:communities, current_seller)
return if [Link::NATIVE_TYPE_COFFEE, Link::NATIVE_TYPE_BUNDLE].include?(@product.native_type)
@product.toggle_community_chat!(enabled)
end
def generate_product_details_using_ai
if Rails.env.test?
generate_product_cover_and_thumbnail_using_ai
generate_product_content_using_ai
else
cover_thread = Thread.new { generate_product_cover_and_thumbnail_using_ai }
content_thread = Thread.new { generate_product_content_using_ai }
cover_thread.join
content_thread.join
end
end
def generate_product_cover_and_thumbnail_using_ai
return unless @product.persisted?
begin
service = Ai::ProductDetailsGeneratorService.new(current_seller:)
result = service.generate_cover_image(product_name: @product.name)
image_data = result[:image_data]
create_blob = ->(identifier) {
ActiveStorage::Blob.create_and_upload!(
io: StringIO.new(image_data),
filename: "#{@product.external_id}_#{identifier}_#{Time.now.to_i}.jpeg",
content_type: "image/jpeg",
identify: false
)
}
cover_image_blob = create_blob.call("cover")
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/tags_controller.rb | app/controllers/tags_controller.rb | # frozen_string_literal: true
class TagsController < ApplicationController
def index
render json: params[:text] ? Tag.by_text(text: params[:text]) : { success: false }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/instant_payouts_controller.rb | app/controllers/instant_payouts_controller.rb | # frozen_string_literal: true
class InstantPayoutsController < Sellers::BaseController
def create
authorize :instant_payout
result = InstantPayoutsService.new(current_seller, date: Date.parse(params.require(:date))).perform
if result[:success]
redirect_to balance_path, notice: "Instant payout initiated successfully"
else
redirect_to balance_path, alert: result[:error]
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/secure_redirect_controller.rb | app/controllers/secure_redirect_controller.rb | # frozen_string_literal: true
class SecureRedirectController < ApplicationController
before_action :validate_params, only: [:new, :create]
before_action :set_encrypted_params, only: [:new, :create]
before_action :set_react_component_props, only: [:new, :create]
def new
end
def create
confirmation_text = params[:confirmation_text]
if confirmation_text.blank?
return render json: { error: "Please enter the confirmation text" }, status: :unprocessable_entity
end
# Decrypt and parse the bundled payload
begin
payload_json = SecureEncryptService.decrypt(@encrypted_payload)
if payload_json.nil?
return render json: { error: "Invalid request" }, status: :unprocessable_entity
end
payload = JSON.parse(payload_json)
destination = payload["destination"]
confirmation_texts = payload["confirmation_texts"] || []
send_confirmation_text = payload["send_confirmation_text"]
# Verify the payload is recent (within 24 hours)
if payload["created_at"] && Time.current.to_i - payload["created_at"] > 24.hours
return render json: { error: "This link has expired" }, status: :unprocessable_entity
end
rescue JSON::ParserError, NoMethodError
return render json: { error: "Invalid request" }, status: :unprocessable_entity
end
# Check if confirmation text matches any of the allowed texts
if confirmation_texts.any? { |text| ActiveSupport::SecurityUtils.secure_compare(text, confirmation_text) }
if send_confirmation_text
begin
uri = URI.parse(destination)
query_params = Rack::Utils.parse_query(uri.query)
query_params["confirmation_text"] = confirmation_text
uri.query = query_params.to_query
destination = uri.to_s
rescue URI::InvalidURIError
Rails.logger.error("Invalid destination: #{destination}")
end
end
if destination.present?
redirect_to destination
else
render json: { error: "Invalid destination" }, status: :unprocessable_entity
end
else
render json: { error: @error_message }, status: :unprocessable_entity
end
end
private
def validate_params
if params[:encrypted_payload].blank?
redirect_to root_path
end
end
def set_encrypted_params
@encrypted_payload = params[:encrypted_payload]
@message = params[:message].presence || "Please enter the confirmation text to continue to your destination."
@field_name = params[:field_name].presence || "Confirmation text"
@error_message = params[:error_message].presence || "Confirmation text does not match"
end
def set_react_component_props
props = {
message: @message,
field_name: @field_name,
error_message: @error_message,
encrypted_payload: @encrypted_payload,
form_action: secure_url_redirect_path,
authenticity_token: form_authenticity_token
}
props[:flash_error] = flash[:error] if flash[:error].present?
@react_component_props = props
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/braintree_controller.rb | app/controllers/braintree_controller.rb | # frozen_string_literal: true
# Braintree controller contains any stateless backend API calls we need to make for the frontend when tokenizing
# with Braintree. No other Braintree specific logic should ever live here, but instead can be found in the Charging
# module and in the BraintreeChargeProcessor implementation.
class BraintreeController < ApplicationController
# Cache the client token for 10 minutes for each user (based on their guid). Disabled.
# caches_action :client_token, expires_in: 10.minutes, cache_path: proc { cookies[:_gumroad_guid] }
def client_token
render json: {
clientToken: Braintree::ClientToken.generate
}
rescue *BraintreeExceptions::UNAVAILABLE => e
error_message = "BraintreeException: #{e.inspect}"
Rails.logger.error error_message
render json: {
clientToken: nil
}
end
def generate_transient_customer_token
return render json: { transient_customer_store_key: nil } if params[:braintree_nonce].blank? || cookies[:_gumroad_guid].blank?
begin
raw_transient_customer_store_key = "#{cookies[:_gumroad_guid]}-#{SecureRandom.uuid}"
transient_customer_store_key = ObfuscateIds.encrypt(raw_transient_customer_store_key)
transient_customer_token = BraintreeChargeableTransientCustomer.tokenize_nonce_to_transient_customer(params[:braintree_nonce],
transient_customer_store_key)
transient_customer_store_key = transient_customer_token.try(:transient_customer_store_key)
render json: { transient_customer_store_key: }
rescue ChargeProcessorInvalidRequestError
render json: {
error: "Please check your card information, we couldn't verify it."
}
rescue ChargeProcessorUnavailableError
render json: {
error: "There is a temporary problem, please try again (your card was not charged)."
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/signup_controller.rb | app/controllers/signup_controller.rb | # frozen_string_literal: true
class SignupController < Devise::RegistrationsController
include OauthApplicationConfig, ValidateRecaptcha, InertiaRendering
before_action :verify_captcha_and_handle_existing_users, only: :create
before_action :set_noindex_header, only: :new, if: -> { params[:next]&.start_with?("/oauth/authorize") }
layout "inertia", only: [:new]
def new
@title = "Sign Up"
auth_presenter = AuthPresenter.new(params:, application: @application)
render inertia: "Signup/New", props: auth_presenter.signup_props
end
def create
@user = build_user_with_params(permitted_params) if params[:user]
if @user&.save
card_data_handling_mode = CardParamsHelper.get_card_data_handling_mode(permitted_params)
card_data_handling_error = CardParamsHelper.check_for_errors(permitted_params)
if card_data_handling_error
Rails.logger.error("Card data handling error at Signup: #{card_data_handling_error.error_message} #{card_data_handling_error.card_error_code}")
else
begin
chargeable = CardParamsHelper.build_chargeable(params[:user])
chargeable.prepare! if chargeable.present?
rescue ChargeProcessorInvalidRequestError, ChargeProcessorUnavailableError => e
Rails.logger.error("Error while persisting card during signup with #{chargeable.try(:charge_processor_id)}: #{e.message}")
chargeable = nil
rescue ChargeProcessorCardError => e
Rails.logger.info("Error while persisting card during signup with #{chargeable.try(:charge_processor_id)}: #{e.message}")
chargeable = nil
end
end
attach_past_purchases_to_user(chargeable, card_data_handling_mode)
@user.mark_as_invited(params[:referral]) if params[:referral].present?
sign_in @user
create_user_event("signup")
# Do not require 2FA for newly signed up users
remember_two_factor_auth
respond_to do |format|
format.html { redirect_to login_path_for(@user), allow_other_host: true }
format.json { render json: { success: true, redirect_location: login_path_for(@user) } }
end
else
error_message = if !params[:user] || params[:user][:email].blank?
"Please provide a valid email address."
elsif params[:user][:password].blank?
"Please provide a password."
else
@user.errors.full_messages[0]
end
respond_to do |format|
format.html { redirect_with_signup_error(error_message) }
format.json { render json: { success: false, error_message: error_message } }
end
end
end
def save_to_library
@user = build_user_with_params(permitted_params) if params[:user]
if @user&.save
attach_past_purchases_to_user(nil, nil)
return render json: { success: true }
end
render json: {
success: false,
error_message: @user && @user.errors.full_messages[0]
}
end
private
def attach_past_purchases_to_user(chargeable, card_data_handling_mode)
purchase = Purchase.find_by_external_id(params[:user][:purchase_id]) if params[:user][:purchase_id].present?
purchase&.attach_to_user_and_card(@user, chargeable, card_data_handling_mode)
if params[:user][:email].present?
Purchase.where(email: params[:user][:email], purchaser_id: nil).each do |past_purchase|
past_purchase.attach_to_user_and_card(@user, chargeable, card_data_handling_mode)
end
end
end
def permitted_params
params.require(:user).permit(UsersController::USER_PERMITTED_ATTRS)
end
def verify_captcha_and_handle_existing_users
if params[:user] && params[:user][:buyer_signup].blank?
site_key = GlobalConfig.get("RECAPTCHA_SIGNUP_SITE_KEY")
if !(Rails.env.development? && site_key.blank?) && !valid_recaptcha_response?(site_key: site_key)
respond_to do |format|
format.html { redirect_with_signup_error("Sorry, we could not verify the CAPTCHA. Please try again.") }
format.json { render json: { success: false, error_message: "Sorry, we could not verify the CAPTCHA. Please try again." } }
end
return
end
end
return unless params[:user] && params[:user][:password].present? && params[:user][:email].present?
user = User.find_by(email: params[:user][:email])
return unless user
if !user.deleted? && user.try(:valid_password?, params[:user][:password])
sign_in_or_prepare_for_two_factor_auth(user)
respond_to do |format|
format.html { redirect_to login_path_for(user) }
format.json { render json: { success: true, redirect_location: login_path_for(user) } }
end
else
respond_to do |format|
format.html { redirect_with_signup_error("An account already exists with this email.") }
format.json { render json: { success: false, error_message: "An account already exists with this email." } }
end
end
end
def redirect_with_signup_error(message)
redirect_to signup_path, warning: message, status: :see_other
end
def build_user_with_params(user_params = nil)
return unless user_params.present?
# Merchant Migration: Enable this when we want to enforce check for new users
# user_params[:check_merchant_account_is_linked] = true
create_tos_agreement = user_params.delete(:terms_accepted).present?
user = User.new(user_params)
user.account_created_ip = request.remote_ip
if user_params[:buyer_signup].present?
user.buyer_signup = true
end
user.tos_agreements.build(ip: request.remote_ip) if create_tos_agreement
# To abide by new Canadian anti-spam laws.
user.announcement_notification_enabled = false if GeoIp.lookup(user.account_created_ip).try(:country_code) == Compliance::Countries::CAN.alpha2
user
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/purchases_controller.rb | app/controllers/purchases_controller.rb | # frozen_string_literal: true
class PurchasesController < ApplicationController
include CurrencyHelper, PreorderHelper, RecommendationType, ValidateRecaptcha, ProcessRefund
include Order::ResponseHelpers
SEARCH_RESULTS_PER_PAGE = 100
PARAM_TO_ATTRIBUTE_MAPPINGS = {
friend: :friend_actions,
plugins: :purchaser_plugins,
vat_id: :business_vat_id,
is_preorder: :is_preorder_authorization,
cc_zipcode: :credit_card_zipcode,
tax_country_election: :sales_tax_country_code_election,
stripe_setup_intent_id: :processor_setup_intent_id
}
PARAMS_TO_REMOVE_IF_BLANK = [:full_name, :email]
PUBLIC_ACTIONS = %i[
confirm subscribe unsubscribe send_invoice generate_invoice receipt resend_receipt
update_subscription charge_preorder confirm_generate_invoice confirm_receipt_email
].freeze
before_action :authenticate_user!, except: PUBLIC_ACTIONS
after_action :verify_authorized, except: PUBLIC_ACTIONS
before_action :authenticate_subscription!, only: %i[update_subscription]
before_action :authenticate_preorder!, only: %i[charge_preorder]
before_action :validate_purchase_request, only: [:update_subscription, :charge_preorder]
before_action :set_purchase, only: %i[
update resend_receipt send_invoice generate_invoice change_can_contact cancel_preorder_by_seller receipt
revoke_access undo_revoke_access confirm_receipt_email
]
before_action :verify_current_seller_is_seller_for_purchase, only: %i[update change_can_contact cancel_preorder_by_seller]
before_action :hide_layouts, only: %i[subscribe unsubscribe generate_invoice receipt confirm_receipt_email]
before_action :check_for_successful_purchase_for_vat_refund, only: [:send_invoice]
before_action :set_noindex_header, only: [:receipt, :generate_invoice, :confirm_generate_invoice, :confirm_receipt_email]
before_action :require_email_confirmation, only: [:generate_invoice, :send_invoice]
def confirm
ActiveRecord::Base.connection.stick_to_primary!
@purchase = Purchase.find_by_external_id(params[:id])
e404 unless @purchase
error = Purchase::ConfirmService.new(purchase: @purchase, params:).perform
if error
render_error(error, purchase: @purchase)
else
create_purchase_event(@purchase)
handle_recommended_purchase(@purchase) if @purchase.was_product_recommended
render_create_success(@purchase)
end
end
def unsubscribe
@purchase = Purchase.find_by_secure_external_id(params[:id], scope: "unsubscribe")
# If the confirmation_text is present, we are here from secure_redirect_controller#create.
# There's a chance Charge#id is used instead of Purchase#id in the original unsubscribe URL.
# We need to look up the purchase by Charge#id in that case.
if params[:confirmation_text].present? && @purchase&.email != params[:confirmation_text]
@purchase = Purchase.find_by(id: @purchase.charge.id) if @purchase.charge.present?
if @purchase&.email != params[:confirmation_text]
Rails.logger.info("[Error unsubscribing buyer] purchase: #{@purchase&.id}, confirmation_text: #{params[:confirmation_text]}")
return redirect_to(root_path)
end
end
if @purchase.present?
@purchase.unsubscribe_buyer
return
end
# Fall back to legacy external_id and initiate secure redirect flow
purchase = Purchase.find_by_external_id(params[:id])
charge = Charge.find_by_external_id(params[:id])
e404 if purchase.blank? && charge.blank?
confirmation_emails = Set.new
if charge.present? && charge.successful_purchases.any?
confirmation_emails += charge.successful_purchases.map(&:email)
unless purchase.present?
purchase = charge.successful_purchases.last
end
end
confirmation_emails << purchase.email
if confirmation_emails.any?
destination_url = unsubscribe_purchase_url(id: purchase.secure_external_id(scope: "unsubscribe", expires_at: 2.days.from_now))
# Bundle confirmation_text and destination into a single encrypted payload
secure_payload = {
destination: destination_url,
confirmation_texts: confirmation_emails.to_a,
created_at: Time.current.to_i,
send_confirmation_text: true
}
encrypted_payload = SecureEncryptService.encrypt(secure_payload.to_json)
message = "Please enter your email address to unsubscribe"
error_message = "Email address does not match"
field_name = "Email address"
redirect_to secure_url_redirect_path(
encrypted_payload: encrypted_payload,
message: message,
field_name: field_name,
error_message: error_message
)
return
end
e404
end
def subscribe
(@purchase = Purchase.find_by_external_id(params[:id])) || e404
Purchase.where(email: @purchase.email, seller_id: @purchase.seller_id, can_contact: false).find_each do |purchase|
purchase.update!(can_contact: true)
end
end
def charge_preorder
return render json: { success: true, next: @preorder.link.long_url } if @preorder.state != "authorization_successful"
card_data_handling_mode = CardParamsHelper.get_card_data_handling_mode(params)
card_data_handling_error = CardParamsHelper.check_for_errors(params)
unless card_data_handling_error
chargeable = CardParamsHelper.build_chargeable(params)
if chargeable
card = CreditCard.create(chargeable, card_data_handling_mode, nil)
@preorder.credit_card = card if card.errors.empty?
@preorder.save
end
end
purchase_params = {
card_data_handling_mode:,
card_data_handling_error:
}
purchase = @preorder.charge!(ip_address: request.remote_ip, browser_guid: cookies[:_gumroad_guid], purchase_params:)
if purchase&.successful?
@preorder.mark_charge_successful!
return render json: { success: true, next: @preorder.link.long_url }
end
render json: { success: false, error_message: PurchaseErrorCode.customer_error_message(card_data_handling_error&.error_message) }
end
def update_subscription
# TODO (helen): Remove after debugging https://gumroad.slack.com/archives/C01DBV0A257/p1662042866645759
Rails.logger.info("purchases#update_subscription - id: #{@subscription.external_id} ; params: #{permitted_subscription_params}")
result =
Subscription::UpdaterService.new(subscription: @subscription,
gumroad_guid: cookies[:_gumroad_guid],
params: permitted_subscription_params,
logged_in_user:,
remote_ip: request.remote_ip).perform
render json: result
end
def search
authorize [:audience, Purchase], :index?
per_page = SEARCH_RESULTS_PER_PAGE
page = (params[:page] || 1).to_i
offset = (page - 1) * per_page
query = params[:query].to_s.strip
search_options = {
seller: current_seller,
seller_query: query,
state: Purchase::ALL_SUCCESS_STATES,
exclude_non_original_subscription_purchases: true,
exclude_commission_completion_purchases: true,
from: (page - 1) * per_page,
size: per_page,
sort: [:_score, { created_at: :desc }, { id: :desc }]
}
purchases_records = PurchaseSearchService.search(search_options).records.load
imported_customers_records = current_seller.imported_customers.alive.
where("email LIKE ?", "%#{query}%").
order(id: :desc).limit(per_page).offset(offset).
load
result = purchases_records + imported_customers_records
can_ping = current_seller.urls_for_ping_notification(ResourceSubscription::SALE_RESOURCE_NAME).size > 0
render json: result.as_json(include_receipt_url: true, include_ping: { value: can_ping }, version: 2, include_variant_details: true, query:, pundit_user:)
end
def update
authorize [:audience, @purchase]
@purchase.email = params[:email].strip if params[:email].present?
@purchase.full_name = params[:full_name] if params[:full_name].present?
@purchase.street_address = params[:street_address] if params[:street_address].present?
@purchase.city = params[:city] if params[:city].present?
@purchase.state = params[:state] if params[:state].present?
@purchase.zip_code = params[:zip_code] if params[:zip_code].present?
@purchase.country = Compliance::Countries.find_by_name(params[:country])&.common_name if params[:country].present?
@purchase.quantity = params[:quantity] if @purchase.is_multiseat_license? && params[:quantity].to_i > 0
@purchase.save
if params[:email].present? && @purchase.is_bundle_purchase?
@purchase.product_purchases.each { _1.update!(email: params[:email]) }
end
if params[:giftee_email] && @purchase.gift
giftee_purchase = @purchase.gift.giftee_purchase
gift = @purchase.gift
gift.giftee_email = params[:giftee_email]
gift.save!
giftee_purchase.email = params[:giftee_email]
giftee_purchase.save!
giftee_purchase.resend_receipt
end
if @purchase.errors.empty?
render json: { success: true, purchase: @purchase.as_json(pundit_user:) }
else
render json: { success: false }
end
end
def refund
authorize [:audience, Purchase]
process_refund(seller: current_seller, user: logged_in_user, purchase_external_id: params[:id], amount: params[:amount], impersonating: impersonating?)
end
def revoke_access
authorize [:audience, @purchase]
@purchase.update!(is_access_revoked: true)
head :no_content
end
def undo_revoke_access
authorize [:audience, @purchase]
@purchase.update!(is_access_revoked: false)
head :no_content
end
def resend_receipt
@purchase.resend_receipt
head :no_content
end
def confirm_generate_invoice
@react_component_props = { invoice_url: generate_invoice_by_buyer_path(params[:id]) }
end
def generate_invoice
chargeable = Charge::Chargeable.find_by_purchase_or_charge!(purchase: @purchase)
@invoice_presenter = InvoicePresenter.new(chargeable)
@title = "Generate invoice"
end
def send_invoice
@chargeable = Charge::Chargeable.find_by_purchase_or_charge!(purchase: @purchase)
address_fields = {
full_name: params["full_name"],
street_address: params["street_address"],
city: params["city"],
state: params["state"],
zip_code: params["zip_code"],
country: ISO3166::Country[params["country_code"]]&.common_name
}
additional_notes = params[:additional_notes]&.strip
raw_vat_id = params["vat_id"].present? ? params["vat_id"] : nil
if raw_vat_id
if @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::AUS.alpha2
business_vat_id = AbnValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::SGP.alpha2
business_vat_id = GstValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::CAN.alpha2 &&
@chargeable.purchase_sales_tax_info.state_code == QUEBEC
business_vat_id = QstValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::NOR.alpha2
business_vat_id = MvaValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::BHR.alpha2
business_vat_id = TrnValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::KEN.alpha2
business_vat_id = KraPinValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::NGA.alpha2
business_vat_id = FirsTinValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::TZA.alpha2
business_vat_id = TraTinValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
@chargeable.purchase_sales_tax_info.country_code == Compliance::Countries::OMN.alpha2
business_vat_id = OmanVatNumberValidationService.new(raw_vat_id).process ? raw_vat_id : nil
elsif @chargeable.purchase_sales_tax_info.present? &&
(Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_ALL_PRODUCTS.include?(@chargeable.purchase_sales_tax_info.country_code) ||
Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS_WITH_TAX_ID_PRO_VALIDATION.include?(@chargeable.purchase_sales_tax_info.country_code))
business_vat_id = TaxIdValidationService.new(raw_vat_id, @chargeable.purchase_sales_tax_info.country_code).process ? raw_vat_id : nil
else
business_vat_id = VatValidationService.new(raw_vat_id).process ? raw_vat_id : nil
end
end
invoice_presenter = InvoicePresenter.new(@chargeable, address_fields:, additional_notes:, business_vat_id:)
begin
@chargeable.refund_gumroad_taxes!(refunding_user_id: logged_in_user&.id, note: address_fields.to_json, business_vat_id:) if business_vat_id
invoice_html = render_to_string(locals: { invoice_presenter: }, formats: [:pdf], layout: false)
pdf = PDFKit.new(invoice_html, page_size: "Letter").to_pdf
s3_obj = @chargeable.upload_invoice_pdf(pdf)
message = +"The invoice will be downloaded automatically."
if business_vat_id
notice =
if @chargeable.purchase_sales_tax_info.present? &&
(Compliance::Countries::GST_APPLICABLE_COUNTRY_CODES.include?(@chargeable.purchase_sales_tax_info.country_code) ||
Compliance::Countries::IND.alpha2 == @chargeable.purchase_sales_tax_info.country_code)
"GST has also been refunded."
elsif @chargeable.purchase_sales_tax_info.present? &&
Compliance::Countries::CAN.alpha2 == @chargeable.purchase_sales_tax_info.country_code
"QST has also been refunded."
elsif @chargeable.purchase_sales_tax_info.present? &&
Compliance::Countries::MYS.alpha2 == @chargeable.purchase_sales_tax_info.country_code
"Service tax has also been refunded."
elsif @chargeable.purchase_sales_tax_info.present? &&
Compliance::Countries::JPN.alpha2 == @chargeable.purchase_sales_tax_info.country_code
"CT has also been refunded."
else
"VAT has also been refunded."
end
message << " " << notice
end
file_url = s3_obj.presigned_url(:get, expires_in: SignedUrlHelper::SIGNED_S3_URL_VALID_FOR_MAXIMUM.to_i)
render json: { success: true, message:, file_location: file_url }
rescue StandardError => e
Rails.logger.error("Chargeable #{@chargeable.class.name} (#{@chargeable.external_id}) invoice generation failed due to: #{e.inspect}")
Rails.logger.error(e.message)
Rails.logger.error(e.backtrace.join("\n"))
render json: { success: false, message: "Sorry, something went wrong." }
end
end
def change_can_contact
authorize [:audience, @purchase]
@purchase.can_contact = ActiveModel::Type::Boolean.new.cast(params[:can_contact])
@purchase.save!
head :no_content
end
def cancel_preorder_by_seller
authorize [:audience, @purchase]
if @purchase.preorder.mark_cancelled
render json: { success: true }
else
render json: { success: false }
end
end
def confirm_receipt_email
@title = "Confirm Email"
@hide_layouts = true
end
def receipt
if (@purchase.purchaser && @purchase.purchaser == logged_in_user) ||
(logged_in_user && logged_in_user.is_team_member?) ||
(params[:email].present? && ActiveSupport::SecurityUtils.secure_compare(@purchase.email.downcase, params[:email].to_s.strip.downcase))
message = CustomerMailer.receipt(@purchase.id, for_email: false)
# Generate the same markup used in the email
Premailer::Rails::Hook.perform(message)
render html: message.html_part.body.raw_source.html_safe, layout: false
else
if params[:email].present?
flash[:alert] = "Wrong email. Please try again."
end
redirect_to confirm_receipt_email_purchase_path(@purchase.external_id)
end
end
def export
authorize [:audience, Purchase], :index?
tempfile = Exports::PurchaseExportService.export(
seller: current_seller,
recipient: impersonating_user || logged_in_user,
filters: params.slice(:start_time, :end_time, :product_ids, :variant_ids),
)
if tempfile
send_file tempfile.path
else
redirect_to customers_path, notice: "You will receive an email in your inbox with the data you've requested shortly.", status: :see_other
end
end
protected
def verify_current_seller_is_seller_for_purchase
e404_json if @purchase.nil? || @purchase.seller != current_seller
end
def validate_purchase_request
# Don't allow the purchase to go through if the buyer is a bot. Pretend that the purchase succeeded instead.
return render json: { success: true } if is_bot?
# Don't allow the purchase to go through if cookies are disabled and it's a paid purchase
contains_paid_purchase = if params[:line_items].present?
params[:line_items].any? { |product_params| product_params[:perceived_price_cents] != "0" }
else
params[:perceived_price_cents] != "0"
end
browser_guid = cookies[:_gumroad_guid]
return render_error("Cookies are not enabled on your browser. Please enable cookies and refresh this page before continuing.") if contains_paid_purchase && browser_guid.blank?
# Verify reCAPTCHA response
unless skip_recaptcha?
render_error("Sorry, we could not verify the CAPTCHA. Please try again.") unless valid_recaptcha_response_and_hostname?(site_key: GlobalConfig.get("RECAPTCHA_MONEY_SITE_KEY"))
end
end
def render_create_success(purchase)
render json: purchase.purchase_response
end
def render_error(error_message, purchase: nil)
render json: error_response(error_message, purchase:)
end
def handle_recommended_purchase(purchase)
return unless purchase.successful? || purchase.preorder_authorization_successful? || purchase.is_free_trial_purchase?
if RecommendationType.is_product_recommendation?(purchase.recommended_by)
recommendation_type = RecommendationType::PRODUCT_RECOMMENDATION
recommended_by_link = Link.find_by(unique_permalink: purchase.recommended_by)
else
recommendation_type = purchase.recommended_by
recommended_by_link = nil
end
purchase_info_params = {
purchase:,
recommended_link: purchase.link,
recommended_by_link:,
recommendation_type:,
recommender_model_name: purchase.recommender_model_name,
}
if purchase.was_discover_fee_charged?
purchase_info_params[:discover_fee_per_thousand] = purchase.link.discover_fee_per_thousand
end
RecommendedPurchaseInfo.create!(purchase_info_params)
end
def permitted_subscription_params
params.except("g-recaptcha-response").permit(:id, :price_id, :card_data_handling_mode, :card_country, :card_country_source,
:stripe_payment_method_id, :stripe_customer_id, :stripe_setup_intent_id, :paymentToken, :billing_agreement_id, :visual,
:braintree_device_data, :braintree_transient_customer_store_key, :use_existing_card,
:price_range, :perceived_price_cents, :perceived_upgrade_price_cents, :quantity,
:declined, stripe_error: {}, variants: [], contact_info: [:email, :full_name,
:street_address, :city, :state, :zip_code, :country]).to_h
end
def hide_layouts
@body_id = "app"
@on_purchases_page = @hide_layouts = true
end
def authenticate_subscription!
@subscription = Subscription.find_by_external_id!(params[:id])
e404 unless cookies.encrypted[@subscription.cookie_key] == @subscription.external_id
end
def authenticate_preorder!
@preorder = Preorder.find_by_external_id(params[:id])
e404 if @preorder.blank?
end
def check_for_successful_purchase_for_vat_refund
return if params["vat_id"].blank? || @purchase.successful?
render json: { success: false, message: "Your purchase has not been completed by PayPal yet. Please try again soon." }
end
def skip_recaptcha?
site_key = GlobalConfig.get("RECAPTCHA_MONEY_SITE_KEY")
return true if (Rails.env.development? || Rails.env.test?) && site_key.blank?
return true if action_name == "update_subscription" && params[:perceived_upgrade_price_cents].to_s == "0"
return true if action_name.in?(["update_subscription", "charge_preorder"]) && params[:use_existing_card]
return true if valid_wallet_payment?
false
end
def valid_wallet_payment?
return false if [params[:wallet_type], params[:stripe_payment_method_id]].any?(&:blank?)
payment_method = Stripe::PaymentMethod.retrieve(
params[:stripe_payment_method_id]
)
payment_method&.card&.wallet&.type == params[:wallet_type]
rescue Stripe::StripeError
render_error("Sorry, something went wrong.")
end
def require_email_confirmation
return if ActiveSupport::SecurityUtils.secure_compare(@purchase.email, params[:email].to_s)
if params[:email].blank?
flash[:warning] = "Please enter the purchase's email address to generate the invoice."
else
flash[:alert] = "Incorrect email address. Please try again."
end
redirect_to confirm_generate_invoice_path(@purchase.external_id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/affiliate_redirect_controller.rb | app/controllers/affiliate_redirect_controller.rb | # frozen_string_literal: true
class AffiliateRedirectController < ApplicationController
include AffiliateCookie
def set_cookie_and_redirect
affiliate = Affiliate.find_by_external_id_numeric(params[:affiliate_id].to_i)
if affiliate.nil?
Rails.logger.info("No affiliate found for id #{params[:affiliate_id]}")
return e404
end
create_affiliate_id_cookie(affiliate)
redirect_to redirect_url(affiliate), allow_other_host: true
end
private
def redirect_url(affiliate)
product = Link.find_by(unique_permalink: params[:unique_permalink]) if params[:unique_permalink].present?
final_destination_url = affiliate.final_destination_url(product:)
uri = Addressable::URI.parse(final_destination_url)
request_uri = Addressable::URI.parse(request.url)
query_values = uri.query_values || {}
query_values.merge!(request_uri.query_values || {})
query_values["affiliate_id"] = params[:affiliate_id] if affiliate.destination_url.present?
uri.query_values = query_values unless query_values.empty?
uri.to_s
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/reviews_controller.rb | app/controllers/reviews_controller.rb | # frozen_string_literal: true
class ReviewsController < ApplicationController
layout "inertia"
before_action :authenticate_user!
after_action :verify_authorized
def index
authorize ProductReview
presenter = ReviewsPresenter.new(current_seller)
render inertia: "Reviews/Index", props: presenter.reviews_props.merge(
following_wishlists_enabled: Feature.active?(:follow_wishlists, current_seller)
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/dashboard_controller.rb | app/controllers/dashboard_controller.rb | # frozen_string_literal: true
class DashboardController < Sellers::BaseController
include ActionView::Helpers::NumberHelper, CurrencyHelper
skip_before_action :check_suspended
before_action :check_payment_details, only: :index
layout "inertia", only: :index
def index
authorize :dashboard
if current_seller.suspended_for_tos_violation?
redirect_to products_url
else
LargeSeller.create_if_warranted(current_seller)
presenter = CreatorHomePresenter.new(pundit_user)
render inertia: "Dashboard/Index",
props: { creator_home: presenter.creator_home_props }
end
end
def customers_count
authorize :dashboard
count = current_seller.all_sales_count
render json: { success: true, value: number_with_delimiter(count) }
end
def total_revenue
authorize :dashboard
revenue = current_seller.gross_sales_cents_total_as_seller
render json: { success: true, value: formatted_dollar_amount(revenue) }
end
def active_members_count
authorize :dashboard
count = current_seller.active_members_count
render json: { success: true, value: number_with_delimiter(count) }
end
def monthly_recurring_revenue
authorize :dashboard
revenue = current_seller.monthly_recurring_revenue
render json: { success: true, value: formatted_dollar_amount(revenue) }
end
def download_tax_form
authorize :dashboard
year = Time.current.year - 1
tax_form_download_url = current_seller.tax_form_1099_download_url(year:)
return redirect_to tax_form_download_url, allow_other_host: true if tax_form_download_url.present?
flash[:alert] = "A 1099 form for #{year} was not filed for your account."
redirect_to dashboard_path
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/product_review_responses_controller.rb | app/controllers/product_review_responses_controller.rb | # frozen_string_literal: true
class ProductReviewResponsesController < ApplicationController
before_action :authenticate_user!
before_action :set_purchase
before_action :set_product_review!
before_action :set_or_build_review_response
after_action :verify_authorized
def update
authorize @review_response
if @review_response.update(update_params.merge(user: logged_in_user))
head :no_content
else
render json: { error: @review_response.errors.full_messages.to_sentence },
status: :unprocessable_entity
end
end
def destroy
authorize @review_response
if @review_response.destroy
head :no_content
else
render json: { error: @review_response.errors.full_messages.to_sentence },
status: :unprocessable_entity
end
end
private
def set_product_review!
@product_review = @purchase.original_product_review
e404_json if @product_review.blank?
end
def set_or_build_review_response
@review_response = @product_review.response || @product_review.build_response
end
def update_params
params.permit(:message)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/consumption_analytics_controller.rb | app/controllers/consumption_analytics_controller.rb | # frozen_string_literal: true
class ConsumptionAnalyticsController < ApplicationController
include CreateConsumptionEvent
skip_before_action :check_suspended
def create
render json: { success: create_consumption_event!(params) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/library_controller.rb | app/controllers/library_controller.rb | # frozen_string_literal: true
class LibraryController < Sellers::BaseController
layout "inertia"
skip_before_action :check_suspended
before_action :check_user_confirmed, only: [:index]
before_action :set_purchase, only: [:archive, :unarchive, :delete]
RESEND_CONFIRMATION_EMAIL_TIME_LIMIT = 24.hours
private_constant :RESEND_CONFIRMATION_EMAIL_TIME_LIMIT
def index
authorize Purchase
@title = "Library"
purchase_results, creator_counts, bundles = LibraryPresenter.new(logged_in_user).library_cards
render inertia: "Library/Index", props: {
results: purchase_results,
creators: creator_counts,
bundles:,
reviews_page_enabled: Feature.active?(:reviews_page, current_seller),
following_wishlists_enabled: Feature.active?(:follow_wishlists, current_seller),
}
end
def archive
authorize @purchase
@purchase.update!(is_archived: true)
redirect_to library_path, notice: "Product archived!", status: :see_other
end
def unarchive
authorize @purchase
@purchase.update!(is_archived: false)
redirect_to library_path, notice: "Product unarchived!", status: :see_other
end
def delete
authorize @purchase
@purchase.update!(is_deleted_by_buyer: true)
redirect_to library_path, notice: "Product deleted!", status: :see_other
end
private
def set_purchase
@purchase = logged_in_user.purchases.find_by_external_id!(params[:id])
end
def check_user_confirmed
return if logged_in_user.confirmed?
if logged_in_user.confirmation_sent_at.blank? || logged_in_user.confirmation_sent_at < RESEND_CONFIRMATION_EMAIL_TIME_LIMIT.ago
logged_in_user.send_confirmation_instructions
end
flash[:warning] = "Please check your email to confirm your address before you can see that."
if Feature.active?(:custom_domain_download)
redirect_to settings_main_url(host: DOMAIN), allow_other_host: true
else
redirect_to settings_main_path
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/discover_controller.rb | app/controllers/discover_controller.rb | # frozen_string_literal: true
class DiscoverController < ApplicationController
RECOMMENDED_PRODUCTS_COUNT = 8
INITIAL_PRODUCTS_COUNT = 36
include ActionView::Helpers::NumberHelper, RecommendationType, CreateDiscoverSearch,
DiscoverCuratedProducts, SearchProducts, AffiliateCookie
before_action :set_affiliate_cookie, only: [:index]
def index
format_search_params!
@hide_layouts = true
@card_data_handling_mode = CardDataHandlingMode.get_card_data_handling_mode(logged_in_user)
if params[:sort].blank? && curated_products.present?
params[:sort] = ProductSortKey::CURATED
params[:curated_product_ids] = (curated_products[RECOMMENDED_PRODUCTS_COUNT..] || []).map { _1.product.id }
end
if !show_curated_products? && params.except(:controller, :action, :format, :taxonomy).blank?
params[:from] = RECOMMENDED_PRODUCTS_COUNT + 1
end
if taxonomy
params[:taxonomy_id] = taxonomy.id
params[:include_taxonomy_descendants] = true
end
params[:include_rated_as_adult] = logged_in_user&.show_nsfw_products?
params[:size] = INITIAL_PRODUCTS_COUNT
@search_results = search_products(params)
@search_results[:products] = @search_results[:products].includes(ProductPresenter::ASSOCIATIONS_FOR_CARD).map do |product|
ProductPresenter.card_for_web(
product:,
request:,
recommended_by: RecommendationType::GUMROAD_SEARCH_RECOMMENDATION,
target: Product::Layout::DISCOVER,
compute_description: false,
query: params[:query],
offer_code: params[:offer_code]
)
end
create_discover_search!(query: params[:query], taxonomy: @taxonomy) if is_searching?
prepare_discover_page
@react_discover_props = {
search_results: @search_results,
currency_code: logged_in_user&.currency_type || "usd",
taxonomies_for_nav:,
recommended_products: recommendations,
curated_product_ids: curated_products.map { _1.product.external_id },
search_offset: params[:from] || 0,
show_black_friday_hero: black_friday_feature_active?,
is_black_friday_page: params[:offer_code] == SearchProducts::BLACK_FRIDAY_CODE,
black_friday_offer_code: SearchProducts::BLACK_FRIDAY_CODE,
black_friday_stats: black_friday_feature_active? ? BlackFridayStatsService.fetch_stats : nil,
}
end
def recommended_products
render json: recommendations
end
private
def recommendations
# Don't show any recommended/featured products when offer codes are present
return [] if params[:offer_code].present?
if show_curated_products?
curated_products.take(RECOMMENDED_PRODUCTS_COUNT).map do |product_info|
ProductPresenter.card_for_web(
product: product_info.product,
request:,
recommended_by: product_info.recommended_by,
target: product_info.target,
recommender_model_name: product_info.recommender_model_name,
affiliate_id: product_info.affiliate_id,
)
end
else
products = if taxonomy.present?
search_params = { size: RECOMMENDED_PRODUCTS_COUNT, taxonomy_id: taxonomy.id, include_taxonomy_descendants: true }
search_products(search_params)[:products].includes(ProductPresenter::ASSOCIATIONS_FOR_CARD)
else
all_top_products = Rails.cache.fetch("discover_all_top_products", expires_in: 1.day) do
products = []
Taxonomy.roots.each do |top_taxonomy|
search_params = { size: RECOMMENDED_PRODUCTS_COUNT, taxonomy_id: top_taxonomy.id, include_taxonomy_descendants: true }
top_products = search_products(search_params)[:products].includes(ProductPresenter::ASSOCIATIONS_FOR_CARD)
products.concat(top_products)
end
products
end
all_top_products.sample(RECOMMENDED_PRODUCTS_COUNT)
end
products.map do |product|
ProductPresenter.card_for_web(
product:,
request:,
recommended_by: RecommendationType::GUMROAD_DISCOVER_RECOMMENDATION,
target: Product::Layout::DISCOVER
)
end
end
end
def show_curated_products?
return false if params[:offer_code].present?
!taxonomy && curated_products.any?
end
def is_searching?
params.values_at(:query, :tags, :category, :offer_code).any?(&:present?) ||
(params[:taxonomy].present? && params.values_at(:sort, :min_price, :max_price, :rating, :filetypes).any?(&:present?))
end
def taxonomy
@taxonomy ||= Taxonomy.find_by_path(params[:taxonomy].split("/")) if params[:taxonomy].present?
end
def prepare_discover_page
@on_discover_page = true
@body_id = "discover-page"
@canonical_url = Discover::CanonicalUrlPresenter.canonical_url(params)
if !params[:taxonomy].present? && !params[:query].present? && params[:tags].present?
presenter = Discover::TagPageMetaPresenter.new(params[:tags], @search_results[:total])
@title = "#{presenter.title} | Gumroad"
@discover_tag_meta_description = presenter.meta_description
end
end
def black_friday_feature_active?
Feature.active?(:offer_codes_search) || (params[:feature_key].present? && ActiveSupport::SecurityUtils.secure_compare(params[:feature_key].to_s, ENV["SECRET_FEATURE_KEY"].to_s))
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/customers_controller.rb | app/controllers/customers_controller.rb | # frozen_string_literal: true
class CustomersController < Sellers::BaseController
include CurrencyHelper
before_action :authorize
before_action :set_on_page_type
CUSTOMERS_PER_PAGE = 20
layout "inertia", only: [:index]
def index
product = Link.fetch(params[:link_id]) if params[:link_id].present?
sales = fetch_sales(products: [product].compact)
customers_presenter = CustomersPresenter.new(
pundit_user:,
product:,
customers: load_sales(sales),
pagination: { page: 1, pages: (sales.results.total / CUSTOMERS_PER_PAGE.to_f).ceil, next: nil },
count: sales.results.total
)
create_user_event("customers_view")
render inertia: "Customers/Index",
props: { customers_presenter: customers_presenter.customers_props }
end
def paged
params[:page] = params[:page].to_i - 1
sales = fetch_sales(
query: params[:query],
sort: params[:sort] ? { params[:sort][:key] => { order: params[:sort][:direction] } } : nil,
products: Link.by_external_ids(params[:products]),
variants: BaseVariant.by_external_ids(params[:variants]),
excluded_products: Link.by_external_ids(params[:excluded_products]),
excluded_variants: BaseVariant.by_external_ids(params[:excluded_variants]),
minimum_amount_cents: params[:minimum_amount_cents],
maximum_amount_cents: params[:maximum_amount_cents],
created_after: params[:created_after],
created_before: params[:created_before],
country: params[:country],
active_customers_only: ActiveModel::Type::Boolean.new.cast(params[:active_customers_only]),
)
customers_presenter = CustomersPresenter.new(
pundit_user:,
customers: load_sales(sales),
pagination: { page: params[:page].to_i + 1, pages: (sales.results.total / CUSTOMERS_PER_PAGE.to_f).ceil, next: nil },
count: sales.results.total
)
render json: customers_presenter.customers_props
end
def customer_charges
purchase = Purchase.where(email: params[:purchase_email].to_s).find_by_external_id!(params[:purchase_id])
if purchase.is_original_subscription_purchase?
return render json: purchase.subscription.purchases.successful.map { CustomerPresenter.new(purchase: _1).charge }
elsif purchase.is_commission_deposit_purchase?
return render json: [purchase, purchase.commission.completion_purchase].compact.map { CustomerPresenter.new(purchase: _1).charge }
end
render json: []
end
def customer_emails
original_purchase = current_seller.sales.find_by_external_id!(params[:purchase_id]) if params[:purchase_id].present?
all_purchases = if original_purchase.subscription.present?
original_purchase.subscription.purchases.all_success_states_except_preorder_auth_and_gift.preload(:receipt_email_info_from_purchase)
else
[original_purchase]
end
receipts = all_purchases.map do |purchase|
receipt_email_info = purchase.receipt_email_info
{
type: "receipt",
name: receipt_email_info&.email_name&.humanize || "Receipt",
id: purchase.external_id,
state: receipt_email_info&.state&.humanize || "Delivered",
state_at: receipt_email_info.present? ? receipt_email_info.most_recent_state_at.in_time_zone(current_seller.timezone) : purchase.created_at.in_time_zone(current_seller.timezone),
url: receipt_purchase_url(purchase.external_id, email: purchase.email),
date: purchase.created_at
}
end
posts = original_purchase.installments.alive.where(seller_id: original_purchase.seller_id).map do |post|
email_info = CreatorContactingCustomersEmailInfo.where(purchase: original_purchase, installment: post).last
{
type: "post",
name: post.name,
id: post.external_id,
state: email_info.state.humanize,
state_at: email_info.most_recent_state_at.in_time_zone(current_seller.timezone),
date: post.published_at
}
end
unpublished_posts = posts.select { |post| post[:date].nil? }
published_posts = posts - unpublished_posts
emails = published_posts
emails = emails.sort_by { |e| -e[:date].to_i } + unpublished_posts
emails = receipts + emails unless original_purchase.is_bundle_product_purchase?
render json: emails
end
def missed_posts
purchase = Purchase.where(email: params[:purchase_email].to_s).find_by_external_id!(params[:purchase_id])
render json: CustomerPresenter.new(purchase:).missed_posts
end
def product_purchases
purchase = current_seller.sales.find_by_external_id!(params[:purchase_id]) if params[:purchase_id].present?
render json: purchase.product_purchases.map { CustomerPresenter.new(purchase: _1).customer(pundit_user:) }
end
private
def fetch_sales(query: nil, sort: nil, products: nil, variants: nil, excluded_products: nil, excluded_variants: nil, minimum_amount_cents: nil, maximum_amount_cents: nil, created_after: nil, created_before: nil, country: nil, active_customers_only: false)
search_options = {
seller: current_seller,
country: Compliance::Countries.historical_names(country || params[:bought_from]).presence,
state: Purchase::NON_GIFT_SUCCESS_STATES,
any_products_or_variants: {},
exclude_purchasers_of_product: excluded_products,
exclude_purchasers_of_variant: excluded_variants,
exclude_non_original_subscription_purchases: true,
exclude_giftees: true,
exclude_bundle_product_purchases: true,
exclude_commission_completion_purchases: true,
from: params[:page].to_i * CUSTOMERS_PER_PAGE,
size: CUSTOMERS_PER_PAGE,
sort: [{ created_at: { order: :desc } }, { id: { order: :desc } }],
track_total_hits: true,
seller_query: query || params[:query],
}
search_options[:sort].unshift(sort) if sort.present?
search_options[:any_products_or_variants][:products] = products if products.present?
search_options[:any_products_or_variants][:variants] = variants if variants.present?
if active_customers_only
search_options[:exclude_deactivated_subscriptions] = true
search_options[:exclude_refunded_except_subscriptions] = true
search_options[:exclude_unreversed_chargedback] = true
end
search_options[:price_greater_than] = get_usd_cents(current_seller.currency_type, minimum_amount_cents) if minimum_amount_cents.present?
search_options[:price_less_than] = get_usd_cents(current_seller.currency_type, maximum_amount_cents) if maximum_amount_cents.present?
if created_after || created_before
timezone = ActiveSupport::TimeZone[current_seller.timezone]
search_options[:created_on_or_after] = timezone.parse(created_after) if created_after
search_options[:created_before] = timezone.parse(created_before).tomorrow if created_before
if search_options[:created_on_or_after] && search_options[:created_before] && search_options[:created_on_or_after] > search_options[:created_before]
search_options.except!(:created_before, :created_on_or_after)
end
end
PurchaseSearchService.search(search_options)
end
def load_sales(sales)
sales.records
.includes(
:call,
:purchase_offer_code_discount,
:tip,
:upsell_purchase,
:variant_attributes,
:url_redirect,
:link,
product_review: [:response, { alive_videos: [:video_file] }],
utm_link: [target_resource: [:seller, :user]]
)
.in_order_of(:id, sales.records.ids)
.load
end
def set_title
@title = "Sales"
end
def set_on_page_type
@on_customers_page = true
end
def authorize
super([:audience, Purchase], :index?)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/followers_controller.rb | app/controllers/followers_controller.rb | # frozen_string_literal: true
class FollowersController < ApplicationController
layout "inertia"
include CustomDomainConfig
PUBLIC_ACTIONS = %i[new create from_embed_form confirm cancel].freeze
before_action :authenticate_user!, except: PUBLIC_ACTIONS
after_action :verify_authorized, except: PUBLIC_ACTIONS
before_action :fetch_follower, only: %i[confirm cancel destroy]
before_action :set_user_and_custom_domain_config, only: :new
FOLLOWERS_PER_PAGE = 20
def index
authorize [:audience, Follower]
create_user_event("followers_view")
@on_posts_page = true
@title = "Subscribers"
followers = current_seller.followers.active
paginated_followers = followers
.order(confirmed_at: :desc, id: :desc)
.limit(FOLLOWERS_PER_PAGE)
.as_json(pundit_user:)
render inertia: "Followers/Index", props: {
followers: paginated_followers,
per_page: FOLLOWERS_PER_PAGE,
total: followers.count,
}
end
def search
authorize [:audience, Follower], :index?
email = params[:email].to_s.strip
page = params[:page].to_i > 0 ? params[:page].to_i : 1
searched_followers = current_seller.followers.active
.order(confirmed_at: :desc, id: :desc)
searched_followers = searched_followers.where("email LIKE ?", "%#{email}%") if email.present?
search_followers_total_count = searched_followers.count
searched_followers = searched_followers
.limit(FOLLOWERS_PER_PAGE)
.offset((page - 1) * FOLLOWERS_PER_PAGE)
render json: { paged_followers: searched_followers.as_json(pundit_user:), total_count: search_followers_total_count }
end
def create
follower = create_follower(params)
return render json: { success: false, message: "Sorry, something went wrong." } if follower.nil?
return render json: { success: false, message: follower.errors.full_messages.to_sentence } if follower.errors.present?
if follower.confirmed?
render json: { success: true, message: "You are now following #{follower.user.name_or_username}!" }
else
render json: { success: true, message: "Check your inbox to confirm your follow request." }
end
end
def new
redirect_to @user.profile_url, allow_other_host: true
end
def from_embed_form
@follower = create_follower(params, source: Follower::From::EMBED_FORM)
@hide_layouts = true
return unless @follower.nil? || @follower.errors.present?
flash[:warning] = "Something went wrong. Please try to follow the creator again."
user = User.find_by_external_id(params[:seller_id])
e404 unless user.try(:username)
redirect_to user.profile_url, allow_other_host: true
end
def confirm
e404 unless @follower.user.account_active?
@follower.confirm!
# Redirect to the followed user's profile
redirect_to @follower.user.profile_url, notice: "Thanks for the follow!", allow_other_host: true
end
def destroy
authorize [:audience, @follower]
@follower.mark_deleted!
end
def cancel
follower_id = @follower.external_id
@follower.mark_deleted!
@hide_layouts = true
respond_to do |format|
format.html
format.json do
render json: {
success: true,
follower_id:
}
end
end
end
private
def create_follower(params, source: nil)
followed_user = User.find_by_external_id(params[:seller_id])
return if followed_user.nil?
follower_email = params[:email]
follower_user_id = User.find_by(email: follower_email)&.id
followed_user.add_follower(
follower_email,
follower_user_id:,
logged_in_user:,
source:
)
end
def fetch_follower
@follower = Follower.find_by_external_id(params[:id])
return if @follower
respond_to do |format|
format.html { e404 }
format.json { e404_json }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/affiliates_controller.rb | app/controllers/affiliates_controller.rb | # frozen_string_literal: true
class AffiliatesController < Sellers::BaseController
include Pagy::Backend
PUBLIC_ACTIONS = %i[subscribe_posts unsubscribe_posts].freeze
skip_before_action :authenticate_user!, only: PUBLIC_ACTIONS
after_action :verify_authorized, except: PUBLIC_ACTIONS
before_action :set_direct_affiliate, only: PUBLIC_ACTIONS
before_action :set_affiliate, only: %i[edit update destroy statistics]
before_action :set_title
before_action :hide_layouts, only: PUBLIC_ACTIONS
layout "inertia", only: [:index, :onboarding, :new, :edit, :create, :update]
def index
authorize DirectAffiliate
page = params[:page]&.to_i
query = params[:query]
sort_params = extract_sort_params
presenter = AffiliatesPresenter.new(
pundit_user,
page:,
query:,
sort: sort_params,
should_get_affiliate_requests: page.nil? || page == 1
)
affiliates_data = presenter.index_props
if affiliates_data[:affiliates].empty? && affiliates_data[:affiliate_requests].empty? && (page.nil? || page == 1) && query.blank?
return redirect_to onboarding_affiliates_path
end
render inertia: "Affiliates/Index", props: affiliates_data
end
def onboarding
authorize DirectAffiliate, :index?
presenter = AffiliatesPresenter.new(pundit_user)
render inertia: "Affiliates/Onboarding", props: presenter.onboarding_props
end
def new
authorize DirectAffiliate, :create?
presenter = AffiliatesPresenter.new(pundit_user)
render inertia: "Affiliates/New", props: presenter.new_affiliate_props
end
def edit
authorize @affiliate, :update?
presenter = AffiliatesPresenter.new(pundit_user)
render inertia: "Affiliates/Edit", props: presenter.edit_affiliate_props(@affiliate)
end
def subscribe_posts
return e404 if @direct_affiliate.nil?
@direct_affiliate.update_posts_subscription(send_posts: true)
end
def unsubscribe_posts
return e404 if @direct_affiliate.nil?
@direct_affiliate.update_posts_subscription(send_posts: false)
end
def statistics
authorize @affiliate
products = @affiliate.product_sales_info
total_volume_cents = products.values.sum { _1[:volume_cents] }
render json: { total_volume_cents:, products: }
end
def create
authorize DirectAffiliate, :create?
affiliate = DirectAffiliate.new
result = process_affiliate_params(affiliate)
if result[:success]
redirect_to affiliates_path, notice: "Affiliate created successfully", status: :see_other
else
redirect_to new_affiliate_path, inertia: { errors: { base: [result[:message]] } }
end
end
def update
authorize @affiliate, :update?
result = process_affiliate_params(@affiliate)
if result[:success]
redirect_to affiliates_path, notice: "Affiliate updated successfully", status: :see_other
else
redirect_to edit_affiliate_path(@affiliate), inertia: { errors: { base: [result[:message]] } }
end
end
def destroy
authorize @affiliate, :destroy?
@affiliate.mark_deleted!
AffiliateMailer.direct_affiliate_removal(@affiliate.id).deliver_later
redirect_to affiliates_path, notice: "Affiliate deleted successfully"
end
def export
authorize DirectAffiliate, :index?
result = Exports::AffiliateExportService.export(
seller: current_seller,
recipient: impersonating_user || current_seller,
)
if result
send_file result.tempfile.path, filename: result.filename
else
flash[:warning] = "You will receive an email with the data you've requested."
redirect_back(fallback_location: affiliates_path)
end
end
private
def set_title
@title = "Affiliates"
end
def affiliate_params
params.require(:affiliate).permit(:email, :destination_url, :fee_percent, :apply_to_all_products, products: [:id, :enabled, :fee_percent, :destination_url])
end
def process_affiliate_params(affiliate)
affiliate_email = affiliate_params[:email]
apply_to_all_products = affiliate_params[:apply_to_all_products]
has_invalid_fee = (apply_to_all_products && affiliate_params[:fee_percent].blank?) || (!apply_to_all_products && affiliate_params[:products].any? { _1[:enabled] && _1[:fee_percent].blank? })
return { success: false, message: "Invalid affiliate parameters" } if affiliate_email.blank? || has_invalid_fee
affiliate_user = User.alive.find_by(email: affiliate_email)
return { success: false, message: "The affiliate has not created a Gumroad account with this email address." } if affiliate_user.nil?
return { success: false, message: "You found you. Good job. You can't be your own affiliate though." } if affiliate_user == current_seller
return { success: false, message: "This user has disabled being added as an affiliate." } if affiliate_user.disable_affiliate_requests?
return { success: false, message: "Please enable at least one product." } if !apply_to_all_products && affiliate_params[:products].none? { _1[:enabled] }
affiliate_basis_points = affiliate_params[:fee_percent].to_i * 100
if apply_to_all_products
affiliates_presenter = AffiliatesPresenter.new(pundit_user)
destination_urls_by_product_id = affiliate_params[:products].select { _1[:enabled] }
.index_by { ObfuscateIds.decrypt_numeric(_1[:id].to_i) }
.transform_values { _1[:destination_url] }
enabled_affiliate_products = affiliates_presenter.self_service_affiliate_product_details.keys.map do
{
link_id: _1,
affiliate_basis_points:,
destination_url: destination_urls_by_product_id[_1]
}
end
else
enabled_affiliate_products = affiliate_params[:products].select { _1[:enabled] }.map do
{
link_id: current_seller.links.find_by_external_id_numeric(_1[:id].to_i).id,
affiliate_basis_points: _1[:fee_percent].to_i * 100,
destination_url: _1[:destination_url],
}
end
end
enabled_affiliate_product_ids = enabled_affiliate_products.map { _1[:link_id] }
is_editing_affiliate = affiliate.persisted?
existing_product_affiliates = affiliate&.product_affiliates.to_a
is_editing_products = is_editing_affiliate && existing_product_affiliates.map { _1.link_id }.sort != enabled_affiliate_product_ids.sort
existing_affiliates = current_seller.direct_affiliates.alive.joins(:products).where(affiliate_user_id: affiliate_user.id)
existing_affiliates = existing_affiliates.where.not(id: affiliate.id) if is_editing_affiliate
return { success: false, message: "This affiliate already exists." } if existing_affiliates.exists?
keep_product_affiliates = []
enabled_affiliate_products.each do |product|
affiliate_product = existing_product_affiliates.find { _1.link_id == product[:link_id] } || affiliate.product_affiliates.build(product)
if affiliate_product.persisted?
is_editing_products = true unless affiliate_product.affiliate_basis_points == product[:affiliate_basis_points]
affiliate.association(:product_affiliates).add_to_target(affiliate_product)
affiliate_product.assign_attributes(product)
end
keep_product_affiliates << affiliate_product
end
product_affiliates_to_remove = existing_product_affiliates - keep_product_affiliates
product_affiliates_to_remove.each(&:mark_for_destruction)
existing_affiliate = current_seller.direct_affiliates.where(affiliate_user_id: affiliate_user.id).alive.last
affiliate.affiliate_user = affiliate_user
affiliate.seller = current_seller
affiliate.destination_url = affiliate_params[:destination_url]
affiliate.affiliate_basis_points = affiliate_params[:fee_percent].present? ? affiliate_basis_points : enabled_affiliate_products.map { _1[:affiliate_basis_points] }.min
affiliate.apply_to_all_products = apply_to_all_products
affiliate.send_posts = if existing_affiliate
existing_affiliate.send_posts
else
true
end
affiliate.save
return { success: false, message: affiliate.errors.full_messages.first } if affiliate.errors.present?
if is_editing_products
AffiliateMailer.notify_direct_affiliate_of_updated_products(affiliate.id).deliver_later
end
unless is_editing_affiliate
affiliate.schedule_workflow_jobs
end
{ success: true }
end
def set_direct_affiliate
@direct_affiliate = DirectAffiliate.find_by_external_id(params[:id])
end
def set_affiliate
@affiliate = current_seller.direct_affiliates.find_by_external_id(params[:id])
e404 if @affiliate.nil?
end
def extract_sort_params
column = params[:column]
direction = params[:sort]
return nil unless %w[affiliate_user_name products fee_percent volume_cents].include?(column)
{ key: column, direction: direction == "desc" ? "desc" : "asc" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/checkout_controller.rb | app/controllers/checkout_controller.rb | # frozen_string_literal: true
class CheckoutController < ApplicationController
before_action :process_cart_id_param, only: %i[index]
def index
@hide_layouts = true
@on_checkout_page = true
@checkout_presenter = CheckoutPresenter.new(logged_in_user:, ip: request.remote_ip)
end
private
def process_cart_id_param
return if params[:cart_id].blank?
request_path_except_cart_id_param = "#{request.path}?#{request.query_parameters.except(:cart_id).merge(referrer: UrlService.discover_domain_with_protocol).to_query}"
# Always show their own cart to the logged-in user
return redirect_to(request_path_except_cart_id_param) if logged_in_user.present?
cart = Cart.includes(:user).alive.find_by_external_id(params[:cart_id])
return redirect_to(request_path_except_cart_id_param) if cart.nil?
# Prompt the user to log in if the cart matching the `cart_id` param is associated with a user
return redirect_to login_url(next: request_path_except_cart_id_param, email: cart.user.email), alert: "Please log in to complete checkout." if cart.user.present?
browser_guid = cookies[:_gumroad_guid]
if cart.browser_guid != browser_guid
# Merge the guest cart for the current `browser_guid` with the cart matching the `cart_id` param
MergeCartsService.new(
source_cart: Cart.fetch_by(user: nil, browser_guid:),
target_cart: cart,
browser_guid:
).process
end
redirect_to(request_path_except_cart_id_param)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/embedded_javascripts_controller.rb | app/controllers/embedded_javascripts_controller.rb | # frozen_string_literal: true
class EmbeddedJavascriptsController < ApplicationController
skip_before_action :verify_authenticity_token, only: %i[overlay embed]
def overlay
@script_path = Shakapacker.manifest.lookup!("overlay.js")
@global_stylesheet_path = Shakapacker.manifest.lookup!("design.css")
@stylesheet = "overlay.css"
render :index
end
def embed
@script_path = Shakapacker.manifest.lookup!("embed.js")
render :index
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/stripe_account_sessions_controller.rb | app/controllers/stripe_account_sessions_controller.rb | # frozen_string_literal: true
class StripeAccountSessionsController < Sellers::BaseController
before_action :authorize
def create
connected_account_id = current_seller.stripe_account&.charge_processor_merchant_id
if connected_account_id.blank?
return render json: { success: false, error_message: "User does not have a Stripe account" }
end
begin
session = Stripe::AccountSession.create(
{
account: connected_account_id,
components: {
notification_banner: {
enabled: true,
features: { external_account_collection: true }
}
}
}
)
render json: { success: true, client_secret: session.client_secret }
rescue => e
Bugsnag.notify("Failed to create stripe account session for user #{current_seller.id}: #{e.message}")
render json: { success: false, error_message: "Failed to create stripe account session" }
end
end
private
def authorize
super([:stripe_account_sessions, current_seller])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/users_controller.rb | app/controllers/users_controller.rb | # frozen_string_literal: true
class UsersController < ApplicationController
include ProductsHelper, SearchProducts, CustomDomainConfig, SocialShareUrlHelper, ActionView::Helpers::SanitizeHelper,
AffiliateCookie
before_action :authenticate_user!, except: %i[show coffee subscribe subscribe_preview email_unsubscribe add_purchase_to_library session_info current_user_data]
after_action :verify_authorized, only: %i[deactivate]
before_action :hide_layouts, only: %i[show coffee subscribe subscribe_preview unsubscribe_review_reminders subscribe_review_reminders]
before_action :set_as_modal, only: %i[show]
before_action :set_frontend_performance_sensitive, only: %i[show]
before_action :set_user_and_custom_domain_config, only: %i[show coffee subscribe subscribe_preview]
before_action :set_page_attributes, only: %i[show]
before_action :set_user_for_action, only: %i[email_unsubscribe]
before_action :check_if_needs_redirect, only: %i[show]
before_action :set_affiliate_cookie, only: %i[show]
USER_PERMITTED_ATTRS = [:username, :email, :bio, :password,
:password_confirmation, :remember_me, :name, :payment_address,
:currency_type, :country, :state,
:city, :zip_code, :street_address,
:facebook_access_token, :manage_pages, :verified,
:weekly_notification,
:twitter_oauth_token, :twitter_oauth_secret,
:notification_endpoint, :locale, :announcement_notification_enabled,
:google_analytics_id, :timezone, :user_risk_state,
:tos_violation_reason, :terms_accepted,
:buyer_signup, :support_email,
:background_opacity_percent, :should_paypal_payout_be_split,
:check_merchant_account_is_linked, :collect_eu_vat, :is_eu_vat_exclusive,
:facebook_pixel_id, :skip_free_sale_analytics,
:disable_third_party_analytics, :two_factor_authentication_enabled, :facebook_meta_tag,
:enable_verify_domain_third_party_services,
:enable_payment_email, :enable_payment_push_notification, :enable_free_downloads_email, :enable_free_downloads_push_notification,
:enable_recurring_subscription_charge_email, :enable_recurring_subscription_charge_push_notification,
:disable_comments_email, :disable_reviews_email]
def show
format_search_params!
respond_to do |format|
format.html do
@show_user_favicon = true
@is_on_user_profile_page = true
@profile_props = ProfilePresenter.new(pundit_user:, seller: @user).profile_props(seller_custom_domain_url:, request:)
@card_data_handling_mode = CardDataHandlingMode.get_card_data_handling_mode(@user)
@paypal_merchant_currency = @user.native_paypal_payment_enabled? ?
@user.merchant_account_currency(PaypalChargeProcessor.charge_processor_id) :
ChargeProcessor::DEFAULT_CURRENCY_CODE
end
format.json { render json: @user.as_json }
format.any { e404 }
end
end
def coffee
@show_user_favicon = true
@product = @user.products.visible_and_not_archived.find_by(native_type: Link::NATIVE_TYPE_COFFEE)
e404 if @product.nil?
@title = @product.name
@product_props = ProductPresenter.new(pundit_user:, product: @product, request:).product_props(seller_custom_domain_url:, recommended_by: params[:recommended_by])
end
def subscribe
@title = "Subscribe to #{@user.name.presence || @user.username}"
@profile_presenter = ProfilePresenter.new(
pundit_user:,
seller: @user
)
end
def subscribe_preview
@subscribe_preview_props = {
avatar_url: @user.resized_avatar_url(size: 240),
title: @user.name_or_username,
}
end
def current_user_data
if user_signed_in?
render json: { success: true, user: UserPresenter.new(user: pundit_user.seller).as_current_seller }
else
render json: { success: false }, status: :unauthorized
end
end
def session_info
render json: { success: true, is_signed_in: user_signed_in? }
end
def email_unsubscribe
@action = params[:action]
if params[:email_type] == "notify"
@user.enable_payment_email = false
flash[:notice] = "You have been unsubscribed from purchase notifications."
elsif params[:email_type] == "seller_update"
@user.weekly_notification = false
flash[:notice] = "You have been unsubscribed from weekly sales updates."
elsif params[:email_type] == "product_update"
@user.announcement_notification_enabled = false
flash[:notice] = "You have been unsubscribed from Gumroad announcements."
end
@user.save!
flash[:notice_style] = "success"
redirect_to root_path
end
def deactivate
authorize current_seller
if current_seller.deactivate!
sign_out
flash[:notice] = "Your account has been successfully deleted. Thank you for using Gumroad."
render json: { success: true }
else
render json: { success: false, message: "We could not delete your account. Please try again later." }
end
rescue User::UnpaidBalanceError => e
retry if current_seller.forfeit_unpaid_balance!(:account_closure)
render json: {
success: false,
message: "Cannot delete due to an unpaid balance of #{e.amount}."
}
end
def add_purchase_to_library
purchase = Purchase.find_by_external_id(params["user"]["purchase_id"])
if purchase.present? && ActiveSupport::SecurityUtils.secure_compare(purchase.email.to_s, params["user"]["purchase_email"].to_s)
if logged_in_user.present?
purchase.purchaser = logged_in_user
purchase.save
return render json: { success: true, redirect_location: library_path }
else
user = User.alive.find_by(email: purchase.email)
if user.present? && user.valid_password?(params["user"]["password"])
purchase.purchaser = user
purchase.save
sign_in_or_prepare_for_two_factor_auth(user)
# If the user doesn't require 2FA, they will be redirected to library_path by TwoFactorAuthenticationController
return render json: { success: true, redirect_location: two_factor_authentication_path(next: library_path) }
end
end
end
render json: { success: false }
end
def unsubscribe_review_reminders
logged_in_user.update!(opted_out_of_review_reminders: true)
end
def subscribe_review_reminders
logged_in_user.update!(opted_out_of_review_reminders: false)
end
private
def check_if_needs_redirect
if !@is_user_custom_domain && @user.subdomain_with_protocol.present?
redirect_to root_url(host: @user.subdomain_with_protocol, params: request.query_parameters),
status: :moved_permanently, allow_other_host: true
end
end
def set_page_attributes
@title ||= @user.name_or_username
@body_id = "user_page"
end
def set_user_for_action
@user = User.find_by_secure_external_id(params[:id], scope: "email_unsubscribe")
return if @user.present?
if user_signed_in? && logged_in_user.external_id == params[:id]
@user = logged_in_user
else
user = User.find_by_external_id(params[:id])
if user.present?
destination_url = user_unsubscribe_url(id: user.secure_external_id(scope: "email_unsubscribe", expires_at: 2.days.from_now), email_type: params[:email_type])
# Bundle confirmation_text and destination into a single encrypted payload
secure_payload = {
destination: destination_url,
confirmation_texts: [user.email],
created_at: Time.current.to_i
}
encrypted_payload = SecureEncryptService.encrypt(secure_payload.to_json)
message = "Please enter your email address to unsubscribe"
error_message = "Email address does not match"
field_name = "Email address"
redirect_to secure_url_redirect_path(
encrypted_payload: encrypted_payload,
message: message,
field_name: field_name,
error_message: error_message
)
return
end
end
e404 if @user.nil?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/events_controller.rb | app/controllers/events_controller.rb | # frozen_string_literal: true
class EventsController < ApplicationController
def create
create_user_event(params[:event_name])
render json: {
success: true
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/recommended_products_controller.rb | app/controllers/recommended_products_controller.rb | # frozen_string_literal: true
class RecommendedProductsController < ApplicationController
def index
product_infos = fetch_recommended_product_infos
results = product_infos.map do |product_info|
ProductPresenter.card_for_web(
product: product_info.product,
request:,
recommended_by: product_info.recommended_by,
target: product_info.target,
recommender_model_name: product_info.recommender_model_name,
affiliate_id: product_info.affiliate_id,
)
end
render json: results
end
private
def cart_product_ids
params.fetch(:cart_product_ids, []).map { ObfuscateIds.decrypt(_1) }
end
def limit
@_limit ||= params.require(:limit).to_i
end
def fetch_recommended_product_infos
args = {
purchaser: logged_in_user,
cart_product_ids:,
recommender_model_name: session[:recommender_model_name],
limit:,
recommendation_type: params[:recommendation_type],
}
RecommendedProducts::CheckoutService.fetch_for_cart(**args)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/profile_sections_controller.rb | app/controllers/profile_sections_controller.rb | # frozen_string_literal: true
class ProfileSectionsController < ApplicationController
before_action :authorize
def create
attributes = permitted_params
if attributes[:text].present? && attributes[:type] == "SellerProfileRichTextSection"
processed_content = process_text(attributes[:text][:content])
attributes[:text][:content] = processed_content
end
section = current_seller.seller_profile_sections.create(attributes)
return render json: { error: section.errors.full_messages.to_sentence }, status: :unprocessable_entity if section.errors.present?
render json: { id: section.external_id }
rescue ActiveRecord::SubclassNotFound
render json: { error: "Invalid section type" }, status: :unprocessable_entity
end
def update
section = current_seller.seller_profile_sections.find_by_external_id!(params[:id])
attributes = permitted_params
attributes.delete(:shown_posts)
if attributes[:text].present? && section.is_a?(SellerProfileRichTextSection)
processed_content = process_text(attributes[:text][:content], section.json_data["text"]["content"] || [])
attributes[:text][:content] = processed_content
end
unless section.update(attributes)
render json: { error: section.errors.full_messages.to_sentence }, status: :unprocessable_entity
end
end
def destroy
current_seller.seller_profile_sections.find_by_external_id!(params[:id]).destroy!
end
private
def process_text(content, old_content = [])
SaveContentUpsellsService.new(
seller: current_seller,
content:,
old_content:,
).from_rich_content
end
def authorize
super(section_policy)
end
def section_policy
[:profile_section]
end
def permitted_params
permitted_params = params.permit(policy(section_policy).public_send("permitted_attributes_for_#{action_name}"))
permitted_params[:shown_products]&.map! { ObfuscateIds.decrypt(_1) }
permitted_params[:shown_posts]&.map! { ObfuscateIds.decrypt(_1) }
permitted_params[:shown_wishlists]&.map! { ObfuscateIds.decrypt(_1) }
permitted_params[:product_id] = ObfuscateIds.decrypt(permitted_params[:product_id]) if permitted_params[:product_id].present?
permitted_params[:featured_product_id] = ObfuscateIds.decrypt(permitted_params[:featured_product_id]) if permitted_params[:featured_product_id].present?
permitted_params
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/connections_controller.rb | app/controllers/connections_controller.rb | # frozen_string_literal: true
class ConnectionsController < Sellers::BaseController
before_action :authorize
def unlink_twitter
User::SocialTwitter::TWITTER_PROPERTIES.each do |property|
current_seller.send("#{property}=", nil)
end
current_seller.save!
render json: { success: true }
rescue => e
render json: { success: false, error_message: e.message }
end
private
def authorize
super([:settings, :profile], :manage_social_connections?)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/orders_controller.rb | app/controllers/orders_controller.rb | # frozen_string_literal: true
class OrdersController < ApplicationController
include ValidateRecaptcha, Events, Order::ResponseHelpers
before_action :validate_order_request, only: :create
before_action :fetch_affiliates, only: :create
def create
order_params = permitted_order_params.merge!(
{
browser_guid: cookies[:_gumroad_guid],
session_id: session.id,
ip_address: request.remote_ip,
is_mobile: is_mobile?
}
).to_h
order, purchase_responses, offer_codes = Order::CreateService.new(
buyer: logged_in_user,
params: order_params
).perform
charge_responses = Order::ChargeService.new(order:, params: order_params).perform
if order.persisted? && order.purchases.successful.any? && UtmLinkVisit.where(browser_guid: order_params[:browser_guid]).any?
UtmLinkSaleAttributionJob.perform_async(order.id, order_params[:browser_guid])
end
purchase_responses.merge!(charge_responses)
order.purchases.each { create_purchase_event_and_recommendation_info(_1) }
order.send_charge_receipts unless purchase_responses.any? { |_k, v| v[:requires_card_action] || v[:requires_card_setup] }
render json: { success: true, line_items: purchase_responses, offer_codes:, can_buyer_sign_up: }
end
def confirm
ActiveRecord::Base.connection.stick_to_primary!
order = Order.find_by_external_id(params[:id])
e404 unless order
confirm_responses, offer_codes = Order::ConfirmService.new(order:, params:).perform
confirm_responses.each do |purchase_id, response|
next unless response[:success]
purchase = Purchase.find(purchase_id)
create_purchase_event_and_recommendation_info(purchase)
end
order.send_charge_receipts
render json: { success: true, line_items: confirm_responses, offer_codes:, can_buyer_sign_up: }
end
private
def validate_order_request
# Don't allow the order to go through if the buyer is a bot. Pretend that the order succeeded instead.
return render json: { success: true } if is_bot?
# Don't allow the order to go through if cookies are disabled and it's a paid order
contains_paid_purchase = if params[:line_items].present?
params[:line_items].any? { |product_params| product_params[:perceived_price_cents] != "0" }
else
params[:perceived_price_cents] != "0"
end
browser_guid = cookies[:_gumroad_guid]
return render_error("Cookies are not enabled on your browser. Please enable cookies and refresh this page before continuing.") if contains_paid_purchase && browser_guid.blank?
# Verify reCAPTCHA response
if !skip_recaptcha? && !valid_recaptcha_response_and_hostname?(site_key: GlobalConfig.get("RECAPTCHA_MONEY_SITE_KEY"))
render_error("Sorry, we could not verify the CAPTCHA. Please try again.")
end
end
def skip_recaptcha?
site_key = GlobalConfig.get("RECAPTCHA_MONEY_SITE_KEY")
return true if (Rails.env.development? || Rails.env.test?) && site_key.blank?
return true if action_name == "create" && all_free_products_without_captcha?
return true if valid_wallet_payment?
false
end
def all_free_products_without_captcha?
line_items = params.fetch(:line_items, {})
line_items.all? do |product|
product_link = Link.find_by(unique_permalink: product["permalink"])
!product_link.require_captcha? && product["perceived_price_cents"].to_s == "0"
end
end
def valid_wallet_payment?
return false if [params[:wallet_type], params[:stripe_payment_method_id]].any?(&:blank?)
payment_method = Stripe::PaymentMethod.retrieve(params[:stripe_payment_method_id])
payment_method&.card&.wallet&.type == params[:wallet_type]
rescue Stripe::StripeError
render_error("Sorry, something went wrong.")
end
def permitted_order_params
params.permit(
# Common params across all purchases of the order
:friend, :locale, :plugins, :save_card, :card_data_handling_mode, :card_data_handling_error,
:card_country, :card_country_source, :wallet_type, :cc_zipcode, :vat_id, :email, :tax_country_election,
:save_shipping_address, :card_expiry_month, :card_expiry_year, :stripe_status, :visual,
:billing_agreement_id, :paypal_order_id, :stripe_payment_method_id, :stripe_customer_id, :stripe_error,
:braintree_transient_customer_store_key, :braintree_device_data, :use_existing_card, :paymentToken,
:url_parameters, :is_gift, :giftee_email, :giftee_id, :gift_note, :referrer,
purchase: [:full_name, :street_address, :city, :state, :zip_code, :country],
# Individual purchase params
line_items: [:uid, :permalink, :perceived_price_cents, :price_range, :discount_code, :is_preorder, :quantity, :call_start_time,
:was_product_recommended, :recommended_by, :referrer, :is_rental, :is_multi_buy,
:was_discover_fee_charged, :price_cents, :tax_cents, :gumroad_tax_cents, :shipping_cents, :price_id, :affiliate_id, :url_parameters, :is_purchasing_power_parity_discounted,
:recommender_model_name, :tip_cents, :pay_in_installments,
custom_fields: [:id, :value], variants: [], perceived_free_trial_duration: [:unit, :amount], accepted_offer: [:id, :original_variant_id, :original_product_id],
bundle_products: [:product_id, :variant_id, :quantity, custom_fields: [:id, :value]]])
end
def fetch_affiliates
line_items = params.fetch(:line_items, [])
line_items.each do |line_item_params|
product = Link.find_by(unique_permalink: line_item_params[:permalink])
# In the case a purchase is both recommended and has an affiliate, recommendation takes priority
# so don't include the affiliate unless it is a global affiliate
affiliate = fetch_affiliate(product, line_item_params)
line_item_params.delete(:affiliate_id)
line_item_params[:affiliate_id] = affiliate.id if affiliate&.eligible_for_purchase_credit?(product:, was_recommended: line_item_params[:was_product_recommended] && line_item_params[:recommended_by] != RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION, purchaser_email: params[:email])
end
end
def create_purchase_event_and_recommendation_info(purchase)
create_purchase_event(purchase)
purchase.handle_recommended_purchase if purchase.was_product_recommended
end
def render_error(error_message, purchase: nil)
render json: error_response(error_message, purchase:)
end
def can_buyer_sign_up
!logged_in_user && User.alive.where(email: params[:email]).none?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/oauth_completions_controller.rb | app/controllers/oauth_completions_controller.rb | # frozen_string_literal: true
class OauthCompletionsController < ApplicationController
before_action :authenticate_user!
def stripe
stripe_connect_data = session[:stripe_connect_data] || {}
auth_uid = stripe_connect_data["auth_uid"]
referer = stripe_connect_data["referer"]
signing_in = stripe_connect_data["signup"]
unless auth_uid
flash[:alert] = "Invalid OAuth session"
return safe_redirect_to settings_payments_path
end
stripe_account = Stripe::Account.retrieve(auth_uid)
merchant_account = MerchantAccount.where(charge_processor_merchant_id: auth_uid).alive
.find { |ma| ma.is_a_stripe_connect_account? }
if merchant_account.present? && merchant_account.user != current_user
flash[:alert] = "This Stripe account has already been linked to a Gumroad account."
return safe_redirect_to referer
end
merchant_account = current_user.merchant_accounts.new unless merchant_account.present?
merchant_account.charge_processor_id = StripeChargeProcessor.charge_processor_id
merchant_account.charge_processor_merchant_id = auth_uid
merchant_account.deleted_at = nil
merchant_account.charge_processor_deleted_at = nil
merchant_account.charge_processor_alive_at = Time.current
merchant_account.meta = { "stripe_connect" => "true" }
if merchant_account.save
current_user.check_merchant_account_is_linked = true
current_user.save!
merchant_account.currency = stripe_account.default_currency
merchant_account.country = stripe_account.country
merchant_account.save!
else
flash[:alert] = "There was an error connecting your Stripe account with Gumroad."
return safe_redirect_to referer
end
if merchant_account.active?
current_user.stripe_account&.delete_charge_processor_account!
flash[:notice] = signing_in ? "You have successfully signed in with your Stripe account!" : "You have successfully connected your Stripe account!"
else
flash[:alert] = "There was an error connecting your Stripe account with Gumroad."
end
success_redirect_path = case referer
when settings_payments_path
settings_payments_path
else
dashboard_path
end
session.delete(:stripe_connect_data)
safe_redirect_to success_redirect_path
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/url_redirects_controller.rb | app/controllers/url_redirects_controller.rb | # frozen_string_literal: true
class UrlRedirectsController < ApplicationController
include SignedUrlHelper
include ProductsHelper
before_action :fetch_url_redirect, except: %i[
show stream download_subtitle_file read download_archive latest_media_locations download_product_files
audio_durations
]
before_action :redirect_to_custom_domain_if_needed, only: :download_page
before_action :redirect_bundle_purchase_to_library_if_needed, only: :download_page
before_action :redirect_to_coffee_page_if_needed, only: :download_page
before_action :check_permissions, only: %i[show stream download_page
hls_playlist download_subtitle_file read
download_archive latest_media_locations download_product_files audio_durations]
before_action :hide_layouts, only: %i[
confirm_page membership_inactive_page expired rental_expired_page show download_page download_product_files stream smil hls_playlist download_subtitle_file read
]
before_action :mark_rental_as_viewed, only: %i[smil hls_playlist]
after_action :register_that_user_has_downloaded_product, only: %i[download_page show stream read]
after_action -> { create_consumption_event!(ConsumptionEvent::EVENT_TYPE_READ) }, only: [:read]
after_action -> { create_consumption_event!(ConsumptionEvent::EVENT_TYPE_WATCH) }, only: [:hls_playlist, :smil]
after_action -> { create_consumption_event!(ConsumptionEvent::EVENT_TYPE_DOWNLOAD) }, only: [:show]
after_action -> { create_consumption_event!(ConsumptionEvent::EVENT_TYPE_VIEW) }, only: [:download_page]
skip_before_action :check_suspended, only: %i[show stream confirm confirm_page download_page
download_subtitle_file download_archive download_product_files audio_durations]
before_action :set_noindex_header, only: %i[confirm_page download_page]
rescue_from ActionController::RoutingError do |exception|
if params[:action] == "read"
redirect_to user_signed_in? ? library_path : root_path
else
raise exception
end
end
module AddToLibraryOption
NONE = "none"
ADD_TO_LIBRARY_BUTTON = "add_to_library_button"
SIGNUP_FORM = "signup_form"
end
def show
trigger_files_lifecycle_events
redirect_to @url_redirect.redirect_or_s3_location, allow_other_host: true
end
def read
product = @url_redirect.referenced_link
@product_file = @url_redirect.product_file(params[:product_file_id])
@product_file = product.product_files.alive.find(&:readable?) if product.present? && @product_file.nil?
e404 unless @product_file&.readable?
s3_retrievable = @product_file
@title = @product_file.with_product_files_owner.name
@read_id = @product_file.external_id
@read_url = signed_download_url_for_s3_key_and_filename(s3_retrievable.s3_key, s3_retrievable.s3_filename, cache_group: "read")
# Used for tracking page turns:
@url_redirect_id = @url_redirect.external_id
@purchase_id = @url_redirect.purchase.try(:external_id)
@product_file_id = @product_file.try(:external_id)
@latest_media_location = @product_file.latest_media_location_for(@url_redirect.purchase)
trigger_files_lifecycle_events
rescue ArgumentError
redirect_to(library_path)
end
def download_page
@hide_layouts = true
@body_class = "download-page responsive responsive-nav"
@show_user_favicon = true
@title = @url_redirect.with_product_files.name == "Untitled" ? @url_redirect.referenced_link.name : @url_redirect.with_product_files.name
@react_component_props = UrlRedirectPresenter.new(url_redirect: @url_redirect, logged_in_user:).download_page_with_content_props(common_props)
trigger_files_lifecycle_events
end
def download_product_files
product_files = @url_redirect.alive_product_files.by_external_ids(params[:product_file_ids])
e404 unless product_files.present? && product_files.all? { @url_redirect.is_file_downloadable?(_1) }
if request.format.json?
render(json: { files: product_files.map { { url: @url_redirect.signed_location_for_file(_1), filename: _1.s3_filename } } })
else
# Non-JSON requests to this controller route pass an array with a single product file ID for `product_file_ids`
@product_file = product_files.first
if @product_file.must_be_pdf_stamped? && @url_redirect.missing_stamped_pdf?(@product_file)
flash[:alert] = "We are preparing the file for download. You will receive an email when it is ready."
# Do not enqueue the job more than once in 2 hours
Rails.cache.fetch(PdfStampingService.cache_key_for_purchase(@url_redirect.purchase_id), expires_in: 4.hours) do
StampPdfForPurchaseJob.set(queue: :critical).perform_async(@url_redirect.purchase_id, true) # Stamp and notify the buyer
end
return redirect_to(@url_redirect.download_page_url)
end
redirect_to(@url_redirect.signed_location_for_file(@product_file), allow_other_host: true)
create_consumption_event!(ConsumptionEvent::EVENT_TYPE_DOWNLOAD)
end
end
def download_archive
archive = params[:folder_id].present? ? @url_redirect.folder_archive(params[:folder_id]) : @url_redirect.entity_archive
if request.format.json?
url = url_redirect_download_archive_url(params[:id], folder_id: params[:folder_id]) if archive.present?
render json: { url: }
else
e404 if archive.nil?
redirect_to(
signed_download_url_for_s3_key_and_filename(archive.s3_key, archive.s3_filename),
allow_other_host: true
)
event_type = params[:folder_id].present? ? ConsumptionEvent::EVENT_TYPE_FOLDER_DOWNLOAD : ConsumptionEvent::EVENT_TYPE_DOWNLOAD_ALL
create_consumption_event!(event_type)
end
end
def download_subtitle_file
(product_file = @url_redirect.product_file(params[:product_file_id])) || e404
e404 unless @url_redirect.is_file_downloadable?(product_file)
(subtitle_file = product_file.subtitle_files.alive.find_by_external_id(params[:subtitle_file_id])) || e404
redirect_to @url_redirect.signed_video_url(subtitle_file), allow_other_host: true
end
def smil
@product_file = @url_redirect.product_file(params[:product_file_id])
e404 if @product_file.blank?
render plain: @url_redirect.smil_xml_for_product_file(@product_file), content_type: Mime[:text]
end
# Public: Returns a modified version of the Elastic Transcoder-generated master playlist in order to prevent hotlinking.
#
# The original master playlist simply has relative paths to the resolution-specific playlists and works by the assumption that all playlist
# files and .ts segments are public. This makes it easy for anyone to hotlink the video by posting the path to either of the playlist files.
# The ideal way to prevent that is to use AES encryption, which Elastic Transcoder doesn't yet support. We instead make the playlist files private
# and provide signed urls to these playlist files.
def hls_playlist
(@product_file = @url_redirect.product_file(params[:product_file_id]) || @url_redirect.alive_product_files.first) || e404
hls_playlist_data = @product_file.hls_playlist
e404 if hls_playlist_data.blank?
render plain: hls_playlist_data, content_type: "application/x-mpegurl"
end
def confirm_page
@content_unavailability_reason_code = UrlRedirectPresenter::CONTENT_UNAVAILABILITY_REASON_CODES[:email_confirmation_required]
@title = "#{@url_redirect.referenced_link.name} - Confirm email"
extra_props = common_props.merge(
confirmation_info: {
id: @url_redirect.token,
destination: params[:destination].presence || (@url_redirect.rich_content_json.present? ? "download_page" : nil),
display: params[:display],
email: params[:email],
},
)
@react_component_props = UrlRedirectPresenter.new(url_redirect: @url_redirect, logged_in_user:).download_page_without_content_props(extra_props)
end
def expired
@content_unavailability_reason_code = UrlRedirectPresenter::CONTENT_UNAVAILABILITY_REASON_CODES[:access_expired]
render_unavailable_page(title_suffix: "Access expired")
end
def rental_expired_page
@content_unavailability_reason_code = UrlRedirectPresenter::CONTENT_UNAVAILABILITY_REASON_CODES[:rental_expired]
render_unavailable_page(title_suffix: "Your rental has expired")
end
def membership_inactive_page
@content_unavailability_reason_code = UrlRedirectPresenter::CONTENT_UNAVAILABILITY_REASON_CODES[:inactive_membership]
render_unavailable_page(title_suffix: "Your membership is inactive")
end
def change_purchaser
if params[:email].blank? || !ActiveSupport::SecurityUtils.secure_compare(params[:email].strip.downcase, @url_redirect.purchase.email.strip.downcase)
flash[:alert] = "Please enter the correct email address used to purchase this product"
return redirect_to url_redirect_check_purchaser_path({ id: @url_redirect.token, next: params[:next].presence }.compact)
end
purchase = @url_redirect.purchase
purchase.purchaser = logged_in_user
purchase.save!
redirect_to_next
end
def confirm
forwardable_query_params = {}
forwardable_query_params[:display] = params[:display] if params[:display].present?
if @url_redirect.purchase.email.casecmp(params[:email].to_s.strip.downcase).zero?
set_confirmed_redirect_cookie
if params[:destination] == "download_page"
redirect_to url_redirect_download_page_path(@url_redirect.token, **forwardable_query_params)
elsif params[:destination] == "stream"
redirect_to url_redirect_stream_page_path(@url_redirect.token, **forwardable_query_params)
else
redirect_to url_redirect_path(@url_redirect.token, **forwardable_query_params)
end
else
flash[:alert] = "Wrong email. Please try again."
redirect_to confirm_page_path(id: @url_redirect.token, **forwardable_query_params)
end
end
def send_to_kindle
return render json: { success: false, error: "Please enter a valid Kindle email address" } if params[:email].blank?
if logged_in_user.present?
logged_in_user.kindle_email = params[:email]
return render json: { success: false, error: logged_in_user.errors.full_messages.to_sentence } unless logged_in_user.save
end
@product_file = ProductFile.find_by_external_id(params[:file_external_id])
begin
@product_file.send_to_kindle(params[:email])
create_consumption_event!(ConsumptionEvent::EVENT_TYPE_READ)
render json: { success: true }
rescue ArgumentError => e
render json: { success: false, error: e.message }
end
end
# Consumption event is created by front-end code
def stream
@title = "Watch"
@body_id = "stream_page"
@body_class = "download-page responsive responsive-nav"
@product_file = @url_redirect.product_file(params[:product_file_id]) || @url_redirect.alive_product_files.find(&:streamable?)
e404 unless @product_file&.streamable?
@videos_playlist = @url_redirect.video_files_playlist(@product_file)
@should_show_transcoding_notice = logged_in_user == @url_redirect.seller && !@url_redirect.with_product_files.has_been_transcoded?
@url_redirect_id = @url_redirect.external_id
@purchase_id = @url_redirect.purchase.try(:external_id)
render :video_stream
end
def latest_media_locations
e404 if @url_redirect.purchase.nil? || @url_redirect.installment.present?
product_files = @url_redirect.alive_product_files.select(:id)
media_locations_by_file = MediaLocation.max_consumed_at_by_file(purchase_id: @url_redirect.purchase.id).index_by(&:product_file_id)
json = product_files.each_with_object({}) do |product_file, hash|
hash[product_file.external_id] = media_locations_by_file[product_file.id].as_json
end
render json:
end
def audio_durations
return render json: {} if params[:file_ids].blank?
json = @url_redirect.alive_product_files.where(filegroup: "audio").by_external_ids(params[:file_ids]).each_with_object({}) do |product_file, hash|
hash[product_file.external_id] = product_file.content_length
end
render json:
end
def media_urls
return render json: {} if params[:file_ids].blank?
json = @url_redirect.alive_product_files.by_external_ids(params[:file_ids]).each_with_object({}) do |product_file, hash|
urls = []
urls << @url_redirect.hls_playlist_or_smil_xml_path(product_file) if product_file.streamable?
urls << @url_redirect.signed_location_for_file(product_file) if product_file.listenable? || product_file.streamable?
hash[product_file.external_id] = urls
end
render json:
end
private
def trigger_files_lifecycle_events
@url_redirect.update_transcoded_videos_last_accessed_at
@url_redirect.enqueue_job_to_regenerate_deleted_transcoded_videos
end
def redirect_to_custom_domain_if_needed
return if Feature.inactive?(:custom_domain_download)
creator_subdomain_with_protocol = @url_redirect.seller.subdomain_with_protocol
target_host = !@is_user_custom_domain && creator_subdomain_with_protocol.present? ? creator_subdomain_with_protocol : request.host
return if target_host == request.host
redirect_to(
custom_domain_download_page_url(@url_redirect.token, host: target_host, receipt: params[:receipt]),
status: :moved_permanently,
allow_other_host: true
)
end
def redirect_bundle_purchase_to_library_if_needed
return unless @url_redirect.purchase&.is_bundle_purchase?
redirect_to library_url(bundles: @url_redirect.purchase.link.external_id, purchase_id: params[:receipt] && @url_redirect.purchase.external_id)
end
def redirect_to_coffee_page_if_needed
return unless @url_redirect.referenced_link&.native_type == Link::NATIVE_TYPE_COFFEE
redirect_to custom_domain_coffee_url(host: @url_redirect.seller.subdomain_with_protocol, purchase_email: params[:purchase_email]), allow_other_host: true
end
def register_that_user_has_downloaded_product
return if @url_redirect.nil?
@url_redirect.increment!(:uses, 1)
@url_redirect.mark_as_seen
set_confirmed_redirect_cookie
end
def mark_rental_as_viewed
@url_redirect.mark_rental_as_viewed!
end
def fetch_url_redirect
@url_redirect = UrlRedirect.find_by(token: params[:id])
return e404 if @url_redirect.nil?
# 404 if the installment had some files when this url redirect was created but now it does not (i.e. if the installment was deleted, or the creator removed the files).
return unless @url_redirect.installment.present?
return e404 if @url_redirect.installment.deleted?
return if @url_redirect.referenced_link&.is_recurring_billing
return e404 if @url_redirect.with_product_files.nil?
has_files = @url_redirect.with_product_files.has_files?
can_view_product_download_page_without_files =
@url_redirect.installment.product_or_variant_type? &&
@url_redirect.purchase_id.present?
e404 if !has_files && !can_view_product_download_page_without_files
end
def check_permissions
fetch_url_redirect
purchase = @url_redirect.purchase
return e404 if purchase && (purchase.stripe_refunded || (purchase.chargeback_date.present? && !purchase.chargeback_reversed))
return redirect_to url_redirect_check_purchaser_path(@url_redirect.token, next: request.path) if purchase && user_signed_in? && purchase.purchaser.present? && logged_in_user != purchase.purchaser && !logged_in_user.is_team_member?
return redirect_to url_redirect_rental_expired_page_path(@url_redirect.token) if @url_redirect.rental_expired?
return redirect_to url_redirect_expired_page_path(@url_redirect.token) if purchase && purchase.is_access_revoked
if purchase&.subscription && !purchase.subscription.grant_access_to_product?
return redirect_to url_redirect_membership_inactive_page_path(@url_redirect.token)
end
if cookies.encrypted[:confirmed_redirect] == @url_redirect.token ||
(purchase && ((purchase.purchaser && purchase.purchaser == logged_in_user) || purchase.ip_address == request.remote_ip))
return
end
return if @url_redirect.imported_customer.present?
return if !@url_redirect.has_been_seen || @url_redirect.purchase.nil?
forwardable_query_params = { id: @url_redirect.token, destination: params[:action] }
forwardable_query_params[:display] = params[:display] if params[:display].present?
redirect_to confirm_page_path(forwardable_query_params)
end
def create_consumption_event!(event_type)
ConsumptionEvent.create_event!(
event_type:,
platform: Platform::WEB,
url_redirect_id: @url_redirect.id,
product_file_id: @product_file&.id,
purchase_id: @url_redirect.purchase_id,
product_id: @url_redirect.purchase&.link_id || @url_redirect.link_id,
folder_id: params[:folder_id],
ip_address: request.remote_ip,
)
end
def set_confirmed_redirect_cookie
cookies.encrypted[:confirmed_redirect] = {
value: @url_redirect.token,
httponly: true
}
end
def render_unavailable_page(title_suffix:)
@title = "#{@url_redirect.referenced_link.name} - #{title_suffix}"
@react_component_props = UrlRedirectPresenter.new(url_redirect: @url_redirect, logged_in_user:).download_page_without_content_props(common_props)
render :unavailable
end
def common_props
add_to_library_option = if @url_redirect.purchase && @url_redirect.purchase.purchaser.nil?
logged_in_user.present? ? AddToLibraryOption::ADD_TO_LIBRARY_BUTTON : AddToLibraryOption::SIGNUP_FORM
else
AddToLibraryOption::NONE
end
{
is_mobile_app_web_view: params[:display] == "mobile_app",
content_unavailability_reason_code: @content_unavailability_reason_code,
add_to_library_option:,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/comments_controller.rb | app/controllers/comments_controller.rb | # frozen_string_literal: true
class CommentsController < ApplicationController
before_action :set_post, only: %i[index create update destroy]
before_action :set_comment, only: %i[update destroy]
before_action :set_purchase, only: %i[index create update destroy]
before_action :build_post_comment, only: %i[create]
after_action :verify_authorized
def index
comment_context = CommentContext.new(
comment: nil,
commentable: @post,
purchase: @purchase
)
authorize comment_context
render json: PaginatedCommentsPresenter.new(
pundit_user:,
commentable: @post,
purchase: @purchase,
options: { page: params[:page] }
).result
end
def create
comment_context = CommentContext.new(
comment: @comment,
commentable: nil,
purchase: @purchase
)
authorize comment_context
if @comment.save
render json: { success: true, comment: comment_json }
else
render json: { success: false, error: @comment.errors.full_messages.first }, status: :unprocessable_entity
end
end
def update
comment_context = CommentContext.new(
comment: @comment,
commentable: nil,
purchase: @purchase
)
authorize comment_context
if @comment.update(permitted_update_params)
render json: { success: true, comment: comment_json }
else
render json: { success: false, error: @comment.errors.full_messages.first }, status: :unprocessable_entity
end
end
def destroy
comment_context = CommentContext.new(
comment: @comment,
commentable: nil,
purchase: @purchase
)
authorize comment_context
deleted_comments = @comment.mark_subtree_deleted!
render json: { success: true, deleted_comment_ids: deleted_comments.map(&:external_id) }
end
private
def build_post_comment
comment_author = logged_in_user || @purchase&.purchaser
parent_comment = permitted_create_params[:parent_id].presence && Comment.find_by_external_id(permitted_create_params[:parent_id])
@comment = @post.comments.new(permitted_create_params.except(:parent_id))
@comment.parent_id = parent_comment&.id
@comment.author_id = comment_author&.id
@comment.author_name = comment_author&.display_name || @purchase&.full_name || @purchase&.email
# When 'author_id' is not available, we can fallback to associated
# `purchase` to recognize the comment author
@comment.purchase = @purchase
@comment.comment_type = Comment::COMMENT_TYPE_USER_SUBMITTED
end
def comment_json
CommentPresenter.new(
pundit_user:,
comment: @comment,
purchase: @purchase
).comment_component_props
end
def set_post
@post = Installment.published.find_by_external_id(params[:post_id])
e404_json if @post.blank?
end
def set_comment
@comment = @post.comments.find_by_external_id(params[:id])
e404_json if @comment.blank?
end
def set_purchase
# Post author doesn't need a purchase
return if current_seller && current_seller.id == @post.seller_id
if params[:purchase_id]
@purchase = Purchase.find_by_external_id(params[:purchase_id])
elsif logged_in_user
@purchase = Purchase.where(purchaser_id: logged_in_user.id, link_id: @post.link&.id)
.all_success_states
.not_chargedback_or_chargedback_reversed
.not_fully_refunded
.first
end
if @purchase.present? && @purchase.link.is_recurring_billing
subscription = Subscription.find(@purchase.subscription_id)
@purchase = subscription.original_purchase
end
end
def permitted_create_params
params.require(:comment).permit(:content, :parent_id)
end
def permitted_update_params
params.require(:comment).permit(:content)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/commissions_controller.rb | app/controllers/commissions_controller.rb | # frozen_string_literal: true
class CommissionsController < ApplicationController
def update
commission = Commission.find_by_external_id!(params[:id])
authorize commission
file_signed_ids = permitted_params[:file_signed_ids]
commission.files.each do |file|
file.purge unless file_signed_ids.delete(file.signed_id)
end
commission.files.attach(file_signed_ids)
head :no_content
rescue ActiveRecord::RecordInvalid => e
render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
end
def complete
commission = Commission.find_by_external_id!(params[:id])
authorize commission
begin
commission.create_completion_purchase!
head :no_content
rescue
render json: { errors: ["Failed to complete commission"] }, status: :unprocessable_entity
end
end
private
def permitted_params
params.permit(file_signed_ids: [])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/robots_controller.rb | app/controllers/robots_controller.rb | # frozen_string_literal: true
class RobotsController < ApplicationController
def index
robots_service = RobotsService.new
@sitemap_configs = robots_service.sitemap_configs
@user_agent_rules = robots_service.user_agent_rules
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/s3_utility_controller.rb | app/controllers/s3_utility_controller.rb | # frozen_string_literal: true
class S3UtilityController < Sellers::BaseController
include CdnUrlHelper
before_action :authorize
def generate_multipart_signature
# Prevent attackers from using newlines to split the request body and bypass the seller check
params["to_sign"].split(/[\n\r\s]/).grep(/\A\//).each do |url|
return render(json: { success: false, error: "Unauthorized" }, status: :forbidden) if !%r{\A/#{S3_BUCKET}/\w+/#{current_seller.external_id}/}.match?(url)
end
render inline: Utilities.sign_with_aws_secret_key(params[:to_sign])
end
def current_utc_time_string
render plain: Time.current.httpdate
end
def cdn_url_for_blob
blob = ActiveStorage::Blob.find_by_key(params[:key])
blob || e404
respond_to do |format|
format.html { redirect_to cdn_url_for(blob.url), allow_other_host: true }
format.json { render json: { url: cdn_url_for(blob.url) } }
end
end
private
def authorize
super(:s3_utility)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/logins_controller.rb | app/controllers/logins_controller.rb | # frozen_string_literal: true
class LoginsController < Devise::SessionsController
include OauthApplicationConfig, ValidateRecaptcha, InertiaRendering
skip_before_action :check_suspended, only: %i[create destroy]
before_action :block_json_request, only: :new
after_action :clear_dashboard_preference, only: :destroy
before_action :reset_impersonated_user, only: :destroy
before_action :set_noindex_header, only: :new, if: -> { params[:next]&.start_with?("/oauth/authorize") }
layout "inertia", only: [:new]
def new
return redirect_to login_path(next: request.referrer) if params[:next].blank? && request_referrer_is_a_valid_after_login_path?
@title = "Log In"
auth_presenter = AuthPresenter.new(params:, application: @application)
render inertia: "Logins/New", props: auth_presenter.login_props
end
def create
site_key = GlobalConfig.get("RECAPTCHA_LOGIN_SITE_KEY")
if !(Rails.env.development? && site_key.blank?) && !valid_recaptcha_response?(site_key: site_key)
return redirect_with_login_error("Sorry, we could not verify the CAPTCHA. Please try again.")
end
if params["user"].instance_of?(ActionController::Parameters)
login_identifier = params["user"]["login_identifier"]
password = params["user"]["password"]
@user = User.where(email: login_identifier).first || User.where(username: login_identifier).first if login_identifier.present?
end
return redirect_with_login_error("An account does not exist with that email.") if @user.blank?
return redirect_with_login_error("Please try another password. The one you entered was incorrect.") unless @user.valid_password?(password)
return redirect_with_login_error("You cannot log in because your account was permanently deleted. Please sign up for a new account to start selling!") if @user.deleted?
if @user.suspended_for_fraud?
check_suspended
else
@user.remember_me = true # Always "remember" user sessions
sign_in_or_prepare_for_two_factor_auth(@user)
if @user.respond_to?(:pwned?) && @user.pwned?
flash[:warning] = "Your password has previously appeared in a data breach as per haveibeenpwned.com and should never be used. We strongly recommend you change your password everywhere you have used it."
end
redirect_to login_path_for(@user), allow_other_host: true
end
end
private
def block_json_request
return if request.inertia?
head :bad_request if request.format.json?
end
def redirect_with_login_error(message)
redirect_to login_path, warning: message, status: :see_other
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/collaborators_controller.rb | app/controllers/collaborators_controller.rb | # frozen_string_literal: true
class CollaboratorsController < Sellers::BaseController
layout "inertia", only: [:index]
def index
authorize Collaborator
@title = "Collaborators"
render inertia: "Collaborators/Index"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/tax_center_controller.rb | app/controllers/tax_center_controller.rb | # frozen_string_literal: true
class TaxCenterController < Sellers::BaseController
layout "inertia", only: [:index]
before_action :ensure_tax_center_enabled
def index
authorize :balance
@title = "Payouts"
year = params[:year]&.to_i || Time.current.year - 1
tax_center_presenter = TaxCenterPresenter.new(seller: current_seller, year:)
render inertia: "TaxCenter/Index", props: tax_center_presenter.props
end
def download
authorize :balance, :index?
year = params[:year].to_i
form_type = params[:form_type]
error_message = "Tax form not available for download."
tax_form = current_seller.user_tax_forms.for_year(year).where(tax_form_type: form_type).first
if tax_form.blank?
redirect_to tax_center_path(year:), alert: error_message
return
end
stripe_account_id = tax_form.stripe_account_id || current_seller.stripe_account&.charge_processor_merchant_id
if stripe_account_id && !current_seller.merchant_accounts.stripe.exists?(charge_processor_merchant_id: stripe_account_id)
redirect_to tax_center_path(year:), alert: error_message
return
end
pdf_tempfile = StripeTaxFormsApi.new(stripe_account_id:, form_type:, year:).download_tax_form
if pdf_tempfile
filename = "#{form_type.delete_prefix('us_').tr('_', '-').upcase}-#{year}.pdf"
send_file pdf_tempfile.path, filename:, type: "application/pdf", disposition: "attachment"
pdf_tempfile.close
else
redirect_to tax_center_path(year:), alert: error_message
end
end
private
def ensure_tax_center_enabled
return if Feature.active?(:tax_center, current_seller)
redirect_to dashboard_path, alert: "Tax center is not enabled for your account."
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/healthcheck_controller.rb | app/controllers/healthcheck_controller.rb | # frozen_string_literal: true
class HealthcheckController < ApplicationController
def index
render plain: "healthcheck"
end
def sidekiq
enqueued_jobs_above_limit = SIDEKIQ_QUEUE_LIMITS.any? do |queue, limit|
Sidekiq::Queue.new(queue).size > limit
end
enqueued_jobs_above_limit ||= Sidekiq::RetrySet.new.size > SIDEKIQ_RETRIES_LIMIT
enqueued_jobs_above_limit ||= Sidekiq::DeadSet.new.size > SIDEKIQ_DEAD_LIMIT
status = enqueued_jobs_above_limit ? :service_unavailable : :ok
render plain: "Sidekiq: #{status}", status:
end
SIDEKIQ_QUEUE_LIMITS = { critical: 12_000 }
SIDEKIQ_RETRIES_LIMIT = 20_000
SIDEKIQ_DEAD_LIMIT = 10_000
private_constant :SIDEKIQ_QUEUE_LIMITS, :SIDEKIQ_RETRIES_LIMIT, :SIDEKIQ_DEAD_LIMIT
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/shipments_controller.rb | app/controllers/shipments_controller.rb | # frozen_string_literal: true
class ShipmentsController < ApplicationController
before_action :authenticate_user!, only: [:mark_as_shipped]
before_action :set_purchase, only: [:mark_as_shipped]
after_action :verify_authorized, only: [:mark_as_shipped]
EASYPOST_ERROR_FIELD_MAPPING = {
"street1" => "street",
"city" => "city",
"state" => "state",
"zip" => "zip_code",
"country" => "country"
}.freeze
def verify_shipping_address
easy_post = EasyPost::Client.new(api_key: GlobalConfig.get("EASYPOST_API_KEY"))
address = easy_post.address.create(
verify: ["delivery"],
street1: params.require(:street_address),
city: params.require(:city),
state: params.require(:state),
zip: params.require(:zip_code),
country: params.require(:country)
)
if address.present?
if address.verifications.delivery.success && address.verifications.delivery.errors.empty?
render_address_response(address)
else
error = address.verifications.delivery.errors.first
if error.code.match?(/HOUSE_NUMBER.MISSING|STREET.MISSING|BOX_NUMBER.MISSING|SECONDARY_INFORMATION.MISSING/)
render_error("Is this your street address? You might be missing an apartment, suite, or box number.")
else
render_error("We are unable to verify your shipping address. Is your address correct?")
end
end
else
render_error("We are unable to verify your shipping address. Is your address correct?")
end
rescue EasyPost::Errors::EasyPostError
render_error("We are unable to verify your shipping address. Is your address correct?")
end
def mark_as_shipped
authorize [:audience, @purchase]
# For old products, before we started creating shipments for any products with shipping addresses.
shipment = Shipment.create(purchase: @purchase) if @purchase.shipment.blank?
shipment ||= @purchase.shipment
if params[:tracking_url]
shipment.tracking_url = params[:tracking_url]
shipment.save!
end
shipment.mark_shipped!
head :no_content
end
protected
def set_purchase
@purchase = current_seller.sales.find_by_external_id(params[:purchase_id]) || e404_json
end
private
def render_error(error_message)
render json: { success: false, error_message: }
end
def render_address_response(address)
if address_unchanged?(address)
render json: { success: true,
street_address: address.street1,
city: address.city,
state: address.state,
zip_code: formatted_zip_for(address) }
else
render json: { success: false,
easypost_verification_required: true,
street_address: address.street1,
city: address.city,
state: address.state,
zip_code: formatted_zip_for(address),
formatted_address: formatted_address(address),
formatted_original_address: formatted_address(original_address) }
end
end
# Address suggestion and formatting helpers
def formatted_address(address)
# For street address cannot use titlecase directly on string,
# since "17th st", gets converted to "17 Th St", instead of "17th St".
street = address[:street1].split.map(&:capitalize).join(" ")
city = address[:city].titleize
zip = formatted_zip_for(address)
state = formatted_state_for(address)
"#{street}, #{city}, #{state}, #{zip}"
end
def address_unchanged?(address)
updated_zip = formatted_zip_for(address)
original_zip = formatted_zip_for(original_address)
match_field_for(original_address, address, :street1) &&
match_field_for(original_address, address, :city) &&
match_field_for(original_address, address, :state) &&
updated_zip == original_zip
end
def match_field_for(old_addr, new_addr, field)
new_addr[field].downcase == old_addr[field].downcase
end
def original_address
{ street1: params[:street_address],
city: params[:city],
state: params[:state],
zip: params[:zip_code],
country: params[:country]
}
end
def formatted_zip_for(address)
in_us?(address) ? address[:zip][0..4] : address[:zip]
end
def formatted_state_for(address)
in_us?(address) ? address[:state].upcase : address[:state].titleize
end
def in_us?(address)
["US", "UNITED STATES"].include?(address[:country].upcase)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/public_controller.rb | app/controllers/public_controller.rb | # frozen_string_literal: true
class PublicController < ApplicationController
include ActionView::Helpers::NumberHelper
before_action { opt_out_of_header(:csp) } # for the use of external JS on public pages
before_action :hide_layouts, only: [:thank_you]
before_action :set_on_public_page
layout "inertia", only: [:widgets, :ping]
def home
redirect_to user_signed_in? ? after_sign_in_path_for(logged_in_user) : login_path
end
def widgets
@title = "Widgets"
widget_presenter = WidgetPresenter.new(seller: current_seller)
render inertia: "Public/Widgets", props: widget_presenter.widget_props
end
def charge
@title = "Why is there a charge on my account?"
end
def charge_data
purchases = Purchase.successful_gift_or_nongift.where("email = ?", params[:email])
purchases = purchases.where("card_visual like ?", "%#{params[:last_4]}%") if params[:last_4].present? && params[:last_4].length == 4
if purchases.none?
render json: { success: false }
else
CustomerMailer.grouped_receipt(purchases.ids).deliver_later(queue: "critical")
render json: { success: true }
end
end
def paypal_charge_data
return render json: { success: false } if params[:invoice_id].nil?
purchase = Purchase.find_by_external_id(params[:invoice_id])
if purchase.nil?
render json: { success: false }
else
SendPurchaseReceiptJob.set(queue: purchase.link.has_stampable_pdfs? ? "default" : "critical").perform_async(purchase.id)
render json: { success: true }
end
end
def license_key_lookup
@title = "What is my license key?"
end
# api methods
def api
@title = "API"
@on_api_page = true
end
def ping
@title = "Ping"
render inertia: "Public/Ping"
end
def thank_you
@title = "Thank you!"
end
def working_webhook
render plain: "http://www.gumroad.com"
end
def crossdomain
respond_to :xml
end
private
def set_on_public_page
@body_class = "public"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/calls_controller.rb | app/controllers/calls_controller.rb | # frozen_string_literal: true
class CallsController < ApplicationController
before_action :authenticate_user!
def update
@call = Call.find_by_external_id!(params[:id])
authorize @call
@call.update!(params.permit(policy(@call).permitted_attributes))
head :no_content
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/dropbox_files_controller.rb | app/controllers/dropbox_files_controller.rb | # frozen_string_literal: true
class DropboxFilesController < Sellers::BaseController
before_action :authorize
def create
dropbox_file = DropboxFile.create_with_file_info(permitted_params)
dropbox_file.user = current_seller
if permitted_params[:link_id]
fetch_product_and_enforce_ownership
dropbox_file.link = @product
end
dropbox_file.save!
render json: { dropbox_file: }
end
def index
fetch_product_and_enforce_ownership if permitted_params[:link_id]
dropbox_files = @product.present? ? @product.dropbox_files.available_for_product : current_seller.dropbox_files.available
render json: { dropbox_files: }
end
def cancel_upload
dropbox_file = current_seller.dropbox_files.find_by_external_id(permitted_params[:id])
return render json: { success: false } if dropbox_file.nil?
if dropbox_file.successfully_uploaded?
dropbox_file.mark_deleted!
elsif dropbox_file.in_progress?
dropbox_file.mark_cancelled!
end
render json: { dropbox_file:, success: true }
end
private
def permitted_params
params.permit(:id, :bytes, :name, :link, :icon, :link_id)
end
def authorize
super(:dropbox_files)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/imported_customers_controller.rb | app/controllers/imported_customers_controller.rb | # frozen_string_literal: true
class ImportedCustomersController < ApplicationController
PUBLIC_ACTIONS = %i[unsubscribe].freeze
before_action :authenticate_user!, except: PUBLIC_ACTIONS
after_action :verify_authorized, except: PUBLIC_ACTIONS
def destroy
imported_customer = current_seller.imported_customers.find_by_external_id(params[:id])
authorize imported_customer
if imported_customer.present?
imported_customer.deleted_at = Time.current
imported_customer.save!
render json: { success: true, message: "Deleted!", imported_customer: }
else
render json: { success: false }
end
end
def unsubscribe
@imported_customer = ImportedCustomer.find_by_external_id(params[:id]) || e404
@imported_customer.deleted_at = if @imported_customer.deleted_at
nil
else
Time.current
end
@imported_customer.save!
end
def index
authorize ImportedCustomer
imported_customers = current_seller.imported_customers.alive.order("imported_customers.purchase_date DESC")
if params[:link_id].present?
products = Link.by_unique_permalinks(params[:link_id])
imported_customers = imported_customers.where(link_id: products)
end
page = params[:page].to_i
imported_customers = imported_customers.limit(CustomersController::CUSTOMERS_PER_PAGE).offset(page.to_i * CustomersController::CUSTOMERS_PER_PAGE)
render json: {
customers: imported_customers.as_json(pundit_user:),
begin_loading_imported_customers: true
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/analytics_controller.rb | app/controllers/analytics_controller.rb | # frozen_string_literal: true
class AnalyticsController < Sellers::BaseController
before_action :set_time_range, only: %i[data_by_date data_by_state data_by_referral]
after_action :set_dashboard_preference_to_sales, only: :index
before_action :check_payment_details, only: :index
layout "inertia", only: [:index]
def index
authorize :analytics
@analytics_props = AnalyticsPresenter.new(seller: current_seller).page_props
LargeSeller.create_if_warranted(current_seller)
render inertia: "Analytics/Index",
props: { analytics_props: @analytics_props }
end
def data_by_date
authorize :analytics, :index?
if Feature.active?(:use_creator_analytics_web_in_controller)
data = creator_analytics_web.by_date
else
data = CreatorAnalytics::CachingProxy.new(current_seller).data_for_dates(@start_date, @end_date, by: :date)
end
render json: data
end
def data_by_state
authorize :analytics, :index?
if Feature.active?(:use_creator_analytics_web_in_controller)
data = creator_analytics_web.by_state
else
data = CreatorAnalytics::CachingProxy.new(current_seller).data_for_dates(@start_date, @end_date, by: :state)
end
render json: data
end
def data_by_referral
authorize :analytics, :index?
if Feature.active?(:use_creator_analytics_web_in_controller)
data = creator_analytics_web.by_referral
else
data = CreatorAnalytics::CachingProxy.new(current_seller).data_for_dates(@start_date, @end_date, by: :referral)
end
render json: data
end
protected
def set_time_range
begin
end_time = DateTime.parse(strip_timestamp_location(params[:end_time]))
start_date = Date.parse(strip_timestamp_location(params[:start_time]))
rescue StandardError
end_time = DateTime.current
start_date = end_time.to_date.ago(29.days).to_date
end
@start_date = start_date
@end_date = end_time.to_date
end
def creator_analytics_web
CreatorAnalytics::Web.new(user: current_seller, dates: (@start_date .. @end_date).to_a)
end
def set_title
@title = "Analytics"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/third_party_analytics_controller.rb | app/controllers/third_party_analytics_controller.rb | # frozen_string_literal: true
class ThirdPartyAnalyticsController < ApplicationController
before_action { opt_out_of_header(:csp) } # Turn off CSP for this controller
before_action :fetch_product
OVERRIDE_WINDOW_ACTIONS_CODE = "<script type=\"text/javascript\">
try { window.alert = function() {}; } catch(error) { }
try { window.confirm = function() {}; } catch(error) { }
try { window.prompt = function() {}; } catch(error) { }
try { window.print = function() {}; } catch(error) { }
</script>"
OVERRIDE_ON_CLOSE_CODE = "<script type=\"text/javascript\">
try { window.onbeforeunload = null; } catch(error) { }
try { window.onabort = null; } catch(error) { }
</script>"
after_action :erase_cookies_and_skip_session
def index
@third_party_analytics = OVERRIDE_WINDOW_ACTIONS_CODE
product_snippets = @product.third_party_analytics.alive.where(location: [params[:location], "all"]).pluck(:analytics_code)
@third_party_analytics += product_snippets.join("\n") if product_snippets.present?
user_snippets = @product.user.third_party_analytics.universal.alive.where(location: [params[:location], "all"]).pluck(:analytics_code)
@third_party_analytics += user_snippets.join("\n") if user_snippets.present?
@third_party_analytics += OVERRIDE_ON_CLOSE_CODE
if params[:purchase_id].present?
currency = @product.price_currency_type
purchase = @product.sales.find_by_external_id(params[:purchase_id])
# the purchase was just created and may not be in the read replicas so look in master
if purchase.nil?
ActiveRecord::Base.connection.stick_to_primary!
purchase = @product.sales.find_by_external_id(params[:purchase_id])
end
e404 if purchase.nil?
price = Money.new(purchase.displayed_price_cents, currency.to_sym).format(no_cents_if_whole: true, symbol: false)
@third_party_analytics.gsub!("$VALUE", price)
@third_party_analytics.gsub!("$CURRENCY", currency.upcase)
@third_party_analytics.gsub!("$ORDER", params[:purchase_id])
end
render layout: false
end
private
def erase_cookies_and_skip_session
request.session_options[:skip] = true
cookies.clear
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/balance_controller.rb | app/controllers/balance_controller.rb | # frozen_string_literal: true
class BalanceController < Sellers::BaseController
layout "inertia", only: [:index]
def index
authorize :balance
@title = "Payouts"
payouts_presenter = PayoutsPresenter.new(seller: current_seller, params:)
render inertia: "Payouts/Index",
props: {
next_payout_period_data: -> { payouts_presenter.next_payout_period_data },
processing_payout_periods_data: -> { payouts_presenter.processing_payout_periods_data },
payouts_status: -> { current_seller.payouts_status },
payouts_paused_by: -> { current_seller.payouts_paused_by_source },
payouts_paused_for_reason: -> { current_seller.payouts_paused_for_reason },
instant_payout: -> { payouts_presenter.instant_payout_data },
show_instant_payouts_notice: -> { current_seller.eligible_for_instant_payouts? && !current_seller.active_bank_account&.supports_instant_payouts? },
tax_center_enabled: -> { Feature.active?(:tax_center, current_seller) },
past_payout_period_data: InertiaRails.merge { payouts_presenter.past_payout_period_data },
pagination: -> { payouts_presenter.pagination_data }
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/customer_surcharge_controller.rb | app/controllers/customer_surcharge_controller.rb | # frozen_string_literal: true
class CustomerSurchargeController < ApplicationController
include CurrencyHelper
def calculate_all
products = params.require(:products)
vat_id_valid = false
has_vat_id_input = false
shipping_rate = 0
tax_rate = 0
tax_included_rate = 0
subtotal = 0
products.each do |item|
product = Link.find_by_unique_permalink(item[:permalink])
next unless product
surcharges = calculate_surcharges(product, item[:quantity], item[:price].to_d.to_i, subscription_id: item[:subscription_id], recommended_by: item[:recommended_by])
next unless surcharges
tax_result = surcharges[:sales_tax_result]
vat_id_valid = tax_result.business_vat_status == :valid
has_vat_id_input ||= tax_result.to_hash[:has_vat_id_input]
shipping_rate += get_usd_cents(product.price_currency_type, surcharges[:shipping_rate])
tax_cents = tax_result.tax_cents
if tax_cents > 0
tax_rate += tax_cents
end
subtotal += tax_result.price_cents
end
render json: {
vat_id_valid:,
has_vat_id_input:,
shipping_rate_cents: shipping_rate,
tax_cents: tax_rate.round.to_i,
tax_included_cents: tax_included_rate.round.to_i,
subtotal: subtotal.round.to_i
}
end
private
def calculate_surcharges(product, quantity, price, subscription_id: nil, recommended_by: nil)
if subscription_id.present?
subscription = Subscription.find_by_external_id(subscription_id)
return nil unless subscription&.original_purchase.present?
end
sales_tax_info = subscription&.original_purchase&.purchase_sales_tax_info
if sales_tax_info.present?
buyer_location = {
postal_code: sales_tax_info.postal_code,
country: sales_tax_info.country_code,
ip_address: sales_tax_info.ip_address,
state: sales_tax_info.state_code || GeoIp.lookup(sales_tax_info.ip_address)&.region_name,
}
buyer_vat_id = sales_tax_info.business_vat_id
from_discover = subscription.original_purchase.was_discover_fee_charged?
else
buyer_location = { postal_code: params[:postal_code], country: params[:country], state: params[:state], ip_address: request.remote_ip }
buyer_vat_id = params[:vat_id].presence
from_discover = recommended_by.present?
end
shipping_destination = ShippingDestination.for_product_and_country_code(product:, country_code: params[:country])
shipping_rate = shipping_destination&.calculate_shipping_rate(quantity:) || 0
sales_tax_result = SalesTaxCalculator.new(product:,
price_cents: price,
shipping_cents: shipping_rate,
quantity:,
buyer_location:,
buyer_vat_id:,
from_discover:).calculate
{ sales_tax_result:, shipping_rate: }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/communities_controller.rb | app/controllers/communities_controller.rb | # frozen_string_literal: true
class CommunitiesController < ApplicationController
before_action :authenticate_user!
after_action :verify_authorized
before_action :set_body_id_as_app
def index
@hide_layouts = true
authorize Community
end
private
def set_title
@title = "Communities"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/wishlists_controller.rb | app/controllers/wishlists_controller.rb | # frozen_string_literal: true
class WishlistsController < ApplicationController
include CustomDomainConfig, DiscoverCuratedProducts
before_action :authenticate_user!, except: :show
after_action :verify_authorized, except: :show
layout "inertia", only: [:index, :show]
def index
authorize Wishlist
respond_to do |format|
format.html do
@title = Feature.active?(:follow_wishlists, current_seller) ? "Saved" : "Wishlists"
wishlists_props = WishlistPresenter.library_props(wishlists: current_seller.wishlists.alive)
render inertia: "Wishlists/Index", props: {
wishlists: wishlists_props,
reviews_page_enabled: Feature.active?(:reviews_page, current_seller),
following_wishlists_enabled: Feature.active?(:follow_wishlists, current_seller),
}
end
format.json do
wishlists = current_seller.wishlists.alive.includes(:products).by_external_ids(params[:ids])
render json: WishlistPresenter.cards_props(wishlists:, pundit_user:, layout: Product::Layout::PROFILE)
end
end
end
def create
authorize Wishlist
wishlist = current_seller.wishlists.new(params.require(:wishlist).permit(:name))
respond_to do |format|
if wishlist.save
format.html { redirect_to wishlists_path, notice: "Wishlist created!", status: :see_other }
format.json { render json: { wishlist: WishlistPresenter.new(wishlist:).listing_props }, status: :created }
else
format.html { redirect_to wishlists_path, inertia: { errors: { base: wishlist.errors.full_messages } }, status: :see_other }
format.json { render json: { error: wishlist.errors.full_messages.first }, status: :unprocessable_entity }
end
end
end
def show
wishlist = user_by_domain(request.host).wishlists.alive.find_by_url_slug(params[:id])
e404 if wishlist.blank?
@user = wishlist.user
@title = wishlist.name
@show_user_favicon = true
layout = params[:layout]
props = WishlistPresenter.new(wishlist:).public_props(
request:,
pundit_user:,
recommended_by: params[:recommended_by],
layout:,
taxonomies_for_nav:
)
render inertia: "Wishlists/Show", props:
end
def update
wishlist = current_seller.wishlists.alive.find_by_external_id!(params[:id])
authorize wishlist
if wishlist.update(params.require(:wishlist).permit(:name, :description, :discover_opted_out))
redirect_to wishlists_path, notice: "Wishlist updated!", status: :see_other
else
redirect_to wishlists_path,
inertia: { errors: { base: wishlist.errors.full_messages } },
status: :see_other
end
end
def destroy
wishlist = current_seller.wishlists.alive.find_by_external_id!(params[:id])
authorize wishlist
wishlist.transaction do
wishlist.mark_deleted!
wishlist.wishlist_followers.alive.update_all(deleted_at: Time.current)
end
redirect_to wishlists_path, notice: "Wishlist deleted!", status: :see_other
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/confirmations_controller.rb | app/controllers/confirmations_controller.rb | # frozen_string_literal: true
class ConfirmationsController < Devise::ConfirmationsController
def show
@user = User.find_or_initialize_with_error_by(:confirmation_token, params[:confirmation_token])
if @user.errors.present?
flash[:alert] = "You have already been confirmed."
return redirect_to root_url
end
if @user.confirm
sign_in @user
logged_in_user.reload
invalidate_active_sessions_except_the_current_session!
flash[:notice] = "Your account has been successfully confirmed!"
redirect_to after_confirmation_path_for(:user, @user)
else
redirect_to root_url
end
end
def after_confirmation_path_for(_resource_name, user)
helpers.signed_in_user_home(user)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/audience_controller.rb | app/controllers/audience_controller.rb | # frozen_string_literal: true
class AudienceController < Sellers::BaseController
before_action :set_time_range, only: :index
after_action :set_dashboard_preference_to_audience, only: :index
before_action :check_payment_details, only: :index
layout "inertia", only: :index
def index
authorize :audience
total_follower_count = current_seller.audience_members.where(follower: true).count
render inertia: "Audience/Index", props: {
total_follower_count: InertiaRails.always { total_follower_count },
audience_data: InertiaRails.defer do
if total_follower_count.zero?
nil
else
CreatorAnalytics::Following.new(current_seller).by_date(
start_date: @start_date.to_date,
end_date: @end_date.to_date
)
end
end
}
end
def export
authorize :audience
options = params.required(:options)
.permit(:followers, :customers, :affiliates)
.to_hash
Exports::AudienceExportWorker.perform_async(current_seller.id, (impersonating_user || current_seller).id, options)
head :ok
end
protected
def set_time_range
begin
end_date = DateTime.parse(params[:to])
start_date = DateTime.parse(params[:from])
end_date = start_date if end_date < start_date
rescue StandardError
end_date = DateTime.current
start_date = end_date.ago(29.days)
end
@start_date = start_date
@end_date = end_date
end
def set_title
@title = "Analytics"
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/application_controller.rb | app/controllers/application_controller.rb | # frozen_string_literal: true
class ApplicationController < ActionController::Base
protect_from_forgery
include LoggedInUser
include PunditAuthorization
include AffiliateQueryParams
include Events
include LogrageHelper
include DashboardPreference
include CustomDomainRouteBuilder
include CsrfTokenInjector
include TwoFactorAuthenticationValidator
include Impersonate
include CurrentSeller
include HelperWidget
include UtmLinkTracking
include RackMiniProfilerAuthorization
include InertiaRendering
before_action :debug_headers
before_action :set_is_mobile
before_action :set_title
before_action :invalidate_session_if_necessary
before_action :redirect_to_custom_subdomain
before_action :set_signup_referrer, if: -> { logged_in_user.nil? }
before_action :check_suspended, if: -> { logged_in_user.present? && logged_in_user.suspended? }
before_bugsnag_notify :add_user_to_bugsnag
BUGSNAG_USER_FIELDS = %i[id email username name created_at locale]
before_action :set_gumroad_guid
before_action :set_paper_trail_whodunnit
before_action :set_recommender_model_name
before_action :track_utm_link_visit
add_flash_types :warning
def redirect_to_next
safe_redirect_to(params[:next])
end
def safe_redirect_path(path, allow_subdomain_host: true)
SafeRedirectPathService.new(path, request, allow_subdomain_host:).process
end
def safe_redirect_to(path)
redirect_to safe_redirect_path(path), allow_other_host: true
end
def default_url_options(options = {})
if DiscoverDomainConstraint.matches?(request)
options.merge(host: DOMAIN, protocol: PROTOCOL)
else
options.merge(host: request.host, protocol: PROTOCOL)
end
end
def is_bot?
ua = request.user_agent
return false if ua.nil?
BOT_MAP.include?(ua) || ["msnbot", "yahoo! slurp", "googlebot", "whatsapp"].any? { |bot| ua.downcase.include?(bot) } || params[:user_agent_bot].present?
end
def set_is_mobile
@is_mobile = is_mobile?
end
def is_mobile?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent.present? && request.user_agent.match(/Mobile|webOS/).present?
end
end
def set_purchase
@purchase = Purchase.find_by_external_id(params[:purchase_id] || params[:id]) || e404
end
# Fetches a product owned by current user and identified by a unique permalink
def fetch_product_and_enforce_ownership
unique_permalink = params[:link_id] || params[:id]
@product = Link.fetch(unique_permalink, user: current_seller) || e404
end
# Fetches a product identified by a unique permalink and ensures the current user owns or collaborates on it
def fetch_product_and_enforce_access
unique_permalink = params[:link_id] || params[:id]
@product = Link.fetch(unique_permalink)
e404 unless @product.present? && (@product.user == current_seller || logged_in_user.collaborator_for?(@product))
end
# Fetches a product identified by a unique permalink
def fetch_product
unique_permalink = params[:id] || params[:link_id]
@product = Link.fetch(unique_permalink) || e404
end
rescue_from ActionView::MissingTemplate do |_exception|
e404
end
def e404_page
e404
end
protected
def request_referrer_is_not_root_route?
request.referrer != root_path && request.referrer != root_url
end
def request_referrer_is_not_sign_up_route?
request.referrer != signup_path && request.referrer != signup_url
end
def request_referrer_is_not_login_route?
!request.referrer.start_with?(login_url) && !request.referrer.start_with?(login_path)
end
def request_referrer_is_not_two_factor_authentication_path?
!request.referrer.start_with?(two_factor_authentication_url)
end
def request_referrer_is_a_valid_after_login_path?
request.referrer.present? &&
request_referrer_is_not_root_route? &&
request_referrer_is_not_sign_up_route? &&
request_referrer_is_not_login_route? &&
request_referrer_is_not_two_factor_authentication_path?
end
private
def redirect_to_custom_subdomain
redirect_url = SubdomainRedirectorService.new.redirect_url_for(request)
redirect_to(redirect_url, allow_other_host: true) if redirect_url.present?
end
def debug_headers
headers["X-Revision"] = REVISION
headers["X-GR"] = GR_NUM
end
def authenticate_user!
return if user_signed_in?
if %i[json js].include?(request.format.symbol)
e404_json
else
redirect_to login_path(next: request.fullpath)
end
end
# Returns to redirect after successful login
def after_sign_in_path_for(_resource_or_scope)
request.env["omniauth.origin"] || safe_redirect_path(helpers.signed_in_user_home(logged_in_user, next_url: params[:next]), allow_subdomain_host: false)
end
def merge_guest_cart_with_user_cart
return unless user_signed_in?
browser_guid = cookies[:_gumroad_guid]
guest_cart = Cart.fetch_by(user: nil, browser_guid:)
if guest_cart&.alive_cart_products&.any?
MergeCartsService.new(
source_cart: guest_cart,
target_cart: logged_in_user.alive_cart,
user: logged_in_user,
browser_guid:
).process
end
end
def sign_in_or_prepare_for_two_factor_auth(user)
if skip_two_factor_authentication?(user)
sign_in user
reset_two_factor_auth_login_session
merge_guest_cart_with_user_cart
else
prepare_for_two_factor_authentication(user)
end
end
def login_path_for(user)
next_path = params[:next]
final_path = if next_path.present?
CGI.unescape(next_path)
elsif request_referrer_is_a_valid_after_login_path?
request.referrer
else
helpers.signed_in_user_home(user)
end
safe_final_path = safe_redirect_path(final_path)
# Return URL if it's a 2FA verification link with token (login link navigated from 2FA email)
if safe_final_path.start_with?(verify_two_factor_authentication_path(format: :html))
return safe_final_path
end
if user_for_two_factor_authentication.present?
two_factor_authentication_path(next: safe_final_path)
else
safe_final_path
end
end
# Url to visit after logout is referrer or homepage
def after_sign_out_path_for(_resource_or_scope)
ref = request.referrer
ref.nil? ? "/" : ref
end
# 404 helper
def e404
raise ActionController::RoutingError, "Not Found"
end
def e404_json
render(json: { success: false, error: "Not found" }, status: :not_found)
end
def e404_xml
render(xml: { success: false, error: "Not found" }.to_xml(root: "response"), status: :not_found)
end
def invalidate_session_if_necessary
return if self.class.name == "LoginsController"
return unless request.env["warden"].authenticated?
return if logged_in_user.nil?
return if logged_in_user.last_active_sessions_invalidated_at.nil?
last_sign_in_at = request.env["warden"].session["last_sign_in_at"]
return if last_sign_in_at && last_sign_in_at.to_i >= logged_in_user.last_active_sessions_invalidated_at.to_i
sign_out
flash[:warning] = "We're sorry; you have been logged out. Please login again."
redirect_to login_path
end
def check_suspended
return nil if request.path.in?([balance_path, settings_main_path]) || params[:controller] == "payouts"
return head(:ok) if !request.format.html? && !request.format.json?
respond_to do |format|
format.html do
flash[:warning] = "You can't perform this action because your account has been suspended."
redirect_to root_path unless request.path == root_path
end
format.json { render json: { success: false, error_message: "You can't perform this action because your account has been suspended." } }
end
end
def hide_layouts
@hide_layouts = true
end
def add_user_to_bugsnag(event)
# We can't test a real execution of this method because Bugsnag won't call it in the test environment.
# The following line protects the app in case the internal API changes and `event.user` changes type.
# In this situation, the user will not be reported anymore, which the team will notice and fix.
return unless event.respond_to?(:user) && event.respond_to?(:user=) && event.user.is_a?(Hash)
# The "User" tab gets automatically filled by Bugsnag,
# however it doesn't support `current_resource_owner`, so we need to overwrite it in all cases.
user = logged_in_user
user ||= current_resource_owner if respond_to?(:current_resource_owner)
return unless user
event.user ||= {}
BUGSNAG_USER_FIELDS.each do |field|
event.user[field] = user.public_send(field)
end
end
def set_title
@title = "Gumroad"
@title = "Staging Gumroad" if Rails.env.staging?
@title = "Local Gumroad" if Rails.env.development?
end
def set_signup_referrer
return if session[:signup_referrer].present?
return if params[:_sref].nil? && request.referrer.nil?
if params[:_sref].present?
session[:signup_referrer] = params[:_sref]
else
uri = URI.parse(request.referrer) rescue nil
session[:signup_referrer] = uri.host.downcase if uri && uri.host.present? && !uri.host.ends_with?(ROOT_DOMAIN)
end
end
def set_body_id_as_app
@body_id = "app"
end
def set_as_modal
@as_modal = params[:as_modal] == "true"
end
def set_frontend_performance_sensitive
@is_css_performance_sensitive = true
end
def set_gumroad_guid
return unless cookies[:_gumroad_guid].nil?
cookies[:_gumroad_guid] = {
value: SecureRandom.uuid,
expires: 10.years.from_now,
domain: :all,
httponly: true
}
end
def set_noindex_header
headers["X-Robots-Tag"] = "noindex"
end
def info_for_paper_trail
{
remote_ip: request.remote_ip,
request_path: request.path,
request_uuid: request.uuid,
}
end
def check_payment_details
return unless current_seller
return unless $redis.sismember(RedisKey.user_ids_with_payment_requirements_key, current_seller.id)
merchant_account = current_seller.merchant_accounts.alive.stripe.last
return unless merchant_account
if current_seller.user_compliance_info_requests.requested.present?
redirect_to settings_payments_path, notice: "Urgent: We are required to collect more information from you to continue processing payments." and return
end
stripe_account = Stripe::Account.retrieve(merchant_account.charge_processor_merchant_id)
if (StripeMerchantAccountManager::REQUESTED_CAPABILITIES & stripe_account.capabilities.to_h.stringify_keys.select { |k, v| v == "active" }.keys).size == 2
$redis.srem(RedisKey.user_ids_with_payment_requirements_key, current_seller.id)
else
redirect_to settings_payments_path, notice: "Urgent: We are required to collect more information from you to continue processing payments." and return
end
end
def fetch_affiliate(product, product_params = nil)
affiliate_from_cookies(product) || affiliate_from_params(product, product_params || params)
end
def affiliate_from_cookies(product)
# 1. Fetch all users have an affiliate cookie set, sorted by affiliate cookie recency
affiliates_from_cookies = Affiliate.by_cookies(cookies)
affiliate_user_ids = affiliates_from_cookies.map(&:affiliate_user_id).uniq
if affiliate_user_ids.present?
# 2. Fetch those users' direct affiliate records that apply to this product
affiliate_user_id_string = affiliate_user_ids.map { |id| ActiveRecord::Base.connection.quote(id) }.join(",")
direct_affiliates_for_product_and_user = Affiliate.valid_for_product(product).direct_affiliates.where(affiliate_user_id: affiliate_user_ids).order(Arel.sql("FIELD(affiliate_user_id, #{affiliate_user_id_string})"))
# 3. Exclude direct affiliates where the affiliate didn't have a cookie set for that seller & return the first eligible affiliate
newest_affiliate = direct_affiliates_for_product_and_user.find do |affiliate|
affiliates_from_cookies.any? { |a| a.affiliate_user_id == affiliate.affiliate_user_id && (a.global? || a.seller_id == affiliate.seller_id) }
end
# 4. Fall back to first eligible affiliate with cookie is set if no direct affiliates are present
newest_affiliate || affiliates_from_cookies.find { |a| a.eligible_for_purchase_credit?(product:) }
end
end
# Since Safari doesn't allow setting third-party cookies by default
# (reference: https://github.com/gumroad/web/pull/17775#issuecomment-815047658),
# the 'affiliate_id' cookie doesn't persist in the user's browser for
# the affiliate product URLs served using the overlay and embed widgets.
# To overcome this issue, as a fallback approach, we automatically pass
# the 'affiliate_id' or 'a' param (retrieved from the affiliate product's URL)
# as a parameter in the request payload of the 'POST /purchases' request.
def affiliate_from_params(product, product_params)
affiliate_id = product_params[:affiliate_id].to_i
return if affiliate_id.zero?
Affiliate.valid_for_product(product).find_by_external_id_numeric(affiliate_id)
end
def invalidate_active_sessions_except_the_current_session!
return unless user_signed_in?
logged_in_user.invalidate_active_sessions!
# NOTE: To keep the current session active, we reset the
# "last_sign_in_at" value persisted in the current session with
# a newer timestamp. This is exactly similar to and should match
# with the implementation of the "after_set_user" hook we have defined
# in the "devise_hooks.rb" initializer.
request.env["warden"].session["last_sign_in_at"] = DateTime.current.to_i
end
def strip_timestamp_location(timestamp)
return if timestamp.nil?
timestamp.gsub(/([^(]+).*/, '\1').strip
end
def set_recommender_model_name
session[:recommender_model_name] = RecommendedProductsService::MODELS.sample unless RecommendedProductsService::MODELS.include?(session[:recommender_model_name])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/offer_codes_controller.rb | app/controllers/offer_codes_controller.rb | # frozen_string_literal: true
class OfferCodesController < ApplicationController
def compute_discount
response = OfferCodeDiscountComputingService.new(params[:code], params[:products]).process
response = if response[:error_code].present?
error_message = case response.fetch(:error_code)
when :insufficient_times_of_use
"Sorry, the discount code you are using is invalid for the quantity you have selected."
when :sold_out
"Sorry, the discount code you wish to use has expired."
when :invalid_offer
"Sorry, the discount code you wish to use is invalid."
when :inactive
"Sorry, the discount code you wish to use is inactive."
when :unmet_minimum_purchase_quantity
"Sorry, the discount code you wish to use has an unmet minimum quantity."
end
{ valid: false, error_code: response[:error_code], error_message: }
else
{ valid: true, products_data: response[:products_data].transform_values { _1[:discount] } }
end
render json: response
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/workflows_controller.rb | app/controllers/workflows_controller.rb | # frozen_string_literal: true
class WorkflowsController < Sellers::BaseController
before_action :set_workflow, only: %i[edit update destroy]
before_action :authorize_workflow, only: %i[edit update destroy]
before_action :fetch_product_and_enforce_ownership, only: %i[create update], if: :product_or_variant_workflow?
layout "inertia"
FLASH_CHANGES_SAVED = "Changes saved!"
FLASH_WORKFLOW_PUBLISHED = "Workflow published!"
FLASH_WORKFLOW_UNPUBLISHED = "Unpublished!"
FLASH_WORKFLOW_DELETED = "Workflow deleted!"
def index
authorize Workflow
create_user_event("workflows_view")
workflows_presenter = WorkflowsPresenter.new(seller: current_seller)
render inertia: "Workflows/Index", props: workflows_presenter.workflows_props
end
def new
authorize Workflow
workflow_presenter = WorkflowPresenter.new(seller: current_seller)
render inertia: "Workflows/New", props: {
context: -> { workflow_presenter.workflow_form_context_props }
}
end
def create
authorize Workflow
service = Workflow::ManageService.new(seller: current_seller, params: workflow_params, product: @product, workflow: nil)
success, errors = service.process
if success
redirect_to workflow_emails_path(service.workflow.external_id), notice: FLASH_CHANGES_SAVED, status: :see_other
else
redirect_to new_workflow_path, inertia: { errors: errors }
end
end
def edit
workflow_presenter = WorkflowPresenter.new(seller: current_seller, workflow: @workflow)
render inertia: "Workflows/Edit", props: {
workflow: -> { workflow_presenter.workflow_props },
context: -> { workflow_presenter.workflow_form_context_props }
}
end
def update
service = Workflow::ManageService.new(seller: current_seller, params: workflow_params, product: @product, workflow: @workflow)
success, errors = service.process
if success
notice_message = case workflow_params[:save_action_name]
when "save_and_publish"
FLASH_WORKFLOW_PUBLISHED
when "save_and_unpublish"
FLASH_WORKFLOW_UNPUBLISHED
else
FLASH_CHANGES_SAVED
end
redirect_to workflow_emails_path(@workflow.external_id), notice: notice_message, status: :see_other
else
redirect_to edit_workflow_path(@workflow.external_id), inertia: { errors: { base: [errors] } }, alert: errors
end
end
def destroy
@workflow.mark_deleted!
redirect_to workflows_path, notice: FLASH_WORKFLOW_DELETED, status: :see_other
end
private
def set_title
@title = "Workflows"
end
def set_workflow
@workflow = current_seller.workflows.find_by_external_id(params[:id])
return e404 unless @workflow
e404 if @workflow.product_or_variant_type? && @workflow.link.user != current_seller
end
def authorize_workflow
authorize @workflow
end
def product_or_variant_workflow?
[Workflow::PRODUCT_TYPE, Workflow::VARIANT_TYPE].include?(workflow_params[:workflow_type])
end
def fetch_product_and_enforce_ownership
# Override parent method to handle workflow params structure
permalink = workflow_params[:permalink]
@product = current_seller.products.visible.find_by(unique_permalink: permalink) ||
current_seller.products.visible.find_by(custom_permalink: permalink) ||
e404
end
def workflow_params
params.require(:workflow).permit(
:name, :workflow_type, :variant_external_id, :workflow_trigger,
:paid_more_than, :paid_less_than, :bought_from,
:created_after, :created_before, :permalink,
:send_to_past_customers, :save_action_name,
bought_products: [], not_bought_products: [], affiliate_products: [],
bought_variants: [], not_bought_variants: [],
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/acme_challenges_controller.rb | app/controllers/acme_challenges_controller.rb | # frozen_string_literal: true
class AcmeChallengesController < ApplicationController
MAX_TOKEN_LENGTH = 64
VALID_TOKEN_PATTERN = /\A[A-Za-z0-9_-]+\z/
def show
token = params[:token]
Rails.logger.info "[ACME Challenge] Verification request received for token: #{mask_token(token)}, host: #{request.host}"
unless valid_token?(token)
head :bad_request
return
end
content = $redis.get(RedisKey.acme_challenge(token))
if content.present?
render plain: content
else
head :not_found
end
end
private
def mask_token(token)
return "nil" if token.blank?
return token if token.length <= 4
"#{token[0..1]}...#{token[-2..]}"
end
def valid_token?(token)
token.present? && token.length <= MAX_TOKEN_LENGTH && token.match?(VALID_TOKEN_PATTERN)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/foreign_webhooks_controller.rb | app/controllers/foreign_webhooks_controller.rb | # frozen_string_literal: true
class ForeignWebhooksController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :validate_sns_webhook, only: [:mediaconvert]
before_action only: [:stripe] do
endpoint_secret = GlobalConfig.dig(:stripe, :endpoint_secret)
validate_stripe_webhook(endpoint_secret)
end
before_action only: [:stripe_connect] do
endpoint_secret = GlobalConfig.dig(:stripe_connect, :endpoint_secret)
validate_stripe_webhook(endpoint_secret)
end
before_action only: [:resend] do
endpoint_secret = GlobalConfig.get("RESEND_WEBHOOK_SECRET")
validate_resend_webhook(endpoint_secret)
end
def stripe
if @stripe_event["id"]
HandleStripeEventWorker.perform_async(@stripe_event.as_json)
render json: { success: true }
else
render json: { success: false }
end
end
def stripe_connect
if @stripe_event["id"].present? && (@stripe_event["account"].present? || @stripe_event["user_id"].present?)
HandleStripeEventWorker.perform_async(@stripe_event.as_json)
render json: { success: true }
else
render json: { success: false }
end
end
def paypal
payload = params.to_unsafe_hash.except(:controller, :action).to_hash
PaypalEventHandler.new(payload).schedule_paypal_event_processing
render json: { success: true }
end
def sendgrid
HandleSendgridEventJob.perform_async(params.to_unsafe_hash.to_hash)
LogSendgridEventWorker.perform_async(params.to_unsafe_hash.to_hash)
render json: { success: true }
end
def resend
HandleResendEventJob.perform_async(params.to_unsafe_hash.to_hash)
LogResendEventJob.perform_async(params.to_unsafe_hash.to_hash)
render json: { success: true }
end
def sns
# The SNS post has json body but the content-type is set to plain text.
notification_message = request.body.read
Rails.logger.info("Incoming SNS (Transcoder): #{notification_message}")
# TODO(amir): remove this once elastic transcoder support gets back to us about why it's included and causing the json to be invalid.
Rails.logger.info("Incoming SNS from Elastic Transcoder contains the invalid characters? #{notification_message.include?('#012')}")
notification_message.gsub!("#012", "")
HandleSnsTranscoderEventWorker.perform_in(5.seconds, JSON.parse(notification_message))
head :ok
end
def mediaconvert
notification = JSON.parse(request.raw_post)
Rails.logger.info "Incoming SNS (MediaConvert): #{notification}"
HandleSnsMediaconvertEventWorker.perform_in(5.seconds, notification)
head :ok
end
def sns_aws_config
notification = request.body.read
Rails.logger.info("Incoming SNS (AWS Config): #{notification}")
HandleSnsAwsConfigEventWorker.perform_async(JSON.parse(notification))
head :ok
end
private
def validate_sns_webhook
return if Aws::SNS::MessageVerifier.new.authentic?(request.raw_post)
render json: { success: false }, status: :bad_request
end
def validate_stripe_webhook(endpoint_secret)
payload = request.raw_post
sig_header = request.env["HTTP_STRIPE_SIGNATURE"]
begin
@stripe_event = Stripe::Webhook.construct_event(
payload, sig_header, endpoint_secret
)
rescue JSON::ParserError
# Invalid payload
render json: { success: false }, status: :bad_request
rescue Stripe::SignatureVerificationError
# Invalid signature
render json: { success: false }, status: :bad_request
end
end
def validate_resend_webhook(secret)
payload = request.body.read
signature_header = request.headers["svix-signature"]
timestamp = request.headers["svix-timestamp"]
message_id = request.headers["svix-id"]
raise "Missing signature" if signature_header.blank?
raise "Missing timestamp" if timestamp.blank?
raise "Missing message ID" if message_id.blank?
# Verify timestamp is within 5 minutes
timestamp_dt = Time.at(timestamp.to_i)
if (Time.current.utc - timestamp_dt).abs > 5.minutes
raise "Timestamp too old"
end
# Parse signature header (format: "v1,<signature>")
_, signature = signature_header.split(",", 2)
raise "Invalid signature format" if signature.blank?
# Get the base64 portion after whsec_ and decode it
secret_bytes = Base64.decode64(secret.split("_", 2).last)
# Calculate HMAC using SHA256
signed_payload = "#{message_id}.#{timestamp}.#{payload}"
expected = Base64.strict_encode64(
OpenSSL::HMAC.digest("SHA256", secret_bytes, signed_payload)
)
# Compare signatures using secure comparison
raise "Invalid signature" unless ActiveSupport::SecurityUtils.secure_compare(signature, expected)
rescue => e
Bugsnag.notify("Error verifying Resend webhook: #{e.message}")
render json: { success: false }, status: :bad_request
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/events.rb | app/controllers/concerns/events.rb | # frozen_string_literal: true
module Events
def create_user_event(name, seller_id: nil, on_custom_domain: false)
return if name.nil?
create_event(
event_name: name,
on_custom_domain:,
user_id: logged_in_user&.id
)
end
def create_post_event(installment)
@product = installment.try(:link)
event = create_event(
event_name: Event::NAME_POST_VIEW,
user_id: logged_in_user&.id
)
installment_event = InstallmentEvent.new
installment_event.installment_id = installment.id
installment_event.event_id = event.id
installment_event.save!
end
def create_purchase_event(purchase)
create_event(
billing_zip: purchase.zip_code,
card_type: purchase.card_type,
card_visual: purchase.card_visual,
event_name: Event::NAME_PURCHASE,
price_cents: purchase.price_cents,
purchase_id: purchase.id,
link_id: purchase.link.id,
purchase_state: purchase.purchase_state,
was_product_recommended: purchase.was_product_recommended?,
referrer: purchase.referrer
)
end
def create_service_charge_event(service_charge)
create_event(
billing_zip: service_charge.card_zip_code,
card_type: service_charge.card_type,
card_visual: service_charge.card_visual,
event_name: Event::NAME_SERVICE_CHARGE,
price_cents: service_charge.charge_cents,
service_charge_id: service_charge.id,
purchase_state: service_charge.state
)
end
private
def create_event(args)
return if impersonating?
event_class = case args[:event_name]
when "signup"
SignupEvent
else
Event
end
return if event_class == Event && Event::PERMITTED_NAMES.exclude?(args[:event_name]) && args[:user_id].nil?
geo = GeoIp.lookup(request.remote_ip)
referrer = args[:referrer] || Array.wrap(params[:referrer]).select(&:present?).last || request.referrer
referrer = referrer.encode(Encoding.find("ASCII"), invalid: :replace, undef: :replace, replace: "") if referrer.present?
referrer = referrer[0..190] if referrer.present?
event = event_class.new
event_params = {
browser: request.env["HTTP_USER_AGENT"],
browser_fingerprint: Digest::MD5.hexdigest([request.env["HTTP_USER_AGENT"], params[:plugins]].join(",")),
browser_guid: cookies[:_gumroad_guid],
extra_features: (args.delete(:extra_features) || {}).merge(
browser: request.env["HTTP_USER_AGENT"],
browser_plugins: params[:plugins],
friend_actions: params[:friend],
language: request.env["HTTP_ACCEPT_LANGUAGE"],
source: params[:source],
window_location: params[:window_location]
),
from_multi_overlay: params[:from_multi_overlay],
from_seo: seo_referrer?(session[:signup_referrer]),
ip_address: request.remote_ip,
ip_country: geo.try(:country_name),
ip_state: geo.try(:region_name),
ip_latitude: geo.try(:latitude).to_f,
ip_longitude: geo.try(:longitude).to_f,
is_mobile: is_mobile?,
is_modal: params[:is_modal],
link_id: @product.try(:id),
parent_referrer: params[:parent_referrer],
price_cents: @product.try(:price_cents),
referrer:,
referrer_domain: Referrer.extract_domain(referrer),
view_url: params[:view_url] || request.env["PATH_INFO"],
was_product_recommended: params[:was_product_recommended]
}.merge(args)
event_params.keys.each do |param|
event_params.delete(param) unless event.respond_to?("#{param}=")
end
event.attributes = event_params
if event.try(:was_product_recommended) && event.respond_to?(:referrer_domain=)
event.referrer_domain = REFERRER_DOMAIN_FOR_GUMROAD_RECOMMENDED_PRODUCTS
end
event.save!
event
end
def seo_referrer?(referrer_domain)
return unless referrer_domain.present?
# Match end part of SEO domains (ie. google.com, www.google.com, yandex.ru, r.search.yahoo.com)
referrer_domain.match?(/(google|bing|yahoo|yandex|duckduckgo)(\.[a-z]{2,3})(\.[a-z]{2})?$/i)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/current_api_user.rb | app/controllers/concerns/current_api_user.rb | # frozen_string_literal: true
# Equivalent of current_user for API
#
module CurrentApiUser
extend ActiveSupport::Concern
included do
helper_method :current_api_user
end
def current_api_user
return unless defined?(doorkeeper_token) && doorkeeper_token.present?
@_current_api_user ||= User.find(doorkeeper_token.resource_owner_id)
rescue ActionDispatch::Http::Parameters::ParseError
@_current_api_user = nil
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/fetch_product_by_unique_permalink.rb | app/controllers/concerns/fetch_product_by_unique_permalink.rb | # frozen_string_literal: true
module FetchProductByUniquePermalink
# Fetches a product by unique permalink (only!) identified via `id` or `link_id` params.
# Requires the product's owner or an admin user to be logged in.
#
# This method shouldn't be used to fetch a product by custom_permalink because they are not
# globally unique and if it's admin user accessing the page, we can't be sure which
# creator's product should be shown.
def fetch_product_by_unique_permalink
unique_permalink = params[:id] || params[:link_id] || params[:product_id]
e404 if unique_permalink.blank?
@product = Link.find_by(unique_permalink:) || e404
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/impersonate.rb | app/controllers/concerns/impersonate.rb | # frozen_string_literal: true
# Handles impersonation for both web and mobile API
module Impersonate
extend ActiveSupport::Concern
include CurrentApiUser
include LoggedInUser
included do
helper_method :impersonating_user, :impersonated_user, :impersonating?
end
def impersonate_user(user)
reset_impersonated_user
$redis.set(RedisKey.impersonated_user(current_user_from_api_or_web.id), user.id, ex: 7.days.to_i)
end
def stop_impersonating_user
reset_impersonated_user
end
def impersonated_user
return @_impersonated_user if defined?(@_impersonated_user)
# Short-circuit to avoid a Redis query for non-team members
# Note that if a team member becomes a non-team member while impersonating, the Redis key associated will stick
# around until expiration
return unless can_impersonate?
@_impersonated_user = find_impersonated_user_from_redis
end
def find_impersonated_user_from_redis
impersonated_user_id = $redis.get(RedisKey.impersonated_user(current_user_from_api_or_web.id))
return if impersonated_user_id.nil?
user = User.alive.find(impersonated_user_id)
user if user.account_active?
rescue ActiveRecord::RecordNotFound
nil
end
def impersonating?
impersonated_user.present?
end
# Useful to direct emails that would normally go to the impersonated user, to the admin user instead.
def impersonating_user
current_user_from_api_or_web if impersonating?
end
private
def current_user_from_api_or_web
current_api_user || current_user
end
def can_impersonate? = current_user_from_api_or_web&.is_team_member?
def reset_impersonated_user
$redis.del(RedisKey.impersonated_user(current_user_from_api_or_web.id))
remove_instance_variable(:@_impersonated_user) if defined?(@_impersonated_user)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/create_consumption_event.rb | app/controllers/concerns/create_consumption_event.rb | # frozen_string_literal: true
module CreateConsumptionEvent
private
def create_consumption_event!(params)
return false if params[:url_redirect_id].blank? || ConsumptionEvent::EVENT_TYPES.exclude?(params[:event_type])
url_redirect_id = ObfuscateIds.decrypt(params[:url_redirect_id])
product_file_id = ObfuscateIds.decrypt(params[:product_file_id]) if params[:product_file_id].present?
purchase_id = params[:purchase_id].present? ? ObfuscateIds.decrypt(params[:purchase_id]) : UrlRedirect.find(url_redirect_id)&.purchase_id
product_id = Purchase.find_by(id: purchase_id)&.link_id
consumed_at = params[:consumed_at].present? ? Time.zone.parse(params[:consumed_at]) : Time.current
ConsumptionEvent.create_event!(
event_type: params[:event_type],
platform: params[:platform],
url_redirect_id:,
product_file_id:,
purchase_id:,
product_id:,
consumed_at:,
ip_address: request.remote_ip,
)
true
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.