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/controllers/concerns/csrf_token_injector.rb
app/controllers/concerns/csrf_token_injector.rb
# frozen_string_literal: true module CsrfTokenInjector extend ActiveSupport::Concern TOKEN_PLACEHOLDER = "_CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__" SAFE_INSERTION_SELECTOR = /(<meta\s+name=["']csrf-token["']\s+content=["'])#{Regexp.escape(TOKEN_PLACEHOLDER)}(["'])/i def rewrite_csrf_token(html, token) return html unless html html.gsub(SAFE_INSERTION_SELECTOR) { "#{$1}#{token}#{$2}" } end included do after_action :inject_csrf_token end def inject_csrf_token token = form_authenticity_token return if !protect_against_forgery? rewritten_body = rewrite_csrf_token(response.body, token) response.body = rewritten_body if rewritten_body != response.body end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/pundit_authorization.rb
app/controllers/concerns/pundit_authorization.rb
# frozen_string_literal: true module PunditAuthorization extend ActiveSupport::Concern include Pundit::Authorization included do rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized helper_method :pundit_user end def pundit_user @_pundit_user ||= SellerContext.new(user: logged_in_user, seller: current_seller) end private def user_not_authorized(exception) if exception.policy.class == LinkPolicy && exception.query == "edit?" product_edit_user_not_authorized(exception.record) elsif exception.policy.class == Settings::Main::UserPolicy && exception.query == "show?" settings_main_user_not_authorized else default_user_not_authorized(exception) end end def product_edit_user_not_authorized(product) # Sometimes sellers share the edit product link with their audience by accident. # For a better user experience redirect to the actual product page for a better user experience, rather than # displaying the _Not Authorized_ message redirect_to short_link_path(product) end def settings_main_user_not_authorized # This allows keeping the Nav link to settings_main_path, and redirect to the profile page for those roles # that don't have access to it # All roles have at least read-only access to the profile page redirect_to settings_profile_path end # It could happen for reasons like: # - a UI element allows the user to access a resource that is not authorized # - the user manually accessed a page for which is not authorized (i.e. /settings/password by non-owner) # These are not usual use cases of the app, so logging it to be notified there are bugs that need fixing. # Also, do not log and do not set a flash alert when the user is switching accounts, as this is a normal use case. # def default_user_not_authorized(exception) Rails.logger.warn(debug_message(exception)) unless params["account_switched"] message = build_error_message if request.format.json? || request.format.js? render json: { success: false, error: message }, status: :unauthorized else flash[:alert] = message unless params["account_switched"] redirect_to dashboard_url end end def build_error_message # Some policies (like CommentContextPolicy#index?) do not require the user to be authenticated return "You are not allowed to perform this action." if !user_signed_in? || logged_in_user.role_owner_for?(current_seller) team_membership = logged_in_user.find_user_membership_for_seller!(current_seller) "Your current role as #{team_membership.role.humanize} cannot perform this action." rescue ActiveRecord::RecordNotFound # This should not happen, but if it does, we want to be notified so we can fix it Bugsnag.notify("Team: Could not find membership for user #{logged_in_user.id} and seller #{current_seller.id}") "You are not allowed to perform this action." end def debug_message(exception) if user_signed_in? "Pundit::NotAuthorizedError for #{exception.policy.class} " \ "by User ID #{pundit_user.user.id} for Seller ID #{pundit_user.seller.id}: #{exception.message}" else "Pundit::NotAuthorizedError for #{exception.policy.class} by unauthenticated user: #{exception.message}" end 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_seller.rb
app/controllers/concerns/current_seller.rb
# frozen_string_literal: true module CurrentSeller extend ActiveSupport::Concern included do helper_method :current_seller before_action :verify_current_seller end def current_seller return unless user_signed_in? @_current_seller ||= find_seller_from_cookie(cookies.encrypted[:current_seller_id]) || reset_current_seller end def switch_seller_account(team_membership) team_membership.update!(last_accessed_at: Time.current) cookies.permanent.encrypted[:current_seller_id] = { value: team_membership.seller_id, domain: :all } end private def find_seller_from_cookie(seller_id) return if seller_id.nil? User.alive.find_by_id(seller_id) end def verify_current_seller # Do not destroy the cookie if the user is not signed in to remember last seller account selected return unless user_signed_in? reset_current_seller unless valid_seller?(current_seller) end def valid_seller?(seller) return false unless seller.present? return false unless logged_in_user.member_of?(seller) true end def reset_current_seller cookies.delete(:current_seller_id, domain: :all) # Change the seller for current request @_current_seller = logged_in_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/affiliate_query_params.rb
app/controllers/concerns/affiliate_query_params.rb
# frozen_string_literal: true module AffiliateQueryParams def fetch_affiliate_id(params) id = (params[:affiliate_id].presence || params[:a].presence).to_i id.zero? ? nil : id end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/oauth_application_config.rb
app/controllers/concerns/oauth_application_config.rb
# frozen_string_literal: true module OauthApplicationConfig extend ActiveSupport::Concern included do before_action :set_oauth_application, only: :new end def set_oauth_application return if params[:next].blank? begin next_url = URI.parse(params[:next]) rescue URI::InvalidURIError return redirect_to login_path end if next_url.query.present? application_uid = CGI.parse(next_url.query)["client_id"][0] @application = OauthApplication.alive.find_by(uid: application_uid) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/helper_widget.rb
app/controllers/concerns/helper_widget.rb
# frozen_string_literal: true module HelperWidget extend ActiveSupport::Concern included do helper_method :helper_widget_host, :helper_session end def helper_widget_host GlobalConfig.get("HELPER_WIDGET_HOST") end def helper_session return unless current_seller timestamp = (Time.current.to_f * 1000).to_i { email: current_seller.email, emailHash: helper_widget_email_hmac(timestamp), timestamp:, } end private def helper_widget_email_hmac(timestamp, email: nil) email ||= current_seller.email message = "#{email}:#{timestamp}" OpenSSL::HMAC.hexdigest( "sha256", GlobalConfig.get("HELPER_WIDGET_SECRET"), message ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/rack_mini_profiler_authorization.rb
app/controllers/concerns/rack_mini_profiler_authorization.rb
# frozen_string_literal: true module RackMiniProfilerAuthorization extend ActiveSupport::Concern included do before_action :authorize_rack_mini_profiler end private def authorize_rack_mini_profiler Rack::MiniProfiler.authorize_request if authorize_rack_mini_profiler? end def authorize_rack_mini_profiler? return true if Rails.env.development? current_user&.is_team_member? end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/two_factor_authentication_validator.rb
app/controllers/concerns/two_factor_authentication_validator.rb
# frozen_string_literal: true module TwoFactorAuthenticationValidator extend ActiveSupport::Concern TWO_FACTOR_AUTH_USER_ID_SESSION_NAME = :verify_two_factor_auth_for private_constant :TWO_FACTOR_AUTH_USER_ID_SESSION_NAME def skip_two_factor_authentication?(user) # Skip 2FA if it's not enabled for the user return true unless user.two_factor_authentication_enabled? # Return if the user has logged in via 2FA from this browser before if valid_two_factor_cookie_present?(user) # When a user regularly logs into the app from the same browser, automatically remember the 2FA status for the user for the next 2 months. # This is to reduce the number of 2FA challenges for the user from the same browser. set_two_factor_auth_cookie(user) return true end # Return if the user has logged in from a 2FA authenticated IP before. user.has_logged_in_from_ip_before?(request.remote_ip) end def prepare_for_two_factor_authentication(user) session[TWO_FACTOR_AUTH_USER_ID_SESSION_NAME] = user.id # Do not send token if it's already present in the next URL (navigated from email login login to an unauthenticated session) return if params[:next] && params[:next].include?(verify_two_factor_authentication_path(format: :html)) user.send_authentication_token! end def user_for_two_factor_authentication user_id = session[TWO_FACTOR_AUTH_USER_ID_SESSION_NAME] user_id.present? && User.find(user_id) end def reset_two_factor_auth_login_session session.delete(TWO_FACTOR_AUTH_USER_ID_SESSION_NAME) end def set_two_factor_auth_cookie(user) expires_at = User::TWO_FACTOR_AUTH_EXPIRY.from_now cookies.encrypted[user.two_factor_authentication_cookie_key] = { # Store both user.id and expires_at timestamp to make it unusable with other user accounts value: "#{user.id},#{expires_at.to_i}", expires: expires_at, httponly: true } end def remember_two_factor_auth set_two_factor_auth_cookie(logged_in_user) logged_in_user.add_two_factor_authenticated_ip!(request.remote_ip) end private def valid_two_factor_cookie_present?(user) cookie_value = cookies.encrypted[user.two_factor_authentication_cookie_key] return false if cookie_value.blank? # Check both user_id and timestamp from cookie value user_id, expires_timestamp = cookie_value.split(",").map(&:to_i) user_id == user.id && Time.zone.at(expires_timestamp) > Time.current end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/custom_domain_config.rb
app/controllers/concerns/custom_domain_config.rb
# frozen_string_literal: true module CustomDomainConfig def user_by_domain(host) user_by_subdomain(host) || user_by_custom_domain(host) end def set_user_and_custom_domain_config if GumroadDomainConstraint.matches?(request) set_user else set_user_by_domain @facebook_sdk_disabled = true @title = @user.try(:name_or_username) @body_class = "custom-domain" end end def product_by_custom_domain @_product_by_custom_domain ||= begin product = CustomDomain.find_by_host(request.host)&.product general_permalink = product&.general_permalink if general_permalink.blank? nil else Link.fetch_leniently(general_permalink, user: product.user) end end end def set_frontend_performance_sensitive @is_css_performance_sensitive = (logged_in_user != @user) end private def user_by_subdomain(host) @_user_by_subdomain ||= Subdomain.find_seller_by_hostname(host) end def user_by_custom_domain(host) CustomDomain.find_by_host(host).try(:user) end def set_user if params[:username] @user = User.find_by(username: params[:username]) || User.find_by(external_id: params[:username]) end error_if_user_not_found(@user) end def set_user_by_domain @user = user_by_domain(request.host) error_if_user_not_found(@user) end def error_if_user_not_found(user) unless user && user.account_active? && user.try(:username) respond_to do |format| format.html { e404 } format.json { return e404_json } format.xml { return e404_xml } format.any { e404 } end end 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_discover_search.rb
app/controllers/concerns/create_discover_search.rb
# frozen_string_literal: true module CreateDiscoverSearch def create_discover_search!(extras = {}) return if is_bot? return unless Feature.active?(:store_discover_searches, OpenStruct.new(flipper_id: cookies[:_gumroad_guid])) DiscoverSearch.transaction do search = DiscoverSearch.create!({ user: logged_in_user, ip_address: request.remote_ip, browser_guid: cookies[:_gumroad_guid], }.merge(extras)) search.create_discover_search_suggestion! if search.query.present? && !search.autocomplete end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/logged_in_user.rb
app/controllers/concerns/logged_in_user.rb
# frozen_string_literal: true module LoggedInUser extend ActiveSupport::Concern included do helper_method :logged_in_user end # Usage of current_user is restricted to ensure current_user is not used accidentaly instead of current_seller def logged_in_user impersonated_user || current_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/mass_transfer_purchases.rb
app/controllers/concerns/mass_transfer_purchases.rb
# frozen_string_literal: true module MassTransferPurchases extend ActiveSupport::Concern private def transfer_purchases(user:, new_email:) purchases = Purchase.where(email: user.email) error_message = if user.suspended? "Mass-transferring purchases for a suspended user is not allowed." elsif purchases.none? "User has no purchases." elsif new_email.blank? "Email can't be blank." elsif !EmailFormatValidator.valid?(new_email) "Invalid email format." end return { success: false, message: error_message, status: :unprocessable_entity } if error_message.present? user.transfer_purchases!(new_email:) { success: true, message: "Mass purchase transfer successful to email #{new_email}", status: :ok } rescue ActiveRecord::RecordNotFound error_message = "User with email #{new_email} does not exist." { success: false, message: error_message, status: :not_found } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/mass_blocker.rb
app/controllers/concerns/mass_blocker.rb
# frozen_string_literal: true module MassBlocker extend ActiveSupport::Concern # Records can be separated by whitespaces or commas DELIMITER_REGEX = /\s|,/ BATCH_SIZE = 1_000 private def schedule_mass_block(identifiers:, object_type:, expires_in: nil) array_of_mass_block_args = identifiers.split(DELIMITER_REGEX) .select(&:present?) .uniq .map { |identifier| [object_type, identifier, logged_in_user.id, expires_in].compact } array_of_mass_block_args.in_groups_of(BATCH_SIZE, false).each do |array_of_args| BlockObjectWorker.perform_bulk(array_of_args, batch_size: BATCH_SIZE) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/discover_curated_products.rb
app/controllers/concerns/discover_curated_products.rb
# frozen_string_literal: true module DiscoverCuratedProducts def taxonomies_for_nav(recommended_products: nil) Discover::TaxonomyPresenter.new.taxonomies_for_nav(recommended_products: curated_products.map(&:product)) end def curated_products @root_recommended_products ||= begin cart_product_ids = Cart.fetch_by(user: logged_in_user, browser_guid: cookies[:_gumroad_guid])&.cart_products&.alive&.pluck(:product_id) || [] RecommendedProducts::DiscoverService.fetch(purchaser: logged_in_user, cart_product_ids:, recommender_model_name: session[:recommender_model_name]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/inertia_rendering.rb
app/controllers/concerns/inertia_rendering.rb
# frozen_string_literal: true module InertiaRendering extend ActiveSupport::Concern include ApplicationHelper included do inertia_share do RenderingExtension.custom_context(view_context).merge( authenticity_token: form_authenticity_token, flash: inertia_flash_props, title: @title ) end inertia_share if: :user_signed_in? do { current_user: current_user_props(current_user, impersonated_user) } end end private def inertia_flash_props return if (flash_message = flash[:alert] || flash[:warning] || flash[:notice]).blank? { message: flash_message, status: flash[:alert] ? "danger" : flash[:warning] ? "warning" : "success" } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/validate_recaptcha.rb
app/controllers/concerns/validate_recaptcha.rb
# frozen_string_literal: true module ValidateRecaptcha ENTERPRISE_VERIFICATION_URL = "https://recaptchaenterprise.googleapis.com/v1/projects/#{GOOGLE_CLOUD_PROJECT_ID}/" \ "assessments?key=#{GlobalConfig.get("ENTERPRISE_RECAPTCHA_API_KEY")}" private_constant :ENTERPRISE_VERIFICATION_URL private def valid_recaptcha_response_and_hostname?(site_key:) return true if Rails.env.test? verification_response = recaptcha_verification_response(site_key:) is_valid_token = verification_response.dig("tokenProperties", "valid") # Verify hostname only in production because the returned hostname isn't the real hostname for test keys if Rails.env.production? hostname = verification_response.dig("tokenProperties", "hostname") is_valid_token && ( # TODO: Refactor subdomain check. Use Subdomain module if possible hostname == DOMAIN || hostname.end_with?(".#{ROOT_DOMAIN}") || CustomDomain.find_by_host(hostname).present?) else is_valid_token end end def valid_recaptcha_response?(site_key:) return true if Rails.env.test? verification_response = recaptcha_verification_response(site_key:) verification_response.dig("tokenProperties", "valid") end def recaptcha_verification_response(site_key:) response = HTTParty.post(ENTERPRISE_VERIFICATION_URL, headers: { "Content-Type" => "application/json charset=utf-8" }, body: { event: { token: params["g-recaptcha-response"], siteKey: site_key, userAgent: request.user_agent, userIpAddress: request.remote_ip } }.to_json, timeout: 5) Rails.logger.info response response end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/throttling.rb
app/controllers/concerns/throttling.rb
# frozen_string_literal: true module Throttling extend ActiveSupport::Concern private def throttle!(key:, limit:, period:, redis: $redis) count = redis.incr(key) redis.expire(key, period.to_i) if count == 1 if count > limit retry_after = redis.ttl(key) || period.to_i response.set_header("Retry-After", retry_after) render json: { error: "Rate limit exceeded. Try again in #{retry_after} seconds." }, status: :too_many_requests return false end true end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/mass_unblocker.rb
app/controllers/concerns/mass_unblocker.rb
# frozen_string_literal: true module MassUnblocker extend ActiveSupport::Concern private def schedule_mass_unblock(identifiers:) array_of_mass_unblock_args = identifiers.split(MassBlocker::DELIMITER_REGEX) .select(&:present?) .uniq .map { |identifier| [identifier] } array_of_mass_unblock_args.in_groups_of(MassBlocker::BATCH_SIZE, false).each do |array_of_args| UnblockObjectWorker.perform_bulk(array_of_args, batch_size: MassBlocker::BATCH_SIZE) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/affiliate_cookie.rb
app/controllers/concerns/affiliate_cookie.rb
# frozen_string_literal: true module AffiliateCookie include AffiliateQueryParams private def set_affiliate_cookie affiliate_id = fetch_affiliate_id(params) return unless affiliate_id.present? affiliate = Affiliate.find_by_external_id_numeric(affiliate_id) create_affiliate_id_cookie(affiliate) end def create_affiliate_id_cookie(affiliate) return unless affiliate.present? affiliate = affiliate.affiliate_user.direct_affiliate_accounts.where(seller: affiliate.seller).alive.last if !affiliate.global? && affiliate.deleted? return unless affiliate&.alive? logger.info("Setting affiliate cookie on guid #{cookies[:_gumroad_guid]} for affiliate id #{affiliate.external_id} from referrer #{request.referrer}") cookies[affiliate.cookie_key] = { value: Time.current.to_i, expires: affiliate.class.cookie_lifetime.from_now, httponly: true, domain: :all } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/custom_domain_route_builder.rb
app/controllers/concerns/custom_domain_route_builder.rb
# frozen_string_literal: true module CustomDomainRouteBuilder extend ActiveSupport::Concern included do before_action :set_is_user_custom_domain helper_method :build_view_post_route end def build_view_post_route(post:, purchase_id: nil) return if post&.slug.blank? if @is_user_custom_domain custom_domain_view_post_path(slug: post.slug, purchase_id: purchase_id.presence, protocol: request.protocol) else view_post_path( username: post.user.username.presence || post.user.external_id, slug: post.slug, purchase_id: purchase_id.presence ) end end def seller_custom_domain_url root_url(protocol: request.protocol, host: request.host_with_port) if @is_user_custom_domain end private def set_is_user_custom_domain @is_user_custom_domain = UserCustomDomainRequestService.valid?(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/utm_link_tracking.rb
app/controllers/concerns/utm_link_tracking.rb
# frozen_string_literal: true module UtmLinkTracking extend ActiveSupport::Concern private def track_utm_link_visit return unless request.get? required_params = { utm_source: params[:utm_source].presence, utm_medium: params[:utm_medium].presence, utm_campaign: params[:utm_campaign].presence } optional_params = { utm_term: params[:utm_term].presence, utm_content: params[:utm_content].presence } return if required_params.values.any?(&:blank?) return if cookies[:_gumroad_guid].blank? # i.e. cookies are disabled return unless UserCustomDomainConstraint.matches?(request) seller = CustomDomain.find_by_host(request.host)&.user || Subdomain.find_seller_by_request(request) return if seller.blank? return unless Feature.active?(:utm_links, seller) target_resource_type, target_resource_id = determine_utm_link_target_resource(seller) return if target_resource_type.blank? utm_params = required_params.merge(optional_params).transform_values { _1.to_s.strip.downcase.gsub(/[^a-z0-9\-_]/u, "-").presence } ActiveRecord::Base.transaction do utm_link = UtmLink.active.find_or_initialize_by(utm_params.merge(target_resource_type:, target_resource_id:)) auto_create_utm_link(utm_link, seller) if utm_link.new_record? return unless utm_link.persisted? return unless Feature.active?(:utm_links, utm_link.seller) utm_link.utm_link_visits.create!( user: current_user, referrer: request.referrer, ip_address: request.remote_ip, user_agent: request.user_agent, browser_guid: cookies[:_gumroad_guid], country_code: GeoIp.lookup(request.remote_ip)&.country_code ) utm_link.first_click_at ||= Time.current utm_link.last_click_at = Time.current utm_link.save! UpdateUtmLinkStatsJob.perform_async(utm_link.id) end end def auto_create_utm_link(utm_link, seller) utm_link.seller = seller utm_link.title = utm_link.default_title utm_link.ip_address = request.remote_ip utm_link.browser_guid = cookies[:_gumroad_guid] utm_link.save! end def determine_utm_link_target_resource(seller) if request.path == root_path [UtmLink.target_resource_types[:profile_page], nil] elsif params[:id].present? && request.path.starts_with?(short_link_path(params[:id])) product = if seller&.custom_domain&.product&.general_permalink == params[:id] seller.custom_domain&.product else Link.fetch_leniently(params[:id], user: seller) end return if product.blank? [UtmLink.target_resource_types[:product_page], product.id] elsif params[:slug].present? && request.path.ends_with?(custom_domain_view_post_path(params[:slug])) post = seller.installments.find_by_slug(params[:slug]) return if post.blank? [UtmLink.target_resource_types[:post_page], post.id] elsif request.path == custom_domain_subscribe_path [UtmLink.target_resource_types[:subscribe_page], 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/concerns/search_products.rb
app/controllers/concerns/search_products.rb
# frozen_string_literal: true module SearchProducts BLACK_FRIDAY_CODE = "BLACKFRIDAY2025" ALLOWED_OFFER_CODES = [BLACK_FRIDAY_CODE].freeze private def search_products(params) filetype_options = Link.filetype_options(params) filetype_response = Link.search(filetype_options) product_options = Link.search_options(params.merge(track_total_hits: true)) product_response = Link.search(product_options) { total: product_response.results.total, tags_data: product_response.aggregations["tags.keyword"]["buckets"].to_a.map(&:to_h), filetypes_data: filetype_response.aggregations["filetypes.keyword"]["buckets"].to_a.map(&:to_h), products: product_response.records } end def format_search_params! if params[:tags].is_a?(String) params[:tags] = params[:tags].split(",").map { |t| t.tr("-", " ").squish.downcase } end if params[:filetypes].is_a?(String) params[:filetypes] = params[:filetypes].split(",").map { |f| f.squish.downcase } end params[:offer_code] = "__no_match__" if params[:offer_code].present? && !offer_codes_search_feature_active?(params) if params[:size].is_a?(String) params[:size] = params[:size].to_i end end def offer_codes_search_feature_active?(params) return false if ALLOWED_OFFER_CODES.exclude?(params[:offer_code]) Feature.active?(:offer_codes_search) || (params[:feature_key].present? && ActiveSupport::SecurityUtils.secure_compare(params[:feature_key], 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/concerns/admin_action_tracker.rb
app/controllers/concerns/admin_action_tracker.rb
# frozen_string_literal: true module AdminActionTracker extend ActiveSupport::Concern included do before_action :track_admin_action_call end private def track_admin_action_call AdminActionCallInfo.find_by(controller_name: self.class.name, action_name:)&.increment!(:call_count) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/record_media_location.rb
app/controllers/concerns/record_media_location.rb
# frozen_string_literal: true module RecordMediaLocation private def record_media_location(params) return false if params[:url_redirect_id].blank? || params[:product_file_id].blank? || params[:location].blank? url_redirect_id = ObfuscateIds.decrypt(params[:url_redirect_id]) purchase_id = params[:purchase_id].present? ? ObfuscateIds.decrypt(params[:purchase_id]) : UrlRedirect.find(url_redirect_id).try(:purchase).try(:id) product_id = Purchase.find_by(id: purchase_id).try(:link).try(:id) return false if product_id.blank? || purchase_id.blank? consumed_at = params[:consumed_at].present? ? Time.zone.parse(params[:consumed_at]) : Time.current product_file = ProductFile.find(ObfuscateIds.decrypt(params[:product_file_id])) return false unless product_file.consumable? media_location = MediaLocation.find_or_initialize_by(url_redirect_id:, purchase_id:, product_file_id: product_file.id, product_id:, platform: params[:platform]) return false unless media_location.new_record? || consumed_at > media_location.consumed_at media_location.update!(location: params[:location], consumed_at:) true end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/dashboard_preference.rb
app/controllers/concerns/dashboard_preference.rb
# frozen_string_literal: true module DashboardPreference COOKIE_NAME = "last_viewed_dashboard" SALES_DASHBOARD = "sales" AUDIENCE_DASHBOARD = "audience" private_constant :COOKIE_NAME, :SALES_DASHBOARD, :AUDIENCE_DASHBOARD private def preferred_dashboard_url return @_preferred_dashboard_url if defined?(@_preferred_dashboard_url) return unless cookies.key?(COOKIE_NAME) @_preferred_dashboard_url = cookies[COOKIE_NAME] == SALES_DASHBOARD ? sales_dashboard_url : audience_dashboard_url end def set_dashboard_preference_to_audience cookies[COOKIE_NAME] = AUDIENCE_DASHBOARD end def set_dashboard_preference_to_sales cookies[COOKIE_NAME] = SALES_DASHBOARD end def clear_dashboard_preference cookies.delete(COOKIE_NAME) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/process_refund.rb
app/controllers/concerns/process_refund.rb
# frozen_string_literal: true module ProcessRefund private def process_refund(seller:, user:, purchase_external_id:, amount:, impersonating: false) # We don't support commas in refund amount # Reference: https://github.com/gumroad/web/pull/17747 return render json: { success: false, message: "Commas not supported in refund amount." } if amount&.include?(",") purchase = seller.sales.paid.find_by_external_id(purchase_external_id) return e404_json if purchase.nil? || purchase.stripe_refunded? || purchase.paypal_refund_expired? begin if purchase.refund!(refunding_user_id: user.id, amount:) purchase.seller.update!(refund_fee_notice_shown: true) unless impersonating render json: { success: true, id: purchase.external_id, message: "Purchase successfully refunded.", partially_refunded: purchase.stripe_partially_refunded? } else render json: { success: false, message: purchase.errors.full_messages.to_sentence } end rescue ActiveRecord::RecordInvalid => e Bugsnag.notify(e) render json: { success: false, message: "Sorry, something went wrong." }, status: :unprocessable_entity end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/admin/commentable.rb
app/controllers/concerns/admin/commentable.rb
# frozen_string_literal: true module Admin::Commentable include Pagy::Backend def index pagination, comments = pagy( commentable.comments.includes(:author).references(:author).order(created_at: :desc), limit: params[:per_page] || 20, page: params[:page] || 1 ) render json: { comments: comments.map { json_payload(_1) }, pagination: } end def create comment = commentable.comments.with_type_note.new( author: current_user, **comment_params ) if comment.save render json: { success: true, comment: json_payload(comment) } else render json: { success: false, error: comment.errors.full_messages.join(", ") }, status: :unprocessable_entity end end private def commentable raise NotImplementedError, "Subclass must implement commentable" end def comment_params params.require(:comment).permit(:content, :comment_type) end def json_payload(comment) comment.as_json( only: %i[id author_name comment_type content updated_at], include: { author: { only: %i[id name email], } }, ).reverse_merge(author: 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/admin/fetch_user.rb
app/controllers/concerns/admin/fetch_user.rb
# frozen_string_literal: true module Admin::FetchUser private def fetch_user @user = if user_param.include?("@") User.find_by(email: user_param) else User.where(username: user_param) .or(User.where(id: user_param)) .or(User.where(external_id: user_param)) .first end e404 unless @user end def user_param params[:id] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/admin/list_paginated_users.rb
app/controllers/concerns/admin/list_paginated_users.rb
# frozen_string_literal: true module Admin::ListPaginatedUsers extend ActiveSupport::Concern include Pagy::Backend # We list 5 users per page by default for the following reasons: # - Feature: A list of user cards is used for the refund queue or for searching users, so we don't need to display too many users per page to avoid overwhelming the user. # - UX: A user card in the admin takes up almost the entire height of the page, so we don't need to display too many users per page since the viewer would not see the entire list. # - Performance: Loading a user card is slow because we load a lot of data for each user. RECORDS_PER_PAGE = 5 private def list_paginated_users(users:, template:, legacy_template:, single_result_redirect_path: nil) pagination, users = pagy_countless( users, limit: params[:per_page] || RECORDS_PER_PAGE, page: params[:page], countless_minimal: true ) if single_result_redirect_path && pagination.page == 1 && users.length == 1 return redirect_to single_result_redirect_path.call(users.first) end respond_to do |format| format.html do render( inertia: template, props: { users: InertiaRails.merge do users.with_attached_avatar .includes(:admin_manageable_user_memberships) .with_blocked_attributes_for(:form_email, :form_email_domain) .map do |user| Admin::UserPresenter::Card.new(user: user, pundit_user:).props end end, pagination: }, legacy_template: ) end format.json { render json: { users:, pagination: } } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/concerns/admin/users/list_paginated_products.rb
app/controllers/concerns/admin/users/list_paginated_products.rb
# frozen_string_literal: true module Admin::Users::ListPaginatedProducts include Pagy::Backend PRODUCTS_ORDER = Arel.sql("ISNULL(COALESCE(purchase_disabled_at, banned_at, links.deleted_at)) DESC, created_at DESC") PRODUCTS_PER_PAGE = 10 private def list_paginated_products(user:, products:, inertia_template:) pagination, products = pagy( products.order(PRODUCTS_ORDER), page: params[:page], limit: params[:per_page] || PRODUCTS_PER_PAGE, ) render inertia: inertia_template, props: { user: -> { { id: user.id } }, products: products.includes(:ordered_alive_product_files, :active_integrations, :staff_picked_product, :taxonomy).map do |product| Admin::ProductPresenter::Card.new(product:, pundit_user:).props end, pagination: PagyPresenter.new(pagination).props } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/workflows/emails_controller.rb
app/controllers/workflows/emails_controller.rb
# frozen_string_literal: true class Workflows::EmailsController < Sellers::BaseController before_action :set_workflow before_action :authorize_workflow layout "inertia" FLASH_CHANGES_SAVED = "Changes saved!" FLASH_PREVIEW_EMAIL_SENT = "A preview has been sent to your email." FLASH_WORKFLOW_PUBLISHED = "Workflow published!" FLASH_WORKFLOW_UNPUBLISHED = "Unpublished!" def index @title = @workflow.name workflow_presenter = WorkflowPresenter.new(seller: current_seller, workflow: @workflow) render inertia: "Workflows/Emails/Index", props: { workflow: -> { workflow_presenter.workflow_props }, context: -> { workflow_presenter.workflow_form_context_props }, } end def update service = Workflow::SaveInstallmentsService.new( seller: current_seller, params: installments_params, workflow: @workflow, preview_email_recipient: preview_recipient ) success, errors = service.process if success redirect_to workflow_emails_path(@workflow.external_id), status: :see_other, notice: flash_message_for(installments_params) else redirect_to workflow_emails_path(@workflow.external_id), inertia: { errors: errors }, alert: errors.full_messages.first end end private def set_workflow @workflow = current_seller.workflows.find_by_external_id(params[:workflow_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 preview_recipient impersonating_user || logged_in_user end def installments_params params.require(:workflow).permit( :send_to_past_customers, :save_action_name, installments: [ :id, :name, :message, :time_period, :time_duration, :send_preview_email, files: [:external_id, :url, :position, :stream_only, subtitle_files: [:url, :language]], ], ) end def flash_message_for(permitted_params) case permitted_params[:save_action_name] when "save_and_publish" then FLASH_WORKFLOW_PUBLISHED when "save_and_unpublish" then FLASH_WORKFLOW_UNPUBLISHED else preview_email_requested?(permitted_params) ? FLASH_PREVIEW_EMAIL_SENT : FLASH_CHANGES_SAVED end end def preview_email_requested?(permitted_params) boolean = ActiveModel::Type::Boolean.new Array(permitted_params[:installments]).any? { |inst| boolean.cast(inst[:send_preview_email]) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/payouts/exportables_controller.rb
app/controllers/payouts/exportables_controller.rb
# frozen_string_literal: true class Payouts::ExportablesController < Sellers::BaseController include PayoutsHelper before_action :load_years_with_payouts def index authorize :balance, :export? selected_year = params[:year]&.to_i selected_year = @years_with_payouts.include?(selected_year) ? selected_year : @years_with_payouts.first payouts_in_selected_year = scoped_payments .where(created_at: Time.zone.local(selected_year).all_year) .order(created_at: :desc) render json: { years_with_payouts: @years_with_payouts, selected_year:, payouts_in_selected_year: payouts_in_selected_year.map do |payment| { id: payment.external_id, date_formatted: formatted_payout_date(payment.created_at), } end } end private def load_years_with_payouts @years_with_payouts = scoped_payments .select("EXTRACT(YEAR FROM created_at) AS year") .distinct .order(year: :desc) .map(&:year) .map(&:to_i) .presence || [Time.current.year] end def scoped_payments current_seller.payments.completed.displayable end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/payouts/exports_controller.rb
app/controllers/payouts/exports_controller.rb
# frozen_string_literal: true class Payouts::ExportsController < Sellers::BaseController include PayoutsHelper before_action :load_payout_ids def create authorize :balance, :export? ExportPayoutData.perform_async(@payout_ids, impersonating_user&.id || logged_in_user.id) head :ok end private def load_payout_ids external_ids = Array.wrap(params[:payout_ids]) @payout_ids = current_seller.payments.completed.displayable.by_external_ids(external_ids).pluck(:id) if @payout_ids.empty? || @payout_ids.count != external_ids.count render json: { error: "Invalid payouts" }, status: :unprocessable_entity 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/onboarding_form_controller.rb
app/controllers/affiliate_requests/onboarding_form_controller.rb
# frozen_string_literal: true class AffiliateRequests::OnboardingFormController < Sellers::BaseController before_action :authenticate_user! before_action :set_published_products, only: [:update] def update authorize [:affiliate_requests, :onboarding_form] user_product_external_ids = @published_products.map(&:external_id_numeric) user_product_params = permitted_params[:products].filter { |product| user_product_external_ids.include?(product[:id].to_i) } if disabling_all_products_while_having_pending_requests?(user_product_params) message = "You need to have at least one product enabled since there are some pending affiliate requests" if request.inertia? return redirect_to onboarding_affiliates_path, alert: message else return render json: { success: false, error: message } end end SelfServiceAffiliateProduct.bulk_upsert!(user_product_params, current_seller.id) current_seller.update!(disable_global_affiliate: permitted_params[:disable_global_affiliate]) if request.inertia? redirect_to onboarding_affiliates_path, notice: "Changes saved!" else render json: { success: true } end rescue ActiveRecord::RecordInvalid => e if request.inertia? redirect_to onboarding_affiliates_path, alert: e.message else render json: { success: false, error: e.message } end rescue => e logger.error e.full_message if request.inertia? redirect_to onboarding_affiliates_path, alert: "Something went wrong" else render json: { success: false } end end private def set_published_products @published_products = current_seller.links.alive.order("created_at DESC") end def permitted_params params.permit(:disable_global_affiliate, products: [:id, :enabled, :fee_percent, :destination_url, :name]) end def disabling_all_products_while_having_pending_requests?(user_product_params) return false if user_product_params.any? { |product| product[:enabled] } current_seller.affiliate_requests.unattended_or_approved_but_awaiting_requester_to_sign_up.any? end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/purchases/pings_controller.rb
app/controllers/purchases/pings_controller.rb
# frozen_string_literal: true class Purchases::PingsController < Sellers::BaseController before_action :set_purchase def create authorize [:audience, @purchase], :create_ping? @purchase.send_notification_webhook_from_ui head :no_content end private def set_purchase (@purchase = current_seller.sales.find_by_external_id(params[:purchase_id])) || e404_json end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/purchases/product_controller.rb
app/controllers/purchases/product_controller.rb
# frozen_string_literal: true class Purchases::ProductController < ApplicationController before_action :set_purchase def show @purchase_product_presenter = PurchaseProductPresenter.new(@purchase) # Ensure that the React component receives the same props as the product page, in case ProductPresenter.product_props # changes @product_props = ProductPresenter.new(product: @purchase.link, request:, pundit_user:).product_props(seller_custom_domain_url:).deep_merge(@purchase_product_presenter.product_props) @user = @purchase_product_presenter.product.user @hide_layouts = true set_noindex_header end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/purchases/dispute_evidence_controller.rb
app/controllers/purchases/dispute_evidence_controller.rb
# frozen_string_literal: true class Purchases::DisputeEvidenceController < ApplicationController before_action :set_purchase, :set_dispute_evidence, :check_if_needs_redirect def show @dispute_evidence_page_presenter = DisputeEvidencePagePresenter.new(@dispute_evidence) @title = "Submit additional information" @hide_layouts = true set_noindex_header end def update signed_blob_id = dispute_evidence_params[:customer_communication_file_signed_blob_id] @dispute_evidence.assign_attributes( dispute_evidence_params.slice(:cancellation_rebuttal, :reason_for_winning, :refund_refusal_explanation) ) if signed_blob_id.present? blob = covert_and_optimize_blob_if_needed(signed_blob_id) @dispute_evidence.customer_communication_file.attach(blob) end @dispute_evidence.update_as_seller_submitted! FightDisputeJob.perform_async(@dispute_evidence.dispute.id) render json: { success: true } rescue ActiveRecord::RecordInvalid render json: { success: false, error: @dispute_evidence.errors.full_messages.to_sentence } end private def dispute_evidence_params params.require(:dispute_evidence).permit( :reason_for_winning, :cancellation_rebuttal, :refund_refusal_explanation, :customer_communication_file_signed_blob_id ) end def set_dispute_evidence disputable = @purchase.charge.presence || @purchase @dispute_evidence = disputable.dispute.dispute_evidence end def check_if_needs_redirect message = \ if @dispute_evidence.not_seller_contacted? # The feature flag was not enabled when the email was sent out "You are not allowed to perform this action." elsif @dispute_evidence.seller_submitted? "Additional information has already been submitted for this dispute." elsif @dispute_evidence.resolved? "Additional information can no longer be submitted for this dispute." end return if message.blank? redirect_to dashboard_url, alert: message end # Stripe rejects certain PNG images with the following error: # > We don't support uploading certain types of images. These unsupported images include PNG-format images that use # > 16-bit depth or interlacing. Please convert your image to PDF or JPEG and try again. # Rather than blocking the user from submitting PNGs, convert to JPG and optimize the file. # def covert_and_optimize_blob_if_needed(signed_blob_id) blob = ActiveStorage::Blob.find_signed(signed_blob_id) return blob unless blob.content_type == "image/png" variant = blob.variant(convert: "jpg", quality: 80) new_blob = ActiveStorage::Blob.create_and_upload!( io: StringIO.new(variant.processed.download), filename: "#{File.basename(blob.filename.to_s, File.extname(blob.filename.to_s))}.jpg", content_type: "image/jpeg" ) blob.purge new_blob end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/purchases/variants_controller.rb
app/controllers/purchases/variants_controller.rb
# frozen_string_literal: true class Purchases::VariantsController < Sellers::BaseController before_action :set_purchase def update authorize [:audience, @purchase] success = Purchase::VariantUpdaterService.new( purchase: @purchase, variant_id: params[:variant_id], quantity: params[:quantity].to_i, ).perform head (success ? :no_content : :not_found) end private def set_purchase @purchase = current_seller.sales.find_by_external_id(params[:purchase_id]) || e404_json end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/integrations/zoom_controller.rb
app/controllers/integrations/zoom_controller.rb
# frozen_string_literal: true class Integrations::ZoomController < ApplicationController before_action :authenticate_user!, except: [:oauth_redirect] def account_info zoom_api = ZoomApi.new oauth_response = zoom_api.oauth_token(params[:code], oauth_redirect_integrations_zoom_index_url) access_token = oauth_response.parsed_response&.dig("access_token") refresh_token = oauth_response.parsed_response&.dig("refresh_token") return render json: { success: false } unless oauth_response.success? && access_token.present? && refresh_token.present? user_response = zoom_api.user_info(access_token) return render json: { success: false } unless user_response["id"].present? && user_response["email"].present? render json: { success: true, user_id: user_response["id"], email: user_response["email"], access_token:, refresh_token: } end def oauth_redirect render inline: "", layout: "application", status: params.key?(:code) ? :ok : :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/integrations/circle_controller.rb
app/controllers/integrations/circle_controller.rb
# frozen_string_literal: true class Integrations::CircleController < Sellers::BaseController before_action :skip_authorization def communities return render json: { success: false } if params[:api_key].blank? communities_response = CircleApi.new(params[:api_key]).get_communities return render json: { success: false } if !communities_response.success? || !communities_response.parsed_response.kind_of?(Array) render json: { success: true, communities: communities_response.parsed_response.map { |c| c.slice("name", "id") } } end def space_groups return render json: { success: false } if params[:community_id].blank? || params[:api_key].blank? space_groups_response = CircleApi.new(params[:api_key]).get_space_groups(params[:community_id]) return render json: { success: false } if !space_groups_response.success? || !space_groups_response.parsed_response.kind_of?(Array) render json: { success: true, space_groups: space_groups_response.parsed_response.map { |c| c.slice("name", "id") } } end def communities_and_space_groups return render json: { success: false } if params[:community_id].blank? || params[:api_key].blank? communities_response = CircleApi.new(params[:api_key]).get_communities space_groups_response = CircleApi.new(params[:api_key]).get_space_groups(params[:community_id]) return render json: { success: false } if !space_groups_response.success? || !space_groups_response.parsed_response.kind_of?(Array) || !communities_response.success? || !communities_response.parsed_response.kind_of?(Array) render json: { success: true, communities: communities_response.parsed_response.map { |c| c.slice("name", "id") }, space_groups: space_groups_response.parsed_response.map { |c| c.slice("name", "id") } } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/integrations/google_calendar_controller.rb
app/controllers/integrations/google_calendar_controller.rb
# frozen_string_literal: true class Integrations::GoogleCalendarController < ApplicationController before_action :authenticate_user!, except: [:oauth_redirect] def account_info gcal_api = GoogleCalendarApi.new oauth_response = gcal_api.oauth_token(params[:code], oauth_redirect_integrations_google_calendar_index_url) access_token = oauth_response.parsed_response&.dig("access_token") refresh_token = oauth_response.parsed_response&.dig("refresh_token") return render json: { success: false } unless oauth_response.success? && access_token.present? && refresh_token.present? user_info_response = gcal_api.user_info(access_token) email = user_info_response.parsed_response&.dig("email") return render json: { success: false } unless user_info_response.success? && email.present? render json: { success: true, access_token:, refresh_token:, email: } end def calendar_list gcal_api = GoogleCalendarApi.new calendar_list_response = gcal_api.calendar_list(params[:access_token]) if calendar_list_response.code === 401 refresh_token_response = gcal_api.refresh_token(params[:refresh_token]) access_token = refresh_token_response.parsed_response&.dig("access_token") return render json: { success: false } unless refresh_token_response.success? && access_token.present? calendar_list_response = gcal_api.calendar_list(access_token) end return render json: { success: false } unless calendar_list_response.success? render json: { success: true, calendar_list: calendar_list_response.parsed_response["items"].map { |c| c.slice("id", "summary") } } end def oauth_redirect render inline: "", layout: "application", status: params.key?(:code) ? :ok : :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/integrations/discord_controller.rb
app/controllers/integrations/discord_controller.rb
# frozen_string_literal: true class Integrations::DiscordController < ApplicationController before_action :authenticate_user!, except: [:oauth_redirect, :join_server, :leave_server] def server_info discord_api = DiscordApi.new oauth_response = discord_api.oauth_token(params[:code], oauth_redirect_integrations_discord_index_url) server = oauth_response.parsed_response&.dig("guild") access_token = oauth_response.parsed_response&.dig("access_token") return render json: { success: false } unless oauth_response.success? && server.present? && access_token.present? begin user_response = discord_api.identify(access_token) user = JSON.parse(user_response) render json: { success: true, server_id: server["id"], server_name: server["name"], username: user["username"] } rescue Discordrb::Errors::CodeError render json: { success: false } end end def join_server return render json: { success: false } if params[:code].blank? || params[:purchase_id].blank? discord_api = DiscordApi.new oauth_response = discord_api.oauth_token(params[:code], oauth_redirect_integrations_discord_index_url(host: DOMAIN, protocol: PROTOCOL)) access_token = oauth_response.parsed_response&.dig("access_token") return render json: { success: false } unless oauth_response.success? && access_token.present? begin user_response = discord_api.identify(access_token) user = JSON.parse(user_response) purchase = Purchase.find_by_external_id(params[:purchase_id]) integration = purchase.find_enabled_integration(Integration::DISCORD) return render json: { success: false } if integration.nil? add_member_response = discord_api.add_member(integration.server_id, user["id"], access_token) return render json: { success: false } unless add_member_response.code === 201 || add_member_response.code === 204 purchase_integration = purchase.purchase_integrations.build(integration:, discord_user_id: user["id"]) if purchase_integration.save render json: { success: true, server_name: integration.server_name } else render json: { success: false } end rescue Discordrb::Errors::CodeError, Discordrb::Errors::NoPermission render json: { success: false } end end def leave_server return render json: { success: false } if params[:purchase_id].blank? purchase = Purchase.find_by_external_id(params[:purchase_id]) integration = purchase.find_integration_by_name(Integration::DISCORD) discord_user_id = DiscordIntegration.discord_user_id_for(purchase) return render json: { success: false } if integration.nil? || discord_user_id.blank? begin response = DiscordApi.new.remove_member(integration.server_id, discord_user_id) return render json: { success: false } unless response.code === 204 rescue Discordrb::Errors::UnknownServer => e Rails.logger.info("DiscordController: Customer with purchase ID #{purchase.id} is trying to leave a deleted Discord server. Proceeding to mark the PurchaseIntegration as deleted. Error: #{e.class} => #{e.message}") rescue Discordrb::Errors::NoPermission return render json: { success: false } end purchase.live_purchase_integrations.find_by(integration:).mark_deleted! render json: { success: true, server_name: integration.server_name } end def oauth_redirect if params[:state].present? state = JSON.parse(params[:state]) is_admin = state.dig("is_admin") == true encrypted_product_id = state.dig("product_id") if is_admin && !encrypted_product_id.nil? decrypted_product_id = ObfuscateIds.decrypt(CGI.unescape(encrypted_product_id)) redirect_to join_discord_admin_product_path(decrypted_product_id, code: params[:code]) return end seller = User.find(ObfuscateIds.decrypt(CGI.unescape(state.dig("seller_id")))) if seller.present? host = state.dig("is_custom_domain") ? seller.custom_domain.domain : seller.subdomain redirect_to oauth_redirect_integrations_discord_index_url(host:, params: { code: params[:code] }), allow_other_host: true return end end render inline: "", layout: "application", status: params.key?(:code) ? :ok : :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/user/omniauth_callbacks_controller.rb
app/controllers/user/omniauth_callbacks_controller.rb
# frozen_string_literal: true class User::OmniauthCallbacksController < Devise::OmniauthCallbacksController REQ_PARAM_STATE = "state" # Log in user through FB OAuth def facebook auth_params = request.env["omniauth.params"] if !auth_params.nil? && !auth_params[REQ_PARAM_STATE].nil? && auth_params[REQ_PARAM_STATE] == :link_facebook_account.to_s return link_facebook_account end @user = User.find_for_facebook_oauth(request.env["omniauth.auth"]) if @user.persisted? if @user.is_team_member? flash[:alert] = "You're an admin, you can't login with Facebook." redirect_to login_path elsif @user.deleted? flash[:alert] = "You cannot log in because your account was permanently deleted. Please sign up for a new account to start selling!" redirect_to login_path elsif @user.email.present? sign_in_or_prepare_for_two_factor_auth(@user) safe_redirect_to two_factor_authentication_path(next: post_auth_redirect(@user)) else sign_in @user safe_redirect_to post_auth_redirect(@user) end else flash[:alert] = "Sorry, something went wrong. Please try again." redirect_to signup_path end end # Log in user through Twitter OAuth def twitter auth_params = request.env["omniauth.params"] if auth_params.present? && auth_params[REQ_PARAM_STATE].present? if auth_params[REQ_PARAM_STATE] == "link_twitter_account" return sync_link_twitter_account elsif auth_params[REQ_PARAM_STATE] == "async_link_twitter_account" return async_link_twitter_account end end @user = User.find_or_create_for_twitter_oauth!(request.env["omniauth.auth"]) if @user.persisted? update_twitter_oauth_credentials_for(@user) if @user.is_team_member? flash[:alert] = "You're an admin, you can't login with Twitter." redirect_to login_path elsif @user.deleted? flash[:alert] = "You cannot log in because your account was permanently deleted. Please sign up for a new account to start selling!" redirect_to login_path elsif @user.email.present? sign_in_or_prepare_for_two_factor_auth(@user) safe_redirect_to two_factor_authentication_path(next: post_auth_redirect(@user)) else sign_in @user if @user.unconfirmed_email.present? flash[:warning] = "Please confirm your email address" else create_user_event("signup") flash[:warning] = "Please enter an email address!" end safe_redirect_to settings_main_path end else flash[:alert] = "Sorry, something went wrong. Please try again." redirect_to signup_path end end def stripe_connect auth = request.env["omniauth.auth"] referer = request.env["omniauth.params"]["referer"] Rails.logger.info("Stripe Connect referer: #{referer}, parameters: #{auth}") if logged_in_user&.stripe_connect_account.present? flash[:alert] = "You already have another Stripe account connected with your Gumroad account." return safe_redirect_to settings_payments_path end stripe_account = Stripe::Account.retrieve(auth.uid) unless StripeMerchantAccountManager::COUNTRIES_SUPPORTED_BY_STRIPE_CONNECT.include?(stripe_account.country) flash[:alert] = "Sorry, Stripe Connect is not supported in #{Compliance::Countries.mapping[stripe_account.country]} yet." return safe_redirect_to referer end if logged_in_user.blank? user = User.find_or_create_for_stripe_connect_account(auth) if user.nil? flash[:alert] = "An account already exists with this email." return safe_redirect_to referer elsif user.is_team_member? flash[:alert] = "You're an admin, you can't login with Stripe." return safe_redirect_to referer elsif user.deleted? flash[:alert] = "You cannot log in because your account was permanently deleted. Please sign up for a new account to start selling!" return safe_redirect_to referer end session[:stripe_connect_data] = { "auth_uid" => auth.uid, "referer" => referer, "signup" => true } if user.stripe_connect_account.blank? create_user_event("signup") end if user.email.present? sign_in_or_prepare_for_two_factor_auth(user) return safe_redirect_to two_factor_authentication_path(next: oauth_completions_stripe_path) else sign_in user return safe_redirect_to oauth_completions_stripe_path end end session[:stripe_connect_data] = { "auth_uid" => auth.uid, "referer" => referer, "signup" => false } safe_redirect_to oauth_completions_stripe_path end def google_oauth2 @user = User.find_or_create_for_google_oauth2(request.env["omniauth.auth"]) if @user&.persisted? if @user.is_team_member? flash[:alert] = "You're an admin, you can't login with Google." redirect_to login_path elsif @user.deleted? flash[:alert] = "You cannot log in because your account was permanently deleted. Please sign up for a new account to start selling!" redirect_to login_path elsif @user.email.present? sign_in_or_prepare_for_two_factor_auth(@user) safe_redirect_to two_factor_authentication_path(next: post_auth_redirect(@user)) else sign_in @user safe_redirect_to post_auth_redirect(@user) end else flash[:alert] = "Sorry, something went wrong. Please try again." redirect_to signup_path end end def failure if params[:error_description].present? redirect_to settings_payments_path, notice: params[:error_description] elsif params[REQ_PARAM_STATE] != :async_link_twitter_account.to_s Rails.logger.info("OAuth failure and request state unexpected: #{params}") super else render action: "async_link_twitter_account" end end private def post_auth_redirect(user) if params[:referer].present? && params[:referer] != "/" params[:referer] else safe_redirect_path(helpers.signed_in_user_home(user)) end end def update_twitter_oauth_credentials_for(user) access_token = request.env["omniauth.auth"] user.update!(twitter_oauth_token: access_token["credentials"]["token"], twitter_oauth_secret: access_token["credentials"]["secret"]) end def link_twitter_account access_token = request.env["omniauth.auth"] data = access_token.extra.raw_info User.query_twitter(logged_in_user, data) logged_in_user.update!(twitter_oauth_token: access_token["credentials"]["token"], twitter_oauth_secret: access_token["credentials"]["secret"]) end def async_link_twitter_account link_twitter_account render action: "async_link_twitter_account" end # Links a Twitter handle/account to an existing Gumroad user def sync_link_twitter_account link_twitter_account post_link_account end # Links a Facebook user/account to an existing Gumroad user def link_facebook_account data = request.env["omniauth.auth"] if User.find_by(facebook_uid: data["uid"]) post_link_failure("Your Facebook account has already been linked to a Gumroad account.") else User.query_fb_graph(logged_in_user, data, new_user: false) post_link_account end end def post_link_account logged_in_user.save redirect_to settings_profile_path end def post_link_failure(error_message = nil) flash[:alert] = error_message redirect_to user_path(logged_in_user) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/user/passwords_controller.rb
app/controllers/user/passwords_controller.rb
# frozen_string_literal: true class User::PasswordsController < Devise::PasswordsController def new e404 end def create email = params[:user][:email] if EmailFormatValidator.valid?(email) @user = User.alive.by_email(email).first return head :no_content if @user&.send_reset_password_instructions end render json: { error_message: "An account does not exist with that email." }, status: :unprocessable_entity end def edit @reset_password_token = params[:reset_password_token] @user = User.find_or_initialize_with_error_by(:reset_password_token, Devise.token_generator.digest(User, :reset_password_token, @reset_password_token)) if @user.errors.present? flash[:alert] = "That reset password token doesn't look valid (or may have expired)." return redirect_to root_url end @title = "Reset your password" end def update @reset_password_token = params[:user][:reset_password_token] @user = User.reset_password_by_token(params[:user]) if @user.errors.present? error_message = if @user.errors[:password_confirmation].present? "Those two passwords didn't match." elsif @user.errors[:password].present? @user.errors.full_messages.first else "That reset password token doesn't look valid (or may have expired)." end render json: { error_message: error_message }, status: :unprocessable_entity else flash[:notice] = "Your password has been reset, and you're now logged in." @user.invalidate_active_sessions! sign_in @user unless @user.deleted? head :no_content end end def after_sending_reset_password_instructions_path_for(_resource_name, _user) root_url end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/user/invalidate_active_sessions_controller.rb
app/controllers/user/invalidate_active_sessions_controller.rb
# frozen_string_literal: true class User::InvalidateActiveSessionsController < Sellers::BaseController def update user = current_seller authorize [:settings, :main, user], :invalidate_active_sessions? user.invalidate_active_sessions! sign_out flash[:notice] = "You have been signed out from all your active sessions. Please login again." flash[:notice_style] = "success" 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/custom_domain/verifications_controller.rb
app/controllers/custom_domain/verifications_controller.rb
# frozen_string_literal: true class CustomDomain::VerificationsController < Sellers::BaseController def create authorize [:settings, :advanced, current_seller], :show? has_valid_configuration = CustomDomainVerificationService.new(domain: params[:domain]).process passes_model_validation = if params[:product_id] product = Link.find_by_external_id(params[:product_id]) if product custom_domain = product.custom_domain || product.build_custom_domain custom_domain.domain = params[:domain] custom_domain.valid? else false end else true end success, message = if has_valid_configuration if passes_model_validation [true, "#{params[:domain]} domain is correctly configured!"] else [false, product&.custom_domain&.errors&.map(&:type)&.first || "Domain verification failed. Please make sure you have correctly configured the DNS record for #{params[:domain]}."] end else [false, "Domain verification failed. Please make sure you have correctly configured the DNS record for #{params[:domain]}."] end render json: { success:, message: } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/password_controller.rb
app/controllers/settings/password_controller.rb
# frozen_string_literal: true class Settings::PasswordController < Settings::BaseController before_action :set_user before_action :authorize def show @title = "Settings" render inertia: "Settings/Password/Show", props: settings_presenter.password_props end def update if @user.provider.present? unless @user.confirmed? return redirect_to settings_password_path, alert: "You have to confirm your email address before you can do that." end @user.password = params["user"]["new_password"] @user.provider = nil else if params["user"].blank? || params["user"]["password"].blank? || !@user.valid_password?(params["user"]["password"]) return redirect_to settings_password_path, alert: "Incorrect password." end @user.password = params["user"]["new_password"] end if @user.save invalidate_active_sessions_except_the_current_session! bypass_sign_in(@user) redirect_to settings_password_path, status: :see_other, notice: "You have successfully changed your password." else redirect_to settings_password_path, alert: "New password #{@user.errors[:password].to_sentence}" end end private def set_user @user = current_seller end def authorize super([:settings, :password, @user]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/main_controller.rb
app/controllers/settings/main_controller.rb
# frozen_string_literal: true class Settings::MainController < Settings::BaseController include ActiveSupport::NumberHelper before_action :authorize def show @title = "Settings" render inertia: "Settings/Main/Show", props: settings_presenter.main_props end def update current_seller.with_lock { current_seller.update!(user_params) } if params[:user][:email] == current_seller.email current_seller.update!(unconfirmed_email: nil) end if current_seller.account_level_refund_policy_enabled? current_seller.refund_policy.update!( max_refund_period_in_days: seller_refund_policy_params[:max_refund_period_in_days], fine_print: seller_refund_policy_params[:fine_print], ) end current_seller.update_purchasing_power_parity_excluded_products!(params[:user][:purchasing_power_parity_excluded_product_ids]) current_seller.update_product_level_support_emails!(params[:user][:product_level_support_emails]) redirect_to settings_main_path, status: :see_other, notice: "Your account has been updated!" rescue StandardError => e Bugsnag.notify(e) error_message = current_seller.errors.full_messages.to_sentence.presence || "Something broke. We're looking into what happened. Sorry about this!" redirect_to settings_main_path, alert: error_message end def resend_confirmation_email if current_seller.unconfirmed_email.present? || !current_seller.confirmed? current_seller.send_confirmation_instructions return redirect_to settings_main_path, status: :see_other, notice: "Confirmation email resent!" end redirect_to settings_main_path, alert: "Sorry, something went wrong. Please try again." end private def user_params permitted_params = [ :email, :enable_payment_email, :enable_payment_push_notification, :enable_recurring_subscription_charge_email, :enable_recurring_subscription_charge_push_notification, :enable_free_downloads_email, :enable_free_downloads_push_notification, :announcement_notification_enabled, :disable_comments_email, :disable_reviews_email, :support_email, :locale, :timezone, :currency_type, :purchasing_power_parity_enabled, :purchasing_power_parity_limit, :purchasing_power_parity_payment_verification_disabled, :show_nsfw_products, :disable_affiliate_requests, ] params.require(:user).permit(permitted_params) end def seller_refund_policy_params params[:user][:seller_refund_policy]&.permit(:max_refund_period_in_days, :fine_print) end def product_level_support_emails_params params[:user][:product_level_support_emails]&.permit(:email, { product_ids: [] }) end def fetch_discover_sales(seller) PurchaseSearchService.search( seller:, price_greater_than: 0, recommended: true, state: "successful", exclude_bundle_product_purchases: true, aggs: { price_cents_total: { sum: { field: "price_cents" } } } ).aggregations["price_cents_total"]["value"] end def authorize super([:settings, :main, 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/settings/advanced_controller.rb
app/controllers/settings/advanced_controller.rb
# frozen_string_literal: true class Settings::AdvancedController < Settings::BaseController before_action :authorize def show @title = "Settings" render inertia: "Settings/Advanced/Show", props: settings_presenter.advanced_props end def update begin BlockedCustomerObject.transaction do block_customer_emails end if @invalid_blocked_email.present? return redirect_to settings_advanced_path, alert: "The email #{@invalid_blocked_email} cannot be blocked as it is invalid." end rescue => e Bugsnag.notify(e) logger.error "Couldn't block customer emails: #{e.message}" return redirect_to settings_advanced_path, alert: "Sorry, something went wrong. Please try again." end begin current_seller.with_lock { current_seller.update(advanced_params) } rescue => e Bugsnag.notify(e) return redirect_to settings_advanced_path, alert: "Something broke. We're looking into what happened. Sorry about this!" end if params[:domain].present? custom_domain = current_seller.custom_domain || current_seller.build_custom_domain custom_domain.domain = params[:domain] custom_domain.verify(allow_incrementing_failed_verification_attempts_count: false) begin error_message = custom_domain.errors.full_messages.to_sentence unless custom_domain.save rescue ActiveRecord::RecordNotUnique error_message = "The custom domain is already in use." end if error_message return redirect_to settings_advanced_path, alert: error_message end elsif params[:domain] == "" && current_seller.custom_domain.present? current_seller.custom_domain.mark_deleted! end if current_seller.save redirect_to settings_advanced_path, status: :see_other, notice: "Your account has been updated!" else redirect_to settings_advanced_path, alert: current_seller.errors.full_messages.to_sentence end end private def advanced_params params.require(:user).permit(:notification_endpoint) end def block_customer_emails set_emails_to_block set_invalid_blocked_email_if_exists return if @invalid_blocked_email.present? if @emails_to_block.any? previously_blocked_emails = current_seller.blocked_customer_objects.active.email.pluck(:object_value) emails_to_unblock = previously_blocked_emails - @emails_to_block current_seller.blocked_customer_objects.active.email.where(object_value: emails_to_unblock).find_each(&:unblock!) @emails_to_block.each { |email| BlockedCustomerObject.block_email!(email:, seller_id: current_seller.id) } else current_seller.blocked_customer_objects.active.find_each(&:unblock!) end end def set_emails_to_block @emails_to_block = (params[:blocked_customer_emails].presence || "").split(/[\r\n]+/) end def set_invalid_blocked_email_if_exists @invalid_blocked_email = @emails_to_block.detect { |email| !EmailFormatValidator.valid?(email) } end def authorize super([:settings, :advanced, 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/settings/payments_controller.rb
app/controllers/settings/payments_controller.rb
# frozen_string_literal: true class Settings::PaymentsController < Settings::BaseController include ActionView::Helpers::SanitizeHelper before_action :authorize def show @title = "Settings" render inertia: "Settings/Payments/Show", props: settings_presenter.payments_props(remote_ip: request.remote_ip) end def update unless current_seller.email.present? return redirect_with_error("You have to confirm your email address before you can do that.") end return unless current_seller.fetch_or_build_user_compliance_info.country.present? compliance_info = current_seller.fetch_or_build_user_compliance_info updated_country_code = params.dig(:user, :updated_country_code) if updated_country_code.present? && updated_country_code != compliance_info.legal_entity_country_code begin UpdateUserCountry.new(new_country_code: updated_country_code, user: current_seller).process flash[:notice] = "Your country has been updated!" return redirect_to settings_payments_path, status: :see_other rescue => e Bugsnag.notify("Update country failed for user #{current_seller.id} (from #{compliance_info.country_code} to #{updated_country_code}): #{e}") return redirect_with_error("Country update failed") end end if Compliance::Countries::USA.common_name == compliance_info.legal_entity_country zip_code = params.dig(:user, :is_business) ? params.dig(:user, :business_zip_code).presence : params.dig(:user, :zip_code).presence if zip_code unless UsZipCodes.identify_state_code(zip_code).present? return redirect_with_error("You entered a ZIP Code that doesn't exist within your country.") end end end payout_type = if params[:payment_address].present? "PayPal" elsif params[:card].present? "debit card" else "bank account" end if params.dig(:user, :country) == Compliance::Countries::ARE.alpha2 && !params.dig(:user, :is_business) && payout_type != "PayPal" return redirect_with_error("Individual accounts from the UAE are not supported. Please use a business account.") end if current_seller.has_stripe_account_connected? return redirect_with_error("You cannot change your payout method to #{payout_type} because you have a stripe account connected.") end current_seller.tos_agreements.create!(ip: request.remote_ip) return unless update_payout_method return unless update_user_compliance_info if params[:payout_threshold_cents].present? && params[:payout_threshold_cents].to_i < current_seller.minimum_payout_threshold_cents return redirect_with_error("Your payout threshold must be greater than the minimum payout amount") end unless current_seller.update( params.permit(:payouts_paused_by_user, :payout_threshold_cents, :payout_frequency) ) return redirect_with_error(current_seller.errors.full_messages.first) end # Once the user has submitted all their information, and a bank account record was created for them, # we can create a stripe merchant account for them if they don't already have one. if current_seller.active_bank_account && current_seller.merchant_accounts.stripe.alive.empty? && current_seller.native_payouts_supported? begin StripeMerchantAccountManager.create_account(current_seller, passphrase: GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")) rescue => e return redirect_with_error(e.try(:message) || "Something went wrong.") end end if flash[:notice].blank? flash[:notice] = "Thanks! You're all set." end redirect_to settings_payments_path, status: :see_other end def set_country compliance_info = current_seller.fetch_or_build_user_compliance_info return head :forbidden if compliance_info.country.present? compliance_info.dup_and_save! do |new_compliance_info| new_compliance_info.country = ISO3166::Country[params[:country]]&.common_name new_currency_type = Country.new(new_compliance_info.country_code).default_currency if new_currency_type && new_currency_type != current_seller.currency_type current_seller.currency_type = new_currency_type current_seller.save! end end end def opt_in_to_au_backtax_collection # Just rudimentary validation on the name here. We want an honest attempt at putting their name, but we don't want a meaningless string of characters. if current_seller.alive_user_compliance_info&.legal_entity_name && current_seller.alive_user_compliance_info.legal_entity_name.length != params["signature"].length return render json: { success: false, error: "Please enter your exact name." } end BacktaxAgreement.create!(user: current_seller, jurisdiction: BacktaxAgreement::Jurisdictions::AUSTRALIA, signature: params["signature"]) render json: { success: true } end def paypal_connect if params[:merchantIdInPayPal].blank? || params[:merchantId].blank? || current_seller.external_id != params[:merchantId].split("-")[0] redirect_to settings_payments_path, notice: "There was an error connecting your PayPal account with Gumroad." return end meta = params.slice(:merchantId, :permissionsGranted, :accountStatus, :consentStatus, :productIntentID, :isEmailConfirmed) message = PaypalMerchantAccountManager.new.update_merchant_account( user: current_seller, paypal_merchant_id: params[:merchantIdInPayPal], meta:, send_email_confirmation_notification: false ) redirect_to settings_payments_path, notice: message end def remove_credit_card if current_seller.remove_credit_card head :no_content else render json: { error: current_seller.errors.full_messages.join(",") }, status: :bad_request end end def remediation authorize if current_seller.stripe_account.blank? || current_seller.user_compliance_info_requests.requested.blank? redirect_to settings_payments_path, notice: "Thanks! You're all set." and return end redirect_to Stripe::AccountLink.create({ account: current_seller.stripe_account.charge_processor_merchant_id, refresh_url: remediation_settings_payments_url, return_url: verify_stripe_remediation_settings_payments_url, type: "account_onboarding", }).url, allow_other_host: true end def verify_stripe_remediation safe_redirect_to settings_payments_path and return if current_seller.stripe_account.blank? stripe_account = Stripe::Account.retrieve(current_seller.stripe_account.charge_processor_merchant_id) if stripe_account["requirements"]["currently_due"].blank? && stripe_account["requirements"]["past_due"].blank? # We're marking the pending compliance request as provided on our end here if it is no longer due on Stripe. # We'll get a account.updated webhook event and mark these requests as provided there as well, # but doing it here instead of waiting on the webhook, so that the respective compliance request notice is removed # from the page immediately. current_seller.user_compliance_info_requests.requested.each(&:mark_provided!) flash[:notice] = "Thanks! You're all set." end safe_redirect_to settings_payments_path end private def update_payout_method result = UpdatePayoutMethod.new(user_params: params, seller: current_seller).process return true if result[:success] error_message = case result[:error] when :check_card_information_prompt "Please check your card information, we couldn't verify it." when :credit_card_error strip_tags(result[:data]) when :bank_account_error strip_tags(result[:data]) when :account_number_does_not_match "The account numbers do not match." when :provide_valid_email_prompt "Please provide a valid email address." when :provide_ascii_only_email_prompt "Email address cannot contain non-ASCII characters" when :paypal_payouts_not_supported "PayPal payouts are not supported in your country." end redirect_with_error(error_message) false end def update_user_compliance_info result = UpdateUserComplianceInfo.new(compliance_params: params[:user], user: current_seller).process if result[:success] true else current_seller.comments.create!( author_id: GUMROAD_ADMIN_ID, comment_type: :note, content: result[:error_message] ) redirect_with_error(result[:error_message], error_code: result[:error_code]) false end end def redirect_with_error(error_message, error_code: nil) errors_hash = { base: [error_message] } errors_hash[:error_code] = [error_code] if error_code.present? redirect_to settings_payments_path, inertia: { errors: errors_hash } end def authorize super(current_seller_policy) end def current_seller_policy [:settings, :payments, 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/settings/stripe_controller.rb
app/controllers/settings/stripe_controller.rb
# frozen_string_literal: true class Settings::StripeController < Sellers::BaseController before_action :authenticate_user!, only: [:disconnect] def disconnect authorize [:settings, :payments, logged_in_user], :stripe_connect? render json: { success: StripeMerchantAccountManager.disconnect(user: logged_in_user) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/dismiss_ai_product_generation_promos_controller.rb
app/controllers/settings/dismiss_ai_product_generation_promos_controller.rb
# frozen_string_literal: true class Settings::DismissAiProductGenerationPromosController < Sellers::BaseController before_action :authenticate_user! after_action :verify_authorized def create authorize current_seller, :generate_product_details_with_ai? current_seller.update!(dismissed_create_products_with_ai_promo_alert: true) head :ok end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/team_controller.rb
app/controllers/settings/team_controller.rb
# frozen_string_literal: true class Settings::TeamController < Settings::BaseController before_action :authorize before_action :check_email_presence def show @title = "Team" team_presenter = Settings::TeamPresenter.new(pundit_user:) render inertia: "Settings/Team/Show", props: { member_infos: team_presenter.member_infos, can_invite_member: -> { policy([:settings, :team, TeamInvitation]).create? }, } end private def authorize super([:settings, :team, current_seller]) end def check_email_presence return if current_seller.email.present? redirect_to settings_main_path, alert: "Your Gumroad account doesn't have an email associated. Please assign and verify your email, and 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/settings/base_controller.rb
app/controllers/settings/base_controller.rb
# frozen_string_literal: true class Settings::BaseController < Sellers::BaseController layout "inertia" inertia_share do { settings_pages: -> { settings_presenter.pages } } end protected def settings_presenter @settings_presenter ||= SettingsPresenter.new(pundit_user:) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/profile_controller.rb
app/controllers/settings/profile_controller.rb
# frozen_string_literal: true class Settings::ProfileController < Settings::BaseController before_action :authorize def show @title = "Settings" profile_presenter = ProfilePresenter.new(pundit_user:, seller: current_seller) render inertia: "Settings/Profile/Show", props: settings_presenter.profile_props.merge( profile_presenter.profile_settings_props(request:) ) end def update return respond_error("You have to confirm your email address before you can do that.") unless current_seller.confirmed? if permitted_params[:profile_picture_blob_id].present? return respond_error("The logo is already removed. Please refresh the page and try again.") if ActiveStorage::Blob.find_signed(permitted_params[:profile_picture_blob_id]) .nil? current_seller.avatar.attach permitted_params[:profile_picture_blob_id] elsif permitted_params.has_key?(:profile_picture_blob_id) && current_seller.avatar.attached? current_seller.avatar.purge end begin ActiveRecord::Base.transaction do seller_profile = current_seller.seller_profile sections = current_seller.seller_profile_sections.on_profile if permitted_params[:tabs] tabs = permitted_params[:tabs].as_json tabs.each { |tab| (tab["sections"] ||= []).map! { ObfuscateIds.decrypt(_1) } } sections.each do |section| section.destroy! if tabs.none? { _1["sections"]&.include?(section.id) } end seller_profile.json_data["tabs"] = tabs end seller_profile.assign_attributes(permitted_params[:seller_profile]) if permitted_params[:seller_profile].present? seller_profile.save! current_seller.update!(permitted_params[:user]) if permitted_params[:user] current_seller.clear_products_cache if permitted_params[:profile_picture_blob_id].present? end respond_success rescue ActiveRecord::RecordInvalid => e respond_error(e.record.errors.full_messages.to_sentence) end end private def authorize super(profile_policy) end def permitted_params params.permit(policy(profile_policy).permitted_attributes) end def profile_policy [:settings, :profile] end def respond_error(message) if request.inertia? redirect_to settings_profile_path, alert: message else render json: { success: false, error_message: message } end end def respond_success if request.inertia? redirect_to settings_profile_path, status: :see_other, notice: "Changes saved!" else render json: { success: true } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/third_party_analytics_controller.rb
app/controllers/settings/third_party_analytics_controller.rb
# frozen_string_literal: true class Settings::ThirdPartyAnalyticsController < Settings::BaseController before_action :authorize def show @title = "Settings" render inertia: "Settings/ThirdPartyAnalytics/Show", props: { third_party_analytics: settings_presenter.third_party_analytics_props, products: current_seller.links.alive.map { |product| { permalink: product.unique_permalink, name: product.name } } } end def update current_seller.with_lock do current_seller.assign_attributes(third_party_analytics_params.except(:snippets)) ThirdPartyAnalytic.save_third_party_analytics(third_party_analytics_params[:snippets] || [], current_seller) if current_seller.save redirect_to settings_third_party_analytics_path, status: :see_other, notice: "Changes saved!" else redirect_to settings_third_party_analytics_path, alert: current_seller.errors.full_messages.to_sentence end end rescue ThirdPartyAnalytic::ThirdPartyAnalyticInvalid => e redirect_to settings_third_party_analytics_path, alert: e.message rescue StandardError => e Bugsnag.notify(e) redirect_to settings_third_party_analytics_path, alert: "Something broke. We're looking into what happened. Sorry about this!" end private def third_party_analytics_params params.require(:user).permit( :disable_third_party_analytics, :google_analytics_id, :facebook_pixel_id, :skip_free_sale_analytics, :enable_verify_domain_third_party_services, :facebook_meta_tag, snippets: [[:id, :code, :location, :name, :product]], ) end def authorize super([:settings, :third_party_analytics, 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/settings/authorized_applications_controller.rb
app/controllers/settings/authorized_applications_controller.rb
# frozen_string_literal: true class Settings::AuthorizedApplicationsController < Settings::BaseController def index authorize([:settings, :authorized_applications, OauthApplication]) @title = "Settings" render inertia: "Settings/AuthorizedApplications/Index", props: settings_presenter.authorized_applications_props end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/team/members_controller.rb
app/controllers/settings/team/members_controller.rb
# frozen_string_literal: true class Settings::Team::MembersController < Sellers::BaseController before_action :set_team_membership, only: %i[update destroy restore] def index authorize [:settings, :team, current_seller], :show? @team_presenter = Settings::TeamPresenter.new(pundit_user:) render json: { success: true, member_infos: @team_presenter.member_infos } end def update authorize [:settings, :team, @team_membership] @team_membership.update!(update_params) render json: { success: true } end def destroy authorize [:settings, :team, @team_membership] ActiveRecord::Base.transaction do @team_membership.user.update!(is_team_member: false) if @team_membership.seller.gumroad_account? @team_membership.update_as_deleted! end render json: { success: true } end def restore authorize [:settings, :team, @team_membership] @team_membership.update_as_not_deleted! render json: { success: true } end private def set_team_membership @team_membership = current_seller.seller_memberships.find_by_external_id(params[:id]) || e404_json end def update_params params.require(:team_membership).permit(:role) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/team/invitations_controller.rb
app/controllers/settings/team/invitations_controller.rb
# frozen_string_literal: true class Settings::Team::InvitationsController < Sellers::BaseController before_action :set_team_invitation, only: %i[update destroy restore resend_invitation] def create authorize [:settings, :team, TeamInvitation] team_invitation = current_seller.team_invitations.new(create_params) team_invitation.expires_at = TeamInvitation::ACTIVE_INTERVAL_IN_DAYS.days.from_now.at_end_of_day if team_invitation.save TeamMailer.invite(team_invitation).deliver_later render json: { success: true } else render json: { success: false, error_message: team_invitation.errors.full_messages.to_sentence } end end def update authorize [:settings, :team, @team_invitation] @team_invitation.update!(update_params) render json: { success: true } end def destroy authorize [:settings, :team, @team_invitation] @team_invitation.update_as_deleted! render json: { success: true } end def restore authorize [:settings, :team, @team_invitation] @team_invitation.update_as_not_deleted! render json: { success: true } end def accept team_invitation = TeamInvitation.find_by_external_id!(external_team_invitation_id) authorize [:settings, :team, team_invitation] alert_message = nil logged_in_user_email = logged_in_user.email&.downcase if logged_in_user_email.blank? alert_message = "Your Gumroad account doesn't have an email associated. Please assign and verify your email before accepting the invitation." elsif !logged_in_user.confirmed? alert_message = "Please confirm your email address before accepting the invitation." elsif team_invitation.email != logged_in_user_email alert_message = "The invite was sent to a different email address. You are logged in as #{logged_in_user_email}" elsif team_invitation.expired? alert_message = "Invitation link has expired. Please contact the account owner." elsif team_invitation.accepted? alert_message = "Invitation has already been accepted." elsif team_invitation.deleted? alert_message = "Invitation link is invalid. Please contact the account owner." elsif team_invitation.matches_owner_email? # It can happen if the owner sends an invitation, and then changes their email address to the same email used # for the invitation. When the invitation is accepted, the membership cannot be created because the email is already # taken by the owner. In this case, the invitation is deleted and the user is redirected to the seller's account. team_invitation.update_as_deleted! alert_message = "Invitation link is invalid. Please contact the account owner." end if alert_message.present? flash[:alert] = alert_message else team_membership = nil logged_in_user.with_lock do team_invitation.update_as_accepted!(deleted_at: Time.current) logged_in_user.create_owner_membership_if_needed! logged_in_user.update!(is_team_member: true) if team_invitation.from_gumroad_account? team_membership = team_invitation.seller.seller_memberships.create!(user: logged_in_user, role: team_invitation.role) TeamMailer.invitation_accepted(team_membership).deliver_later end switch_seller_account(team_membership) flash[:notice] = "Welcome to the team at #{team_membership.seller.username}!" end redirect_to dashboard_url end def resend_invitation authorize [:settings, :team, @team_invitation] @team_invitation.update!( expires_at: TeamInvitation::ACTIVE_INTERVAL_IN_DAYS.days.from_now.at_end_of_day ) TeamMailer.invite(@team_invitation).deliver_later render json: { success: true } end private def create_params params.require(:team_invitation).permit(:email, :role) end def update_params params.require(:team_invitation).permit(:role) end def set_team_invitation @team_invitation = current_seller.team_invitations.find_by_external_id(params[:id]) || e404_json end def external_team_invitation_id params.require(:id) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/settings/profile/products_controller.rb
app/controllers/settings/profile/products_controller.rb
# frozen_string_literal: true class Settings::Profile::ProductsController < ApplicationController def show product = current_seller.products.find_by_external_id!(params[:id]) authorize product # Avoid passing the pundit_user so that the product renders as non-editable render json: ProductPresenter.new(product:, request:).product_props(seller_custom_domain_url:) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/stripe/setup_intents_controller.rb
app/controllers/stripe/setup_intents_controller.rb
# frozen_string_literal: true # Stateless API calls we need to make for the frontend to setup future charges for given CC, before passing this # CC data to be saved/charged along with the preorder, subscription, or bundle payment. class Stripe::SetupIntentsController < ApplicationController before_action :validate_card_params, only: %i[create] def create chargeable = CardParamsHelper.build_chargeable(params) if chargeable.nil? logger.error "Error while creating setup intent: failed to load chargeable for params: #{params}" render json: { success: false, error_message: "We couldn't charge your card. Try again or use a different card." }, status: :unprocessable_entity return end chargeable.prepare! reusable_token = chargeable.reusable_token_for!(StripeChargeProcessor.charge_processor_id, logged_in_user) mandate_options = mandate_options_for_stripe(chargeable) setup_intent = ChargeProcessor.setup_future_charges!(merchant_account, chargeable, mandate_options:) if setup_intent.succeeded? render json: { success: true, reusable_token:, setup_intent_id: setup_intent.id } elsif setup_intent.requires_action? render json: { success: true, reusable_token:, setup_intent_id: setup_intent.id, requires_card_setup: true, client_secret: setup_intent.client_secret } else render json: { success: false, error_message: "Sorry, something went wrong." }, status: :unprocessable_entity end rescue ChargeProcessorInvalidRequestError, ChargeProcessorUnavailableError => e logger.error "Error while creating setup intent: `#{e.message}` for params: #{params}" render json: { success: false, error_message: "There is a temporary problem, please try again (your card was not charged)." }, status: :service_unavailable rescue ChargeProcessorCardError => e logger.error "Error while creating setup intent: `#{e.message}` for params: #{params}" render json: { success: false, error_message: PurchaseErrorCode.customer_error_message(e.message), error_code: e.error_code }, status: :unprocessable_entity end private def validate_card_params card_data_handling_error = CardParamsHelper.check_for_errors(params) if card_data_handling_error.present? logger.error("Error while creating setup intent: #{card_data_handling_error.error_message} #{card_data_handling_error.card_error_code}") error_message = card_data_handling_error.is_card_error? ? PurchaseErrorCode.customer_error_message(card_data_handling_error.error_message) : "There is a temporary problem, please try again (your card was not charged)." render json: { success: false, error_message: }, status: :unprocessable_entity end end def merchant_account processor_id = StripeChargeProcessor.charge_processor_id if params[:permalink].present? link = Link.find_by unique_permalink: params[:permalink] link&.user&.merchant_account(processor_id) || MerchantAccount.gumroad(processor_id) else MerchantAccount.gumroad(processor_id) end end def mandate_options_for_stripe(chargeable) if chargeable.requires_mandate? # In case of checkout, create mandate with max product price, # as that is what we'd create an off-session charge for at max max_product_price = params.permit(products: [:price]).to_h.values.first.max_by { _1["price"].to_i }["price"].to_i rescue 0 # In case of subscription update, create mandate with current subscription price, # as price in params is 0 if there's no change in price subscription_id = params.permit(products: [:subscription_id]).to_h.values.first[0]["subscription_id"] rescue nil subscription_current_amount = subscription_id.present? ? Subscription.find_by_external_id(subscription_id).current_subscription_price_cents : 0 mandate_amount = max_product_price > 0 ? max_product_price : subscription_current_amount mandate_amount > 0 ? { payment_method_options: { card: { mandate_options: { reference: StripeChargeProcessor::MANDATE_PREFIX + SecureRandom.hex, amount_type: "maximum", amount: mandate_amount, currency: "usd", start_date: Time.current.to_i, interval: "sporadic", supported_types: ["india"] } } } } : 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/admin/suspend_users_controller.rb
app/controllers/admin/suspend_users_controller.rb
# frozen_string_literal: true class Admin::SuspendUsersController < Admin::BaseController # IDs can be separated by whitespaces or commas ID_DELIMITER_REGEX = /\s|,/ SUSPEND_REASONS = [ "Violating our terms of service", "Creating products that violate our ToS", "Using Gumroad to commit fraud", "Using Gumroad for posting spam or SEO manipulation", ].freeze def show @title = "Mass-suspend users" render inertia: "Admin/SuspendUsers/Show", props: { suspend_reasons: SUSPEND_REASONS } end def update user_ids = suspend_users_params[:identifiers].split(ID_DELIMITER_REGEX).select(&:present?) reason = suspend_users_params[:reason] additional_notes = suspend_users_params[:additional_notes].presence.try(:strip) SuspendUsersWorker.perform_async(current_user.id, user_ids, reason, additional_notes) redirect_to admin_suspend_users_url, notice: "User suspension in progress!", status: :see_other end private def suspend_users_params params.require(:suspend_users).permit(:identifiers, :reason, :additional_notes) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/block_email_domains_controller.rb
app/controllers/admin/block_email_domains_controller.rb
# frozen_string_literal: true class Admin::BlockEmailDomainsController < Admin::BaseController include MassBlocker def show @title = "Mass-block email domains" render inertia: "Admin/BlockEmailDomains/Show" end def update schedule_mass_block(identifiers: email_domains_params[:identifiers], object_type: "email_domain") redirect_to admin_block_email_domains_url, status: :see_other, notice: "Email domains blocked successfully!" end private def email_domains_params params.require(:email_domains).permit(:identifiers) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/unblock_email_domains_controller.rb
app/controllers/admin/unblock_email_domains_controller.rb
# frozen_string_literal: true class Admin::UnblockEmailDomainsController < Admin::BaseController include MassUnblocker def show @title = "Mass-unblock email domains" render inertia: "Admin/UnblockEmailDomains/Show" end def update schedule_mass_unblock(identifiers: email_domains_params[:identifiers]) redirect_to admin_unblock_email_domains_url, status: :see_other, notice: "Email domains unblocked successfully!" end private def email_domains_params params.require(:email_domains).permit(:identifiers) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/merchant_accounts_controller.rb
app/controllers/admin/merchant_accounts_controller.rb
# frozen_string_literal: true class Admin::MerchantAccountsController < Admin::BaseController def show if !MerchantAccount.external_id?(params[:external_id]) && merchant_account = MerchantAccount.find_by(id: params[:external_id]) return redirect_to admin_merchant_account_path(merchant_account.external_id) end @merchant_account = MerchantAccount.find_by_external_id(params[:external_id]) || MerchantAccount.find_by(charge_processor_merchant_id: params[:external_id]) || e404 @title = "Merchant Account #{@merchant_account.external_id}" render inertia: "Admin/MerchantAccounts/Show", props: { merchant_account: Admin::MerchantAccountPresenter.new(merchant_account: @merchant_account).props } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/links_controller.rb
app/controllers/admin/links_controller.rb
# frozen_string_literal: true class Admin::LinksController < Admin::BaseController before_action :fetch_product!, except: :show def show if !Link.external_id?(params[:external_id]) && product = Link.find_by(id: params[:external_id]) return redirect_to admin_product_path(product.external_id) end product_by_external_id = Link.find_by_external_id(params[:external_id]) @product_matches = product_by_external_id ? [product_by_external_id] : Link.by_general_permalink(params[:external_id]) if @product_matches.many? @title = "Multiple products matched" render inertia: "Admin/Products/MultipleMatches", legacy_template: "admin/links/multiple_matches", props: { product_matches: @product_matches.map { |product| Admin::ProductPresenter::MultipleMatches.new(product:).props } } elsif @product_matches.one? @product = @product_matches.first @title = @product.name render inertia: "Admin/Products/Show", legacy_template: "admin/links/show", props: { title: @product.name, product: Admin::ProductPresenter::Card.new(product: @product, pundit_user:).props, user: Admin::UserPresenter::Card.new(user: @product.user, pundit_user:).props } else e404 end end def destroy @product.delete! render json: { success: true } end def generate_url_redirect url_redirect = UrlRedirect.create!(link: @product) url_redirect.admin_generated = true url_redirect.save! redirect_to url_redirect.download_page_url end def restore render json: { success: @product.update_attribute(:deleted_at, nil) } end def publish begin @product.publish! rescue Link::LinkInvalid, WithProductFilesInvalid return render json: { success: false, error_message: @product.errors.full_messages.join(", ") } rescue => e Bugsnag.notify(e) return render json: { success: false, error_message: I18n.t(:error_500) } end render json: { success: true } end def unpublish @product.unpublish! render json: { success: true } end def is_adult @product.is_adult = params[:is_adult] @product.save! render json: { success: true } end def access_product_file url_redirect = @product.url_redirects.build product_file = ProductFile.find_by_external_id(params[:product_file_id]) redirect_to url_redirect.signed_location_for_file(product_file), allow_other_host: true end def legacy_purchases if parse_boolean(params[:is_affiliate_user]) affiliate_user = User.find(params[:user_id]) sales = Purchase.where(link_id: @product.id, affiliate_id: affiliate_user.direct_affiliate_accounts.select(:id)) else sales = @product.sales end @purchases = sales.where("purchase_state IN ('preorder_authorization_successful', 'preorder_concluded_unsuccessfully', 'successful', 'failed', 'not_charged')").exclude_not_charged_except_free_trial @purchases = @purchases.order("created_at DESC, id DESC").page_with_kaminari(params[:page]).per(params[:per_page]) respond_to do |format| purchases_json = @purchases.as_json(admin_review: true) format.json { render json: { purchases: purchases_json, page: params[:page].to_i } } end end def flag_seller_for_tos_violation user = @product.user suspend_tos_reason = params.try(:[], :suspend_tos).try(:[], :reason) || params[:reason] raise "Invalid request" if user.nil? || !suspend_tos_reason raise "Cannot flag for TOS violation" if !user.can_flag_for_tos_violation? ActiveRecord::Base.transaction do user.update!(tos_violation_reason: suspend_tos_reason) comment_content = "Flagged for a policy violation on #{Time.current.to_fs(:formatted_date_full_month)} for a product named '#{@product.name}' (#{suspend_tos_reason})" user.flag_for_tos_violation!(author_id: current_user.id, product_id: @product.id, content: comment_content) unpublish_or_delete_product!(@product) end render json: { success: true } rescue => e render json: { success: false, error_message: e.message } end def views_count if request.format.json? render json: { views_count: @product.number_of_views } else render layout: false end end def sales_stats if request.format.json? render json: { sales_stats: { preorder_state: @product.is_in_preorder_state, count: @product.is_in_preorder_state ? @product.sales.preorder_authorization_successful.count : @product.sales.successful.count, stripe_failed_count: @product.is_in_preorder_state ? @product.sales.preorder_authorization_failed.stripe_failed.count : @product.sales.stripe_failed.count, balance_formatted: @product.balance_formatted } } else render layout: false end end def join_discord integration = @product.get_integration(DiscordIntegration.name) return render plain: "No Discord integration found for this product." if integration.nil? discord_api = DiscordApi.new oauth_response = discord_api.oauth_token(params[:code], oauth_redirect_integrations_discord_index_url(host: DOMAIN, protocol: PROTOCOL)) access_token = oauth_response.parsed_response&.dig("access_token") return render plain: "Failed to get access token from Discord, try re-authorizing." unless oauth_response.success? && access_token.present? begin user_response = discord_api.identify(access_token) user = JSON.parse(user_response) add_member_response = discord_api.add_member(integration.server_id, user["id"], access_token) return render plain: "Failed to join Discord Channel: #{integration.server_name}, please try again later." unless add_member_response.code === 201 || add_member_response.code === 204 discord_redirect_uri = fetch_discord_redirect_uri(@product) return render plain: "Failed to get valid Discord Channel URI, please try again later." if discord_redirect_uri.nil? redirect_to discord_redirect_uri, allow_other_host: true rescue Discordrb::Errors::CodeError, Discordrb::Errors::NoPermission => e render plain: "Unexpected error response from Discord API: #{e.message}" end end def join_discord_redirect discord_oauth_url = "https://www.discord.com/api/oauth2/authorize" params = { "response_type" => "code", "redirect_uri" => oauth_redirect_integrations_discord_index_url(host: DOMAIN, protocol: PROTOCOL), "scope" => "identify guilds.join", "client_id" => DISCORD_CLIENT_ID, "state" => { is_admin: true, product_id: ObfuscateIds.encrypt(@product.id) }.to_json } redirect_uri = "#{discord_oauth_url}?#{params.to_query}" redirect_to(redirect_uri, allow_other_host: true) end private def fetch_product! @product = Link.find_by_external_id(params[:external_id]) @product || e404 end def unpublish_or_delete_product!(product) product.is_tiered_membership? ? product.unpublish! : product.delete! end def fetch_discord_redirect_uri(product) discord_integration = product.get_integration(DiscordIntegration.name) return nil if discord_integration.nil? begin URI.parse("https://discord.com/channels/#{discord_integration.server_id}/").to_s rescue URI::InvalidURIError nil end end def parse_boolean(value) value == "true" ? true : false end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/paydays_controller.rb
app/controllers/admin/paydays_controller.rb
# frozen_string_literal: true class Admin::PaydaysController < Admin::BaseController # Pay the seller for all their balances up to and including `params[:payout_period_end_date]`. def pay_user user = User.find(params[:id]) date = Date.parse(payday_params[:payout_period_end_date]) payout_processor_type = if payday_params[:payout_processor] == PayoutProcessorType::STRIPE PayoutProcessorType::STRIPE elsif payday_params[:payout_processor] == PayoutProcessorType::PAYPAL user.update!(should_paypal_payout_be_split: true) if payday_params[:should_split_the_amount].present? PayoutProcessorType::PAYPAL end payments = Payouts.create_payments_for_balances_up_to_date_for_users(date, payout_processor_type, [user], from_admin: true) if request.format.json? payment = payments.first&.first if payment.blank? || payment.failed? render json: { message: payment&.errors&.full_messages&.first || "Payment was not sent." }, status: :unprocessable_entity else head :no_content end else redirect_to admin_user_url(user), notice: payments.first.present? && !payments.first.first.failed? ? "Payment was sent." : "Payment was not sent." end end private def payday_params params.require(:payday).permit(:payout_period_end_date, :payout_processor, :should_split_the_amount) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/purchases_controller.rb
app/controllers/admin/purchases_controller.rb
# frozen_string_literal: true class Admin::PurchasesController < Admin::BaseController before_action :fetch_purchase, only: %i[cancel_subscription refund refund_for_fraud refund_taxes_only resend_receipt show sync_status_with_charge_processor block_buyer unblock_buyer undelete update_giftee_email] def cancel_subscription if @purchase.subscription @purchase.subscription.cancel!(by_seller: params[:by_seller] == "true", by_admin: true) render json: { success: true } else render json: { success: false } end end def refund if @purchase.refund_and_save!(current_user.id) render json: { success: true } else render json: { success: false } end end def refund_for_fraud if @purchase.refund_for_fraud_and_block_buyer!(current_user.id) render json: { success: true } else render json: { success: false } end end def refund_taxes_only e404 if @purchase.nil? if @purchase.refund_gumroad_taxes!(refunding_user_id: current_user.id, note: params[:note], business_vat_id: params[:business_vat_id]) render json: { success: true } else render json: { success: false, message: @purchase.errors.full_messages.presence&.to_sentence || "No refundable taxes available" } end end def resend_receipt if @purchase if params[:resend_receipt][:email_address].present? @purchase.email = params[:resend_receipt][:email_address] @purchase.save! if @purchase.subscription.present? && !@purchase.is_original_subscription_purchase? @purchase.original_purchase.update!(email: params[:resend_receipt][:email_address]) end user = User.alive.find_by(email: @purchase.email) @purchase.attach_to_user_and_card(user, nil, nil) if user end @purchase.resend_receipt render json: { success: true } else e404_json end rescue ActiveRecord::RecordInvalid => e render json: { message: e.message }, status: :unprocessable_content end def show e404 if @purchase.nil? @product = @purchase.link @title = "Purchase #{@purchase.external_id}" purchase = Admin::PurchasePresenter.new(@purchase).props render( inertia: "Admin/Purchases/Show", props: { purchase:, product: Admin::ProductPresenter::Card.new(product: @product, pundit_user:).props, user: Admin::UserPresenter::Card.new(user: @product.user, pundit_user:).props }, ) end def sync_status_with_charge_processor @purchase.sync_status_with_charge_processor(mark_as_failed: true) end def block_buyer @purchase.block_buyer!(blocking_user_id: current_user.id) render json: { success: true } rescue => e render json: { success: false, message: e.message } end def unblock_buyer if @purchase.buyer_blocked? @purchase.unblock_buyer! comment_content = "Buyer unblocked by Admin (#{current_user.email})" @purchase.comments.create!(content: comment_content, comment_type: "note", author_id: current_user.id) if @purchase.purchaser.present? @purchase.purchaser.comments.create!(content: comment_content, comment_type: "note", author: current_user, purchase: @purchase) end end render json: { success: true } rescue => e render json: { success: false, message: e.message } end def undelete e404 if @purchase.nil? begin if @purchase.is_deleted_by_buyer? @purchase.update!(is_deleted_by_buyer: false) comment_content = "Purchase undeleted by Admin (#{current_user.email})" @purchase.comments.create!(content: comment_content, comment_type: "note", author_id: current_user.id) if @purchase.purchaser.present? @purchase.purchaser.comments.create!(content: comment_content, comment_type: "note", author: current_user, purchase: @purchase) end end render json: { success: true } rescue => e render json: { success: false, message: e.message } end end def update_giftee_email new_giftee_email = params[:giftee_email] if (gift = @purchase.gift_given).present? && new_giftee_email != gift.giftee_email giftee_purchase = Purchase.find_by(id: gift.giftee_purchase_id) if giftee_purchase.present? gift.update!(giftee_email: new_giftee_email) giftee_purchase.update!(email: new_giftee_email) giftee_purchase.resend_receipt redirect_to admin_purchase_path(@purchase.external_id) else render json: { success: false, message: "This gift is missing a giftee purchase. Please ask an engineer to generate one with script here: https://github.com/gumroad/web/issues/17248#issuecomment-784478299", } end end end private def fetch_purchase if !Purchase.external_id?(params[:external_id]) && purchase = Purchase.find_by(id: params[:external_id]) return redirect_to admin_purchase_path(purchase.external_id) end @purchase = Purchase.find_by_external_id(params[:external_id]) @purchase ||= Purchase.find_by_external_id_numeric(params[:external_id].to_i) @purchase ||= Purchase.find_by_stripe_transaction_id(params[: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/admin/dashboard_controller.rb
app/controllers/admin/dashboard_controller.rb
# frozen_string_literal: true class Admin::DashboardController < Admin::BaseController end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/affiliates_controller.rb
app/controllers/admin/affiliates_controller.rb
# frozen_string_literal: true class Admin::AffiliatesController < Admin::BaseController include Pagy::Backend include Admin::ListPaginatedUsers before_action :fetch_affiliate, only: [:show] before_action :clean_search_query, only: [:index] before_action :fetch_users_from_query, only: [:index] helper Pagy::UrlHelpers def index @title = "Affiliate results" @users = @users.joins(:direct_affiliate_accounts).distinct @users = @users.with_blocked_attributes_for(:form_email, :form_email_domain) list_paginated_users users: @users, template: "Admin/Affiliates/Index", legacy_template: "admin/affiliates/index", single_result_redirect_path: method(:admin_affiliate_path) end def show @title = "#{@affiliate_user.display_name} affiliate on Gumroad" respond_to do |format| format.html do render inertia: "Admin/Affiliates/Show", props: { user: Admin::UserPresenter::Card.new(user: @affiliate_user, pundit_user:).props, } end format.json { render json: @affiliate_user } end end private def fetch_affiliate @affiliate_user = User.find_by(username: params[:id]) @affiliate_user ||= User.find_by(id: params[:id]) @affiliate_user ||= User.find_by_external_id(params[:id].gsub(/^ext-/, "")) e404 if @affiliate_user.nil? || @affiliate_user.direct_affiliate_accounts.blank? end def clean_search_query @raw_query = params[:query].strip @query = "%#{@raw_query}%" end def fetch_users_from_query @users = User.where(email: @raw_query).order(created_at: :desc, id: :desc) if EmailFormatValidator.valid?(@raw_query) @users ||= User.where("external_id = ? or email like ? or name like ?", @raw_query, @query, @query).order(created_at: :desc, id: :desc) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users_controller.rb
app/controllers/admin/users_controller.rb
# frozen_string_literal: true class Admin::UsersController < Admin::BaseController include Admin::FetchUser include MassTransferPurchases skip_before_action :require_admin!, if: :request_from_iffy?, only: %i[suspend_for_fraud_from_iffy mark_compliant_from_iffy flag_for_explicit_nsfw_tos_violation_from_iffy] before_action :fetch_user, except: %i[block_ip_address] def show @title = "#{@user.display_name} on Gumroad" respond_to do |format| format.html do render inertia: "Admin/Users/Show", props: { user: Admin::UserPresenter::Card.new(user: @user, pundit_user:).props, } end format.json { render json: @user } end end def refund_balance RefundUnpaidPurchasesWorker.perform_async(@user.id, current_user.id) render json: { success: true } end def verify @user.verified = !@user.verified @user.save! render json: { success: true } rescue => e render json: { success: false, message: e.message } end def enable @user.reactivate! render json: { success: true } end def update_email return if params[:update_email][:email_address].blank? @user.email = params[:update_email][:email_address] @user.save! render json: { success: true } rescue ActiveRecord::RecordInvalid => e render json: { message: e.message }, status: :unprocessable_entity end def reset_password @user.update!(password: SecureRandom.hex(24)) render json: { success: true, message: "New password is #{@user.password}" } end def confirm_email @user.confirm @user.save! render json: { success: true } end def disable_paypal_sales @user.update!(disable_paypal_sales: true) render json: { success: true } end def create_stripe_managed_account merchant_account = StripeMerchantAccountManager.create_account(@user, passphrase: Rails.application.credentials.strongbox_general_password, from_admin: true) render json: { success: true, message: "Merchant Account created, External ID: #{merchant_account.external_id} Stripe Account ID: #{merchant_account.charge_processor_merchant_id}", merchant_account_external_id: merchant_account.external_id, charge_processor_merchant_id: merchant_account.charge_processor_merchant_id } rescue MerchantRegistrationUserAlreadyHasAccountError render json: { success: false, message: "User already has a merchant account." } rescue MerchantRegistrationUserNotReadyError, Stripe::InvalidRequestError => e render json: { success: false, message: e.message } end def block_ip_address BlockedObject.block!( BLOCKED_OBJECT_TYPES[:ip_address], params[:ip_address], current_user.id, expires_in: BlockedObject::IP_ADDRESS_BLOCKING_DURATION_IN_MONTHS.months ) render json: { success: true } end def mark_compliant @user.mark_compliant!(author_id: current_user.id) render json: { success: true } end def invalidate_active_sessions @user.invalidate_active_sessions! render json: { success: true, message: "User has been signed out from all active sessions." } end def mass_transfer_purchases transfer = transfer_purchases(user: @user, new_email: mass_transfer_purchases_params[:new_email]) render json: { success: transfer[:success], message: transfer[:message] }, status: transfer[:status] end def mark_compliant_from_iffy @user.mark_compliant!(author_name: "iffy") render json: { success: true } rescue => e render json: { success: false, message: e.message } end def suspend_for_fraud unless @user.suspended? @user.suspend_for_fraud!(author_id: current_user.id) suspension_note = params.dig(:suspend_for_fraud, :suspension_note).presence if suspension_note @user.comments.create!( author_id: current_user.id, author_name: current_user.name, comment_type: Comment::COMMENT_TYPE_SUSPENSION_NOTE, content: suspension_note ) end end render json: { success: true } rescue => e render json: { success: false, message: e.message } end def suspend_for_fraud_from_iffy @user.flag_for_fraud!(author_name: "iffy") unless @user.flagged_for_fraud? || @user.on_probation? || @user.suspended? @user.suspend_for_fraud!(author_name: "iffy") unless @user.suspended? render json: { success: true } rescue => e render json: { success: false, message: e.message } end def flag_for_explicit_nsfw_tos_violation_from_iffy @user.flag_for_explicit_nsfw_tos_violation!(author_name: "iffy") unless @user.flagged_for_explicit_nsfw? render json: { success: true } rescue => e render json: { success: false, message: e.message } end def flag_for_fraud if !@user.flagged_for_fraud? && !@user.suspended_for_fraud? @user.flag_for_fraud!(author_id: current_user.id) flag_note = params.dig(:flag_for_fraud, :flag_note).presence if flag_note @user.comments.create!( author_id: current_user.id, author_name: current_user.name, comment_type: Comment::COMMENT_TYPE_FLAG_NOTE, content: flag_note ) end end render json: { success: true } rescue => e render json: { success: false, message: e.message } end def add_credit credit_params = params.require(:credit).permit(:credit_amount) credit_amount = credit_params[:credit_amount] if credit_amount.present? begin credit_amount_cents = (BigDecimal(credit_amount.to_s) * 100).round user_credit = Credit.create_for_credit!( user: @user, amount_cents: credit_amount_cents, crediting_user: current_user ) user_credit.notify_user if credit_amount_cents > 0 render json: { success: true, amount: credit_amount } rescue ArgumentError, Credit::Error => e render json: { success: false, message: e.message } end else render json: { success: false, message: "Credit amount is required" } end end def set_custom_fee custom_fee_per_thousand = params[:custom_fee_percent].present? ? (params[:custom_fee_percent].to_f * 10).round : nil @user.update!(custom_fee_per_thousand:) render json: { success: true } rescue ActiveRecord::RecordInvalid => e render json: { success: false, message: e.message }, status: :unprocessable_content end def toggle_adult_products @user.all_adult_products = !@user.all_adult_products @user.save! render json: { success: true } rescue => e render json: { success: false, message: e.message } end private def mass_transfer_purchases_params params.require(:mass_transfer_purchases).permit(:new_email) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/refund_queues_controller.rb
app/controllers/admin/refund_queues_controller.rb
# frozen_string_literal: true class Admin::RefundQueuesController < Admin::BaseController include Admin::ListPaginatedUsers def show @title = "Refund queue" @users = User.refund_queue list_paginated_users users: @users, template: "Admin/RefundQueues/Show", legacy_template: "admin/users/refund_queue" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/helper_actions_controller.rb
app/controllers/admin/helper_actions_controller.rb
# frozen_string_literal: true module Admin class HelperActionsController < BaseController before_action :load_user def impersonate redirect_to admin_impersonate_path(user_identifier: @user.external_id) end def stripe_dashboard merchant_account = @user.merchant_accounts.alive.stripe.first if merchant_account&.charge_processor_merchant_id redirect_to "https://dashboard.stripe.com/connect/accounts/#{merchant_account.charge_processor_merchant_id}", allow_other_host: true else head :not_found end end private def load_user @user = User.find_by!(external_id: params[:user_id]) rescue ActiveRecord::RecordNotFound head :not_found end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/comments_controller.rb
app/controllers/admin/comments_controller.rb
# frozen_string_literal: true class Admin::CommentsController < Admin::BaseController skip_before_action :require_admin!, if: :request_from_iffy? def create Comment.create!(comment_params) render json: { success: true } end private def comment_params permitted_params = params.require(:comment).permit(:commentable_id, :commentable_type, :author_id, :author_name, :content, :comment_type) permitted_params[:author_id] = current_user.id unless request_from_iffy? 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/admin/action_call_dashboard_controller.rb
app/controllers/admin/action_call_dashboard_controller.rb
# frozen_string_literal: true class Admin::ActionCallDashboardController < Admin::BaseController def index @title = "Action Call Dashboard" @admin_action_call_infos = AdminActionCallInfo.order(call_count: :desc, controller_name: :asc, action_name: :asc) render inertia: "Admin/ActionCallDashboard/Index", props: { admin_action_call_infos: @admin_action_call_infos.as_json(only: [:id, :controller_name, :action_name, :call_count]) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/base_controller.rb
app/controllers/admin/base_controller.rb
# frozen_string_literal: true class Admin::BaseController < ApplicationController include ActionView::Helpers::DateHelper, ActionView::Helpers::NumberHelper, AdminActionTracker, Impersonate layout "admin" inertia_share do { card_types: CreditCardUtility.card_types_for_react, compliance: { reasons: Compliance::TOS_VIOLATION_REASONS, default_reason: Compliance::DEFAULT_TOS_VIOLATION_REASON } } end before_action :require_admin! before_action :hide_layouts before_action do @body_id = "admin" @title = "Admin" end def index @title = "Admin" render inertia: "Admin/Base/Index" end def impersonate user = find_user(params[:user_identifier]) if user impersonate_user(user) redirect_to products_path else flash[:alert] = "User not found" redirect_to admin_path end end def unimpersonate stop_impersonating_user render json: { redirect_to: admin_url } end def redirect_to_stripe_dashboard user = find_user(params[:user_identifier]) if user merchant_account = user.merchant_accounts.alive.stripe.first if merchant_account&.charge_processor_merchant_id base_url = "https://dashboard.stripe.com" base_url += "/test" unless Rails.env.production? redirect_to "#{base_url}/connect/accounts/#{merchant_account.charge_processor_merchant_id}", allow_other_host: true else flash[:alert] = "Stripe account not found" redirect_to admin_path end else flash[:alert] = "User not found" redirect_to admin_path end end protected # Override render to allow serving Inertia-admin pages inside the legacy "admin_old" layout, for transitional/testing purposes. # # Normal usage: # - For standard HTML requests: use the default render behavior. # - For render(partial: ...): use the default render (do NOT use the admin_old layout). # - For requests with inertia: By default, use the normal layout. # - If params[:admin_old] is set and inertia is present: Render the React page server-side # but in the admin_old layout, and map each React prop to an instance variable # for legacy view compatibility. It looks for a template file based on the inertia name, # lowercased and suffixed with '_old' (e.g., Admin/Base/Index => admin/base/index_old). def render(*args, **kwargs) Rails.logger.warn("Warning: render(*args, **kwargs) is being overridden in Admin::BaseController") Rails.logger.warn("args: #{args.inspect}") Rails.logger.warn("kwargs: #{kwargs.inspect}") Rails.logger.warn("Make sure to remove this override when we are done migrating to Inertia.") return super(*args, **kwargs) unless request.format.html? return super(*args, **kwargs) if kwargs.key?(:partial) return super(*args, layout: "admin_old", **kwargs) unless kwargs.key?(:inertia) return super(*args, **kwargs) unless params[:admin_old] kwargs[:props] ||= {} kwargs[:props].each_key do |key| next if instance_variable_defined?("@#{key}") instance_variable_set("@#{key}", kwargs[:props][key]) end legacy_template = kwargs.delete(:legacy_template) || kwargs[:inertia].underscore render template: legacy_template, layout: "admin_old" end private def find_user(identifier) return nil if identifier.blank? User.find_by(external_id: identifier) || User.find_by(email: identifier) || User.find_by(username: identifier) || MerchantAccount.stripe.find_by(charge_processor_merchant_id: identifier)&.user end def user_not_authorized(exception) message = "You are not allowed to perform this action." if request.format.json? || request.format.js? render json: { success: false, error: message }, status: :unauthorized else flash[:alert] = message redirect_to root_path end end def request_from_iffy? ActiveSupport::SecurityUtils.secure_compare(params[:auth_token].to_s, GlobalConfig.get("IFFY_TOKEN")) end def require_admin! if current_user.nil? return e404_json if xhr_or_json_request? return redirect_to login_path(next: request.path) end unless current_user.is_team_member? return e404_json if xhr_or_json_request? redirect_to root_path end end def xhr_or_json_request? request.xhr? || request.format.json? end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/guids_controller.rb
app/controllers/admin/guids_controller.rb
# frozen_string_literal: true class Admin::GuidsController < Admin::BaseController include Admin::ListPaginatedUsers def show guid = params[:id] @title = guid @users = User.where(id: Event.by_browser_guid(guid).distinct.pluck(:user_id)) list_paginated_users users: @users, template: "Admin/Compliance/Guids/Show", legacy_template: "admin/compliance/guids/show" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/sales_reports_controller.rb
app/controllers/admin/sales_reports_controller.rb
# frozen_string_literal: true class Admin::SalesReportsController < Admin::BaseController def index @title = "Sales reports" render inertia: "Admin/SalesReports/Index", props: { countries: Compliance::Countries.for_select.map { |alpha2, name| [name, alpha2] }, sales_types: GenerateSalesReportJob::SALES_TYPES.map { [_1, _1.humanize] }, job_history: Admin::SalesReport.fetch_job_history } end def create sales_report = Admin::SalesReport.new(sales_report_params) if sales_report.valid? sales_report.generate_later redirect_to admin_sales_reports_path, status: :see_other, notice: "Sales report job enqueued successfully!" else redirect_to admin_sales_reports_path, inertia: { errors: sales_report.errors_hash }, alert: "Invalid form submission. Please fix the errors." end end private def sales_report_params params.require(:sales_report).permit(:country_code, :start_date, :end_date, :sales_type) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/payouts_controller.rb
app/controllers/admin/payouts_controller.rb
# frozen_string_literal: true class Admin::PayoutsController < Admin::BaseController before_action :fetch_payment, only: %i[show retry cancel fail sync] def show @title = "Payout" render inertia: "Admin/Payouts/Show", props: { payout: Admin::PaymentPresenter.new(payment: @payment).props } end def retry unless @payment.cancelled? || @payment.failed? || @payment.returned? return render json: { success: false, message: "Failed! Payout is not in a cancelled, failed or returned state." } end if @payment.user.payments.last != @payment return render json: { success: false, message: "Failed! This is not the most recent payout for this user." } end Payouts.create_payments_for_balances_up_to_date_for_users(@payment.payout_period_end_date, @payment.processor, [@payment.user], from_admin: true) render json: { success: true } end def cancel return render json: { success: false, message: "Failed! You can only cancel PayPal payouts." } unless @payment.processor == PayoutProcessorType::PAYPAL return render json: { success: false, message: "Failed! Payout is not in an unclaimed state." } unless @payment.unclaimed? @payment.with_lock do @payment.mark_cancelled! end render json: { success: true, message: "Marked as cancelled." } end def fail error_message = if !@payment.processing? "Failed! Payout is not in the processing state." elsif @payment.created_at > 2.days.ago "Failed! Payout can be marked as failed only two days after creation." end return render json: { success: false, message: error_message } if error_message @payment.with_lock do @payment.correlation_id = "Marked as failed by user with ID #{current_user.id}" @payment.mark_failed! end render json: { success: true, message: "Marked as failed." } end def sync return render json: { success: false, message: "Failed! You can only sync PayPal payouts." } unless @payment.processor == PayoutProcessorType::PAYPAL return render json: { success: false, message: "Failed! Payout is already in terminal state." } unless Payment::NON_TERMINAL_STATES.include?(@payment.state) @payment.with_lock do @payment.sync_with_payout_processor end if @payment.errors.empty? render json: { success: true, message: "Synced!" } else render json: { success: false, message: @payment.errors.first.message } end end private def fetch_payment @payment = Payment.find_by(id: params[:id]) || e404 end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/unreviewed_users_controller.rb
app/controllers/admin/unreviewed_users_controller.rb
# frozen_string_literal: true class Admin::UnreviewedUsersController < Admin::BaseController def index @title = "Unreviewed users" cached_data = Admin::UnreviewedUsersService.cached_users_data if cached_data.blank? render inertia: "Admin/UnreviewedUsers/Index", props: { users: [], total_count: 0, cutoff_date: Admin::UnreviewedUsersService.cutoff_date.to_s } return end user_ids = cached_data[:users].map { |u| u[:id] } still_unreviewed_ids = User.where(id: user_ids, user_risk_state: "not_reviewed").pluck(:id).to_set still_unreviewed_users = cached_data[:users].select { |u| still_unreviewed_ids.include?(u[:id]) } render inertia: "Admin/UnreviewedUsers/Index", props: { users: still_unreviewed_users, total_count: cached_data[:total_count], cutoff_date: cached_data[:cutoff_date] } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/search_controller.rb
app/controllers/admin/search_controller.rb
# frozen_string_literal: true class Admin::SearchController < Admin::BaseController before_action :clean_search_query RECORDS_PER_PAGE = 25 private_constant :RECORDS_PER_PAGE def users @title = "User results" @users = User.where(email: @raw_query).order("created_at DESC").limit(25) if EmailFormatValidator.valid?(@raw_query) @users ||= User.where("external_id = ? or email like ? or name like ?", @raw_query, @query, @query).order("created_at DESC").limit(RECORDS_PER_PAGE) @users = @users.with_blocked_attributes_for(:form_email, :form_email_domain) redirect_to admin_user_path(@users.first) if @users.length == 1 end def purchases @title = "Purchase results" @purchases = AdminSearchService.new.search_purchases( query: @raw_query, product_title_query: params[:product_title_query]&.strip, purchase_status: params[:purchase_status], ) @purchases = @purchases.page_with_kaminari(params[:page]).per(RECORDS_PER_PAGE) if @purchases.present? redirect_to admin_purchase_path(@purchases.first.external_id) if @purchases.one? && params[:page].blank? end private def clean_search_query @raw_query = params[:query].strip @query = "%#{@raw_query}%" end def set_title @title = "Search for #{@raw_query}" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/purchases/comments_controller.rb
app/controllers/admin/purchases/comments_controller.rb
# frozen_string_literal: true class Admin::Purchases::CommentsController < Admin::BaseController include Admin::Commentable private def commentable Purchase.find_by_external_id!(params[: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/admin/affiliates/products_controller.rb
app/controllers/admin/affiliates/products_controller.rb
# frozen_string_literal: true class Admin::Affiliates::ProductsController < Admin::Affiliates::BaseController include Admin::Users::ListPaginatedProducts def index @title = "#{@affiliate_user.display_name} products on Gumroad" list_paginated_products user: @affiliate_user, products: @affiliate_user.directly_affiliated_products.unscope(where: :purchase_disabled_at).order(Admin::Users::ListPaginatedProducts::PRODUCTS_ORDER), inertia_template: "Admin/Affiliates/Products/Index" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/affiliates/base_controller.rb
app/controllers/admin/affiliates/base_controller.rb
# frozen_string_literal: true class Admin::Affiliates::BaseController < Admin::BaseController before_action :set_affiliate_user private def set_affiliate_user @affiliate_user = User.find(params[:affiliate_id]) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/affiliates/products/purchases_controller.rb
app/controllers/admin/affiliates/products/purchases_controller.rb
# frozen_string_literal: true class Admin::Affiliates::Products::PurchasesController < Admin::Affiliates::Products::BaseController include Pagy::Backend def index scope = @product.sales.for_affiliate_user(@affiliate_user) pagination, purchases = pagy_countless( scope.for_admin_listing.includes(:subscription, :price, :refunds), limit: params[:per_page], page: params[:page], countless_minimal: true ) render json: { purchases: purchases.as_json(admin_review: true), pagination: } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/affiliates/products/base_controller.rb
app/controllers/admin/affiliates/products/base_controller.rb
# frozen_string_literal: true class Admin::Affiliates::Products::BaseController < Admin::Affiliates::BaseController before_action :set_product private def set_product @product = Link.find_by_external_id!(params[:product_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/admin/compliance/cards_controller.rb
app/controllers/admin/compliance/cards_controller.rb
# frozen_string_literal: true class Admin::Compliance::CardsController < Admin::BaseController def refund if params[:stripe_fingerprint].blank? render json: { success: false } else purchases = Purchase.not_chargedback_or_chargedback_reversed.paid.where(stripe_fingerprint: params[:stripe_fingerprint]).select(:id) purchases.find_each do |purchase| RefundPurchaseWorker.perform_async(purchase.id, current_user.id, Refund::FRAUD) end render json: { success: true } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/products/purchases_controller.rb
app/controllers/admin/products/purchases_controller.rb
# frozen_string_literal: true class Admin::Products::PurchasesController < Admin::Products::BaseController include Pagy::Backend def index pagination, purchases = pagy_countless( @product.sales.for_admin_listing.includes(:subscription, :price, :refunds), limit: params[:per_page], page: params[:page], countless_minimal: true ) render json: { purchases: purchases.as_json(admin_review: true), pagination: } end def mass_refund_for_fraud external_ids = params[:purchase_ids].reject(&:blank?).uniq if external_ids.empty? render json: { success: false, message: "Select at least one purchase." }, status: :unprocessable_entity return end purchases_relation = @product.sales.by_external_ids(external_ids) found_external_ids = purchases_relation.map(&:external_id) missing_external_ids = external_ids - found_external_ids if missing_external_ids.any? render json: { success: false, message: "Some purchases are invalid for this product." }, status: :unprocessable_entity return end MassRefundForFraudJob.perform_async(@product.id, external_ids, current_user.id) render json: { success: true, message: "Processing #{external_ids.size} fraud refunds..." } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/products/comments_controller.rb
app/controllers/admin/products/comments_controller.rb
# frozen_string_literal: true class Admin::Products::CommentsController < Admin::Products::BaseController include Admin::Commentable private def commentable @product end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/products/base_controller.rb
app/controllers/admin/products/base_controller.rb
# frozen_string_literal: true class Admin::Products::BaseController < Admin::BaseController before_action :set_product private def set_product @product = Link.find_by_external_id!(params[:product_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/admin/products/staff_picked_controller.rb
app/controllers/admin/products/staff_picked_controller.rb
# frozen_string_literal: true class Admin::Products::StaffPickedController < Admin::Products::BaseController include AfterCommitEverywhere def create authorize [:admin, :products, :staff_picked, @product] staff_picked_product = @product.staff_picked_product || @product.build_staff_picked_product staff_picked_product.update_as_not_deleted! 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/admin/products/details_controller.rb
app/controllers/admin/products/details_controller.rb
# frozen_string_literal: true class Admin::Products::DetailsController < Admin::Products::BaseController def show if @product.filegroup render json: { details: ProductPresenter.new(product: @product).admin_info } else render json: { details: 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/admin/products/infos_controller.rb
app/controllers/admin/products/infos_controller.rb
# frozen_string_literal: true class Admin::Products::InfosController < Admin::Products::BaseController def show render json: { info: @product.as_json(admin_info: true) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/email_changes_controller.rb
app/controllers/admin/users/email_changes_controller.rb
# frozen_string_literal: true class Admin::Users::EmailChangesController < Admin::Users::BaseController before_action :fetch_user def index render json: { email_changes: @user.versions_for(:email, :payment_address), fields: %w(email payment_address) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/merchant_accounts_controller.rb
app/controllers/admin/users/merchant_accounts_controller.rb
# frozen_string_literal: true class Admin::Users::MerchantAccountsController < Admin::Users::BaseController before_action :fetch_user def index render json: { merchant_accounts: @user.merchant_accounts.as_json(only: %i[charge_processor_id], methods: %i[external_id alive charge_processor_alive]), has_stripe_account: @user.merchant_accounts.alive.charge_processor_alive.stripe.any? } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/stats_controller.rb
app/controllers/admin/users/stats_controller.rb
# frozen_string_literal: true class Admin::Users::StatsController < Admin::Users::BaseController include CurrencyHelper before_action :fetch_user def index render json: { total: formatted_dollar_amount(@user.sales_cents_total), balance: @user.balance_formatted, chargeback_volume: @user.lost_chargebacks[:volume], chargeback_count: @user.lost_chargebacks[:count] } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/products_controller.rb
app/controllers/admin/users/products_controller.rb
# frozen_string_literal: true class Admin::Users::ProductsController < Admin::Users::BaseController include Admin::Users::ListPaginatedProducts before_action :fetch_user def index @title = "#{@user.display_name} products on Gumroad" list_paginated_products user: @user, products: @user.products, inertia_template: "Admin/Users/Products/Index" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/comments_controller.rb
app/controllers/admin/users/comments_controller.rb
# frozen_string_literal: true class Admin::Users::CommentsController < Admin::Users::BaseController include Admin::Commentable before_action :fetch_user private def commentable @user end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/base_controller.rb
app/controllers/admin/users/base_controller.rb
# frozen_string_literal: true class Admin::Users::BaseController < Admin::BaseController include Admin::FetchUser protected def user_param params[:user_id] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/guids_controller.rb
app/controllers/admin/users/guids_controller.rb
# frozen_string_literal: true class Admin::Users::GuidsController < Admin::Users::BaseController def index guids = Event.where(user_id: user_param).distinct.pluck(:browser_guid) guids_to_users = Event.select(:user_id, :browser_guid).by_browser_guid(guids). where.not(user_id: nil).distinct.group_by(&:browser_guid). map { |browser_guid, events| { guid: browser_guid, user_ids: events.map(&:user_id) } } render json: guids_to_users end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false