You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

140 lines
2.9 KiB

class Admin::AdminController < ApplicationController
layout 'admin'
# The admin has two roles: Admin, who gets everything, and Guest (the `user`
# role), who gets a read-only slice -- the analytics dashboard and the
# published leaderboard. Listed by controller name.
GUEST_SECTIONS = %w[analytics leaderboard].freeze
# The nav sections in the order they appear in the sidebar.
ADMIN_SECTIONS = %i[analytics leaderboard nodes assets].freeze
before_action :authenticate_user!
before_action :only_permitted_section!
before_action :set_locale_to_default
helper_method :current_user
helper_method :user_signed_in?
helper_method :form_locale, :available_locales
helper_method :admin?, :permitted_admin_sections
# DELETE admin/cache/clear
def clear_cache
Rails.cache.clear
respond_to do |format|
format.turbo_stream { flash.now[:notice] = t(:cache_cleared, scope: 'utils') }
end
end
private
def default_url_options
{ locale: I18n.locale }
end
def set_locale_to_default
I18n.locale = I18n.default_locale
end
def form_locale
(params['form_locale'] || I18n.locale).to_s
end
def available_locales
@available_locales ||= I18n.available_locales.map(&:to_s).map(&:downcase).map{|v| v.sub('-', '_')}
end
def authenticate_user!
unless user_signed_in?
store_location
redirect_to admin_sessions_path
end
end
def admin?
current_user&.admin_role?
end
# What a Guest is allowed to open. Anything else bounces them to analytics
# rather than out of the admin entirely, so every link in the nav they see
# actually works and a stray URL doesn't log them out.
def only_permitted_section!
return if admin?
return if GUEST_SECTIONS.include?(controller_name)
bounce_guest!
end
# For the handful of actions inside a Guest section that still change
# something -- clearing a cache, say. Guests may look, not touch, so this
# cannot lean on the section check: the section itself is permitted.
def only_admin!
return if admin?
bounce_guest!
end
def bounce_guest!
redirect_to admin_analytics_path(locale: params[:locale] || I18n.default_locale)
end
def permitted_admin_sections
return ADMIN_SECTIONS if admin?
ADMIN_SECTIONS.select { |section| GUEST_SECTIONS.include?(section.to_s) }
end
def current_user
Current.user ||= authenticate_user_from_session
end
def authenticate_user_from_session
User.enabled.find_by(id: session[:user_id])
end
def user_signed_in?
current_user.present?
end
def login(user)
Current.user = user
reset_session
user.touch(:last_logon_at)
session[:user_id] = user.id
end
def logout(user)
Current.user = nil
reset_session
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def store_location
session[:return_to] = request.fullpath if request.get?
end
end