docbrown/app/controllers/application_controller.rb
rhymes 7ff882b8ce
Refactor Admin Member Detail view - Tools section (#14283)
* Test with Grid layout

* Use Flexbox

* Replace with utility classes

* Wire up Tools -> Emails

* Stash: will rebase with a better commit message

* Fix transition between Email and Tools component

* Refactor Verify Email Ownership button a bit

* Use respond_to for verify_email_ownership

* Wrap the Preact Snackbar controller in Stimulus and use it from users/tools/email_controller

* Add HTML5 validation to EmailComponent

* Validation and cleanup

* Add Email history list and fix styling

* Additional styling cleanups

* Add error handling

* Close panel after email operations

* Actually use <local-time> GitHub time element correctly

* Add specs for Tools component and controller

* Email to Emails

* Add tests for Admin::Users::Tools::EmailsComponent

* Fix bug with ToolsComponent instantiation in ToolsController

* Add notes to show page

* Add ToolsComponent css

* Use Rails UJS instead of manual Stimulus to connect remote helpers

* Make Notes section come alive by adding its code

* Make Credits section come alive by adding its code

* Go back to vertical flex

* Finalize small restructuring of credits code

* Simplify ToolsComponent instantiation

* Add basic Add user to org functionality

* Make update user permissions form work

* Make remove user from org work

* Use generic Stimulus AjaxController to cleanup code

* Use Stimulus AjaxController for NotesComponent

* Use Stimulus AjaxController for CreditsComponent

* Use Stimulus AjaxController for OrganizationsController

* Add Admin::Users::Tools::ReportsComponent

* Do not display snackbar message if there is no message

* Add Admin::Users::Tools::ReactionsComponent

* Fix EmailsComponent spec

* Add CreditsComponent tests

* Fix quotes

* Add OrganizationsComponent specs

* Add ReportsComponent spec

* Add ReactionsComponent spec

* Fix rubocop violation

* Fix ToolsComponent specs

* Remove unused variable

* More tests

* Use keyword argument for ToolsComponent

* Fill in Tools requests specs

* Use Rspec shared_examples for ToolsController and EmailsController

* Add tests for Admin::Users::Tools::CreditsController

* Add tests for Admin::Users::Tools::NotesController

* Add tests for Admin::Users::Tools::OrganizationsController

* Add tests for Admin::Users::Tools::ReactionsController and ReportsController

* Fix bugs and add tests to Admin::OrganizationMembershipsController

* Add comments to deprecated sections of the UsersController

* Fix bugs and add tests to Admin::UsersController #send_email and #verify_email_ownership

* Add User model tests

* Feature flag fixes

* Add Cypress Tools - Emails tests

* Add Cypress Tools - Notes tests

* Add Cypress Tools - Credits tests

* Add Cypress Tools - Organizations tests

* Add Cypress Tools - Reports and Reactions tests

* Mark the replace target as a polite region

* Update view_component gem

* Tiny fixes

* Fix spec

* Wrap component rendering in render_component

* Move user.related_negative_reactions to a Reaction scope

* Move user.reports to a FeedbackMessage scope

* Move user.last_verification_date as EmailAuthorization class method

* Revert encapsulation to private

* Fix boxes backlinks names

* Add keyboard focus styling to boxes

* Remove duplicate styling

* Remove duplicated header element

* Improve heading hiearchy

* Fix <legend> and labels

* Backlink should be Tools not Users

* Announce section change to screen reader and fix focus

* Fix specs

* Add focus style for backlinks

* Enable email sending in e2e mode

* Use Settings instead of env variable
2021-08-17 18:55:53 +02:00

224 lines
6.5 KiB
Ruby

class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
skip_before_action :track_ahoy_visit
before_action :verify_private_forem
protect_from_forgery with: :exception, prepend: true
before_action :remember_cookie_sync
before_action :forward_to_app_config_domain
include SessionCurrentUser
include ValidRequest
include Pundit
include CachingHeaders
include ImageUploads
include VerifySetupCompleted
include DevelopmentDependencyChecks if Rails.env.development?
include EdgeCacheSafetyCheck unless Rails.env.production?
include Devise::Controllers::Rememberable
rescue_from ActionView::MissingTemplate, with: :routing_error
rescue_from RateLimitChecker::LimitReached do |exc|
error_too_many_requests(exc)
end
rescue_from ActionController::InvalidAuthenticityToken do
ForemStatsClient.increment(
"users.invalid_authenticity_token",
tags: ["controller_name:#{controller_name}", "path:#{request.fullpath}"],
)
end
PUBLIC_CONTROLLERS = %w[async_info
confirmations
deep_links
ga_events
health_checks
instances
invitations
omniauth_callbacks
passwords
registrations
service_worker
shell].freeze
private_constant :PUBLIC_CONTROLLERS
CONTENT_CHANGE_PATHS = [
"/tags/onboarding", # Needs to change when suggested_tags is edited.
"/onboarding", # Page is cached at edge.
"/", # Page is cached at edge.
].freeze
private_constant :CONTENT_CHANGE_PATHS
def verify_private_forem
return if controller_name.in?(PUBLIC_CONTROLLERS)
return if self.class.module_parent.to_s == "Admin"
return if user_signed_in? || Settings::UserExperience.public
if api_action?
authenticate!
elsif (@page = Page.landing_page)
render template: "pages/show"
else
@user ||= User.new
render template: "devise/registrations/new"
end
end
def not_found
raise ActiveRecord::RecordNotFound, "Not Found"
end
def routing_error
raise ActionController::RoutingError, "Routing Error"
end
def not_authorized
render json: "Error: not authorized", status: :unauthorized
raise NotAuthorizedError, "Unauthorized"
end
def bad_request
render json: "Error: Bad Request", status: :bad_request
end
def error_too_many_requests(exc)
response.headers["Retry-After"] = exc.retry_after
render json: { error: exc.message, status: 429 }, status: :too_many_requests
end
def authenticate_user!
if current_user
Honeycomb.add_field("current_user_id", current_user.id)
return
end
respond_to do |format|
format.html { redirect_to sign_up_path }
format.json { render json: { error: "Please sign in" }, status: :unauthorized }
end
end
def redirect_permanently_to(location)
redirect_to location + internal_nav_param, status: :moved_permanently
end
def customize_params
params[:signed_in] = user_signed_in?.to_s
end
# This method is used by Devise to decide which is the path to redirect
# the user to after a successful log in
def after_sign_in_path_for(resource)
if current_user.saw_onboarding
path = stored_location_for(resource) || request.env["omniauth.origin"] || root_path(signin: "true")
signin_param = { "signin" => "true" } # the "signin" param is used by the service worker
uri = Addressable::URI.parse(path)
uri.query_values = if uri.query_values
uri.query_values.merge(signin_param)
else
signin_param
end
uri.to_s
else
referrer = request.env["omniauth.origin"] || "none"
onboarding_path(referrer: referrer)
end
end
def after_accept_path_for(_resource)
onboarding_path
end
def raise_suspended
raise SuspendedError if current_user&.suspended?
end
def internal_navigation?
params[:i] == "i"
end
helper_method :internal_navigation?
def feed_style_preference
# TODO: Future functionality will let current_user override this value with UX preferences
# if current_user exists and has a different preference.
Settings::UserExperience.feed_style
end
helper_method :feed_style_preference
def set_no_cache_header
response.headers["Cache-Control"] = "no-cache, no-store"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end
def rate_limit!(action)
rate_limiter.check_limit!(action)
end
def rate_limiter
(current_user || anonymous_user).rate_limiter
end
def anonymous_user
User.new(ip_address: request.env["HTTP_FASTLY_CLIENT_IP"])
end
def api_action?
self.class.to_s.start_with?("Api::")
end
def initialize_stripe
Stripe.api_key = Settings::General.stripe_api_key
return unless Rails.env.development? && Stripe.api_key.present?
Stripe.log_level = Stripe::LEVEL_INFO
end
def remember_cookie_sync
# Set remember cookie token in case not properly set.
if user_signed_in? &&
cookies[:remember_user_token].blank?
current_user.remember_me = true
current_user.remember_me!
remember_me(current_user)
end
end
def forward_to_app_config_domain
# Let's only redirect get requests for this purpose.
return unless request.get? &&
# If the request equals the original set domain, e.g. forem-x.forem.cloud.
request.host == ENV["APP_DOMAIN"] &&
# If the app domain config has now been set, let's go there instead.
ENV["APP_DOMAIN"] != Settings::General.app_domain
redirect_to URL.url(request.fullpath)
end
def bust_content_change_caches
EdgeCache::Bust.call(CONTENT_CHANGE_PATHS)
Settings::General.admin_action_taken_at = Time.current # Used as cache key
end
# To ensure that components are sent back as HTML, we wrap their rendering in
# this helper method
def render_component(component_class, *args, **kwargs)
render component_class.new(*args, **kwargs), content_type: "text/html"
end
private
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: %i[username name profile_image profile_image_url])
end
def internal_nav_param
return "" unless params[:i] == "i"
"?i=i"
end
end