All Files (82.08% covered at 6.62 hits/line)
42 files in total.
904 relevant lines.
742 lines covered and
162 lines missed
- 1
class Admin::ConfigurationController < ApplicationController
# Admin::ConfigurationController handles the batch-updating of TrustyCms::Config entries.
# It accepts any set of config name-value pairs but is accessible only to administrators.
# Note that configuration is routed as a singular resource so we only deal with show/edit/update
# and the show and edit views determine what set of config values is shown and made editable.
- 1
before_action :initialize_config
- 1
only_allow_access_to :edit, :update,
:when => [:admin],
:denied_url => { :controller => 'admin/configuration', :action => 'show' },
:denied_message => 'You must have admin privileges to edit site configuration.'
- 1
def show
- 5
@user = current_user
- 5
render
end
- 1
def edit
- 1
render
end
- 1
def update
- 1
if params[:trusty_config]
- 1
begin
- 1
TrustyCms.config.transaction do
- 1
params[:trusty_config].each_pair do |key, value|
- 10
@trusty_config[key] = TrustyCms::Config.find_or_initialize_by(key: key)
- 10
@trusty_config[key].value = value # validation sets errors on @trusty_config['key'] that the helper methods will pick up
end
- 1
redirect_to :action => :show
end
rescue ActiveRecord::RecordInvalid => e
flash[:error] = "Configuration error: please check the form"
render :action => :edit
rescue TrustyCms::Config::ConfigError => e
flash[:error] = "Configuration error: #{e}"
render :action => :edit
end
end
end
- 1
protected
- 1
def initialize_config
- 7
@trusty_config = {}
end
end
- 1
class Admin::ExtensionsController < ApplicationController
- 1
only_allow_access_to :index,
:when => :admin,
:denied_url => { :controller => 'pages', :action => 'index' },
:denied_message => 'You must have administrative privileges to perform this action.'
- 1
def index
@template_name = 'index' # for Admin::RegionsHelper
@extensions = TrustyCms::Extension.descendants.sort_by { |e| e.extension_name }
end
end
- 1
class Admin::PagesController < Admin::ResourceController
- 1
before_action :initialize_meta_rows_and_buttons, :only => [:new, :edit, :create, :update]
- 1
before_action :count_deleted_pages, :only => [:destroy]
- 1
rescue_from ActiveRecord::RecordInvalid, :with => :validation_error
- 1
class PreviewStop < ActiveRecord::Rollback
- 1
def message
'Changes not saved!'
end
end
- 1
create_responses do |r|
- 1
r.plural.js do
@level = params[:level].to_i
@index = params[:index].to_i
@rendered_html = ""
@template_name = 'index'
self.models = Page.find(params[:page_id]).children.all
response.headers['Content-Type'] = 'text/html;charset=utf-8'
render :action => 'children.html.haml', :layout => false
end
end
- 1
def index
- 22
@homepage = Page.find_by_parent_id(nil)
- 22
response_for :plural
end
- 1
def new
- 2
@page = self.model = model_class.new_with_defaults(trusty_config)
- 2
assign_page_attributes
- 2
response_for :new
end
- 1
def preview
render_preview
rescue PreviewStop => exception
render :text => exception.message unless @performed_render
end
- 1
def save_table_position
new_position = params[:new_position]
Page.save_order(new_position)
head :ok
end
- 1
private
- 1
def validation_error(e)
flash[:error] = e.message
render :new
end
- 1
def assign_page_attributes
- 2
if params[:page_id].blank?
- 2
self.model.slug = '/'
end
- 2
self.model.parent_id = params[:page_id]
end
- 1
def model_class
- 222
if Page.descendants.any? { |d| d.to_s == params[:page_class] }
verify_page_class(params[:page_class])
- 74
elsif params[:page_id]
Page.find(params[:page_id]).children
else
- 74
Page
end
end
- 1
def render_preview
params.permit!
Page.transaction do
page_class = Page.descendants.include?(model_class) ? model_class : Page
if request.referer =~ %r{/admin/pages/(\d+)/edit}
page = Page.find($1).becomes(page_class)
layout_id = page.layout_id
page.update_attributes(params[:page])
page.published_at ||= Time.now
else
page = page_class.new(params[:page])
page.published_at = page.updated_at = page.created_at = Time.now
page.parent = Page.find($1) if request.referer =~ %r{/admin/pages/(\d+)/children/new}
end
page.pagination_parameters = pagination_parameters
process_with_exception(page)
end
end
- 1
def process_with_exception(page)
page.process(request, response)
@performed_render = true
render template: 'site/show_page', layout: false
raise PreviewStop
end
- 1
def count_deleted_pages
- 1
@count = model.children.count + 1
end
- 1
def initialize_meta_rows_and_buttons
- 4
@buttons_partials ||= []
- 4
@meta ||= []
- 4
@meta << {:field => "slug", :type => "text_field", :args => [{:class => 'textbox', :maxlength => 100}]}
- 4
@meta << {:field => "breadcrumb", :type => "text_field", :args => [{:class => 'textbox', :maxlength => 160}]}
end
- 1
def verify_page_class(page_class)
if page_class.constantize.ancestors.include?(Page)
page_class.constantize
else
raise "I'm not allowed to constantize #{page_class}!"
end
end
end
- 1
class Admin::PreferencesController < ApplicationController
- 1
before_action :initialize_variables
- 1
def show
- 1
set_standard_body_style
- 1
render :edit
end
- 1
def edit
render
end
- 1
def update
- 1
if @user.update_attributes(preferences_params)
- 1
redirect_to admin_configuration_path
else
flash[:error] = t('preferences_controller.error_updating')
render :edit
end
end
- 1
private
- 1
def initialize_variables
- 2
@user = current_user
- 2
@controller_name = 'user'
- 2
@template_name = 'preferences'
end
- 1
def preferences_params
- 1
params.require(:user).permit(:name, :email, :login, :password, :password_confirmation, :locale)
end
end
- 1
class Admin::UsersController < Admin::ResourceController
- 1
paginate_models
- 1
only_allow_access_to :index, :show, :new, :create, :edit, :update, :remove, :destroy,
:when => :admin,
:denied_url => { :controller => 'pages', :action => 'index' },
:denied_message => 'You must have administrative privileges to perform this action.'
- 1
before_action :ensure_deletable, :only => [:remove, :destroy]
- 1
def show
redirect_to edit_admin_user_path(params[:id])
end
- 1
def update
user_params = params[model_symbol].permit!
if user_params && user_params['admin'] == false && model == current_user
user_params.delete('admin')
annouce_cannot_remove_self_from_admin_role
end
model.update_attributes!(user_params)
response_for :update
end
- 1
def ensure_deletable
if current_user.id.to_s == params[:id].to_s
announce_cannot_delete_self
redirect_to admin_users_path
end
end
- 1
private
- 1
def announce_cannot_delete_self
flash[:error] = t('users_controller.cannot_delete_self')
end
- 1
def annouce_cannot_remove_self_from_admin_role
flash[:error] = 'You cannot remove yourself from the admin role.'
end
end
- 1
class Admin::WelcomeController < ApplicationController
- 1
no_login_required
- 1
before_action :never_cache
- 1
skip_before_action :verify_authenticity_token
- 1
def index
- 21
redirect_to admin_pages_path
end
- 1
def login
- 43
if request.post?
- 20
@username_or_email = params[:username_or_email]
- 20
password = params[:password]
- 20
announce_invalid_user unless self.current_user = User.authenticate(@username_or_email, password)
end
- 43
if current_user
- 18
if params[:remember_me]
current_user.remember_me
set_session_cookie
end
- 18
redirect_to(session[:return_to] || welcome_path)
- 18
session[:return_to] = nil
end
end
- 1
def logout
- 1
request.cookies[:session_token] = { :expires => 1.day.ago.utc }
- 1
self.current_user.forget_me if self.current_user
- 1
self.current_user = nil
- 1
announce_logged_out
- 1
redirect_to login_path
end
- 1
private
- 1
def never_cache
- 65
expires_now
end
- 1
def announce_logged_out
- 1
flash[:notice] = t('welcome_controller.logged_out')
end
- 1
def announce_invalid_user
- 2
flash.now[:error] = t('welcome_controller.invalid_user')
end
end
- 1
require 'trusty_cms/pagination/controller'
- 1
class SiteController < ApplicationController
- 1
include TrustyCms::Pagination::Controller
- 1
skip_before_action :verify_authenticity_token
- 1
no_login_required
- 1
def self.cache_timeout=(val)
TrustyCms::PageResponseCacheDirector.cache_timeout=(val)
end
- 1
def self.cache_timeout
TrustyCms::PageResponseCacheDirector.cache_timeout
end
- 1
def show_page
- 21
url = params[:url]
- 21
if Array === url
url = url.join('/')
else
- 21
url = url.to_s
end
- 21
if @page = find_page(url)
batch_page_status_refresh if (url == "/" || url == "")
# This is a bit of a hack to get Vanity URL pages working in another extension
# In Rails 2, redirect_to halted execution, so process_page could be aliased and
# a redirect could be used. This no longer works. There's a better fix for this,
# but for now, anything that aliases process_page can return false if it's rendering
# or redirecting on its own.
return unless process_page(@page)
set_cache_control
@performed_render ||= true
render layout: false
else
render :template => 'site/not_found', :status => 404, layout: false
end
rescue Page::MissingRootPageError
- 21
redirect_to welcome_path
end
- 1
def cacheable_request?
(request.head? || request.get?) && live?
end
# hide_action :cacheable_request?
- 1
def set_expiry(time, options={})
expires_in time, options
end
# hide_action :set_expiry
- 1
def set_etag(val)
headers['ETag'] = val
end
# hide_action :set_expiry
- 1
private
- 1
def batch_page_status_refresh
@changed_pages = []
@pages = Page.where({:status_id => Status[:scheduled].id})
@pages.each do |page|
if page.published_at <= Time.now
page.status_id = Status[:published].id
page.save
@changed_pages << page.id
end
end
expires_in nil, :private=>true, "no-cache" => true if @changed_pages.length > 0
end
- 1
def set_cache_control
response_cache_director(@page).set_cache_control
end
- 1
def response_cache_director(page)
klass_name = "TrustyCms::#{page.class}ResponseCacheDirector"
begin
klass = klass_name.constantize
rescue NameError, LoadError
director_klass = "TrustyCms::PageResponseCacheDirector"
#Rubocop: The use of eval is a serious security risk.
#eval(%Q{class #{klass_name} < #{director_klass}; end}, TOPLEVEL_BINDING)
klass = director_klass.constantize
end
klass.new(page, self)
end
- 1
def find_page(url)
- 21
found = Page.find_by_path(url, live?)
found if found and (found.published? or dev?)
end
- 1
def process_page(page)
page.pagination_parameters = pagination_parameters
page.process(request, response)
end
- 1
def dev?
- 21
request.host == @trusty_config['dev.host'] || request.host =~ /^dev\./
end
- 1
def live?
- 21
not dev?
end
end
- 1
module Admin::ConfigurationHelper
# Defines helper methods for use in the admin interface when displaying or editing configuration.
# Renders the setting as label and value:
#
# show_config("admin.title")
# => <label for="admin_title">Admin title<label><span id="admin_title">TrustyCms CMS</span>
#
- 1
def show_config(key, options={})
- 50
setting = setting_for(key)
- 50
setting.valid?
- 50
domkey = key.gsub(/\W/, '_')
- 50
html = ""
- 50
html << content_tag(:label, t("trusty_config.#{key}").titlecase, :for => domkey)
- 50
if setting.boolean?
- 5
value = setting.checked? ? t('yes') : t('no')
- 5
html << content_tag(:span, value, :id => domkey, :class => "#{value} #{options[:class]}")
else
- 45
value = setting.selected_value || setting.value
- 45
html << content_tag(:span, value, :id => domkey, :class => options[:class])
end
- 50
html << content_tag(:span, " #{t("units.#{setting.units}")}", :class => 'units') if setting.units
- 50
html << content_tag(:span, " #{t('warning')}: #{[setting.errors[:value]].flatten.first}", :class => 'warning') if setting.errors.messages[:value].present?
- 50
Rails.logger.error(html)
- 50
html.html_safe
end
# Renders the setting as label and appropriate input field:
#
# edit_setting("admin.title")
# => <label for="admin_title">Admin title<label><input type="text" name="config['admin.title']" id="admin_title" value="TrustyCms CMS" />
#
# edit_config("defaults.page.status")
# =>
# <label for="defaults_page_status">Default page status<label>
# <select type="text" name="config['defaults.page.status']" id="defaults_page_status">
# <option value="Draft">Draft</option>
# ...
# </select>
#
# edit_setting("user.allow_password_reset?")
# => <label for="user_allow_password_reset_">Admin title<label><input type="checkbox" name="config['user.allow_password_reset?']" id="user_allow_password_reset_" value="1" checked="checked" />
#
- 1
def edit_config(key, options={})
- 10
setting = setting_for(key)
- 10
domkey = key.gsub(/\W/, '_')
- 10
name = "trusty_config[#{key}]"
- 10
title = t("trusty_config.#{key}").titlecase
- 10
title << content_tag(:span, " (#{t("units.#{setting.units}")})", :class => 'units') if setting.units
- 10
value = params[key.to_sym].nil? ? setting.value : params[key.to_sym]
- 10
html = ""
- 10
if setting.boolean?
- 1
html << hidden_field_tag(name, 0)
- 1
html << check_box_tag(name, 1, value, :class => 'setting', :id => domkey)
- 1
html << content_tag(:label, title.html_safe, :class => 'checkbox', :for => domkey)
- 9
elsif setting.selector?
- 4
html << content_tag(:label, title.html_safe, :for => domkey)
- 4
html << select_tag(name, options_for_select(setting.definition.selection, value), :class => 'setting', :id => domkey)
else
- 5
html << content_tag(:label, title.html_safe, :for => domkey)
- 5
html << text_field_tag(name, value, :class => 'textbox', :id => domkey)
end
- 10
if setting.errors[:value].present?
html << content_tag(:span, [setting.errors[:value]].flatten.first, :class => 'error')
html = content_tag(:span, html.html_safe, :class => "error-with-field")
end
- 10
html.html_safe
end
- 1
def setting_for(key)
- 60
@trusty_config ||= {} # normally initialized in Admin::ConfigurationController
- 60
@trusty_config[key] ||= TrustyCms.config.find_or_initialize_by(key: key)
end
- 1
def definition_for(key)
if setting = setting_for(key)
setting.definition
end
end
end
- 1
module Admin::ExtensionsHelper
end
- 1
module Admin::NodeHelper
- 1
def render_nodes(page, starting_index, parent_index = nil, simple = false)
- 4
@rendered_html = ""
- 4
render_node page, starting_index, parent_index, simple
- 4
@rendered_html
end
- 1
def render_node(page, index, parent_index = nil, simple = false)
- 4
@current_node = prepare_page(page)
- 4
@rendered_html += (render :partial => 'admin/pages/node',
:locals => {level: index, index: index, parent_index: parent_index,
- 4
page: page, simple: simple, branch: (page.children.count > 0) })
- 4
index
end
- 1
def prepare_page(page)
- 4
page.extend MenuRenderer
- 4
page.view = self
- 4
if page.additional_menu_features?
page.extend(*page.menu_renderer_modules)
end
- 4
page
end
- 1
def homepage
@homepage ||= Page.find_by_parent_id(nil)
end
- 1
def show_all?
controller.action_name == 'remove'
end
- 1
def expanded_rows
unless @expanded_rows
@expanded_rows = case
when rows = cookies[:expanded_rows]
rows.split(',').map { |x| Integer(x) rescue nil }.compact
else
[]
end
if homepage and !@expanded_rows.include?(homepage.id)
@expanded_rows << homepage.id
end
end
@expanded_rows
end
- 1
def expanded
show_all? || expanded_rows.include?(@current_node.id)
end
- 1
def expander(level)
unless @current_node.children.empty? or level == 0
image((expanded ? "collapse" : "expand"),
:class => "expander", :alt => 'toggle children',
:title => '')
else
""
end
end
- 1
def icon
- 4
icon_name = @current_node.virtual? ? 'virtual_page' : 'page'
- 4
image(icon_name, :class => "icon", :alt => '', :title => '')
end
- 1
def node_title
- 4
%{<span class="title">#{ h(@current_node.title) }</span>}.html_safe
end
- 1
def page_type
- 3
display_name = @current_node.class.display_name
- 3
if display_name == 'Page'
- 3
""
else
%{<span class="info">(#{ h(display_name) })</span>}.html_safe
end
end
- 1
def spinner
- 3
image('spinner.gif',
:class => 'busy', :id => "busy_#{@current_node.id}",
:alt => "", :title => "",
:style => 'display: none;')
end
end
- 1
module Admin::PagesHelper
- 1
include Admin::NodeHelper
- 1
include Admin::ReferencesHelper
- 1
def class_of_page
@page.class
end
- 1
def filter
@page.parts.first.filter if @page.parts.respond_to?(:any?) && @page.parts.any?
end
- 1
def meta_errors?
- 6
!!(@page.errors[:slug] or @page.errors[:breadcrumb])
end
- 1
def status_to_display
- 3
@page.status_id = 100 if @page.status_id == 90
- 15
@display_status = Status.selectable.map{ |s| [I18n.translate(s.name.downcase), s.id] }
end
- 1
def clean_page_description(page)
page.description.to_s.strip.gsub(/\t/,'').gsub(/\s+/,' ')
end
end
- 1
module Admin::PreferencesHelper
end
- 1
require "RedCloth"
- 1
module Admin::ReferencesHelper
- 1
def tag_reference
String.new.tap do |output|
class_of_page.tag_descriptions.sort.each do |tag_name, description|
value = t("desc.#{tag_name.gsub(':','-')}").match('desc') ? description : t("desc.#{tag_name.gsub(':','-')}")
output << render(:partial => "admin/references/tag_reference.haml",
:locals => {:tag_name => tag_name,
:description => RedCloth.new(TrustyCms::Taggable::Util.strip_leading_whitespace(value)).to_html
})
end
end
end
- 1
def filter_reference
unless filter.blank?
if filter.description.blank?
"There is no documentation on this filter."
else
filter.description
end
else
"There is no filter on the current page part."
end
end
- 1
def _display_name
case params[:type]
when 'filters'
filter ? filter.filter_name : t('select.none')
when 'tags'
class_of_page.display_name
end
end
- 1
def filter
@filter ||= begin
TextFilter.find_descendant(params[:filter_name])
end
end
- 1
def class_of_page
@page_class ||= (params[:class_name].blank? ? 'Page' : params[:class_name]).constantize
end
end
- 1
module Admin::UsersHelper
- 1
def roles(user)
roles = []
roles << I18n.t('admin') if user.admin?
roles << I18n.t('designer') if user.designer?
roles.join(', ')
end
end
- 1
module Admin::WelcomeHelper
end
- 1
module SiteHelper
end
- 1
class Layout < ActiveRecord::Base
# Default Order
- 26
default_scope {order("name")}
# Associations
- 1
has_many :pages
- 1
belongs_to :created_by, :class_name => 'User'
- 1
belongs_to :updated_by, :class_name => 'User'
# Validations
- 1
validates_presence_of :name
- 1
validates_uniqueness_of :name
- 1
validates_length_of :name, :maximum => 100
end
- 1
module MenuRenderer
- 1
def exclude(*type_names)
@excluded_class_names ||= []
@excluded_class_names.concat(type_names).uniq!
end
- 1
module_function :exclude
- 1
def excluded_class_names
- 9
MenuRenderer.instance_variable_get(:@excluded_class_names)
end
- 1
module_function :excluded_class_names
- 1
public :excluded_class_names
- 1
def view=(val)
- 4
@view = val
end
- 1
def view
- 48
@view
end
- 1
def additional_menu_features?
- 4
@additional_menu_features ||= (menu_renderer_module_name != 'MenuRenderer' && Object.const_defined?(menu_renderer_module_name))
end
- 1
def menu_renderer_module_name
- 4
simple_name = self.class_name.to_s.sub('Page','')
- 4
"#{simple_name}MenuRenderer"
end
- 1
def menu_renderer_modules
[Object.const_get(menu_renderer_module_name)]
end
- 1
def allowed_child_classes
- 9
(allowed_children_cache.to_s.split(',') - Array(excluded_class_names)).map do |name|
- 27
begin
- 27
name.constantize
rescue LoadError, NameError => _
nil
end
- 9
end.compact
end
- 1
def default_child_item
- 3
menu_item(default_child)
end
- 1
def separator_item
- 3
view.content_tag :li, '', :class => 'separator'
end
- 1
def child_items
- 3
(allowed_child_classes - [self.class.default_child]).map do |child|
- 6
menu_item(child)
end
end
- 1
def menu_items
- 3
[default_child_item, separator_item] + child_items
end
- 1
def menu_list
- 3
view.content_tag :ul, menu_items.join.html_safe, :class => 'menu', :id => "allowed_children_#{id}"
end
- 1
def remove_link
- 3
view.link_to view.image('minus') + ' ' + I18n.t('remove'), view.remove_admin_page_url(self), :class => "action"
end
- 1
def remove_option
- 3
remove_link
end
- 1
def add_child_disabled?
- 3
allowed_child_classes.size == 0
end
- 1
def disabled_add_child_link
view.content_tag :span, view.image('plus_disabled') + ' Add Child', :class => 'action disabled'
end
- 1
def add_child_link
view.link_to((view.image('plus') + ' Add Child'), view.new_admin_page_child_path(self, :page_class => default_child.name), :class => "action")
end
- 1
def add_child_link_with_menu_hook
- 3
view.link_to((view.image('plus') + ' Add Child'), "#allowed_children_#{id}", :class => "action dropdown")
end
- 1
def add_child_menu
- 3
menu_list
end
- 1
def add_child_link_with_menu
- 3
add_child_link_with_menu_hook + add_child_menu
end
- 1
def add_child_option
- 3
if add_child_disabled?
disabled_add_child_link
else
- 3
if allowed_child_classes.size == 1
add_child_link
else
- 3
add_child_link_with_menu
end
end
end
- 1
private
- 1
def clean_page_description(page_class)
- 9
page_class.description.to_s.strip.gsub(/\t/,'').gsub(/\s+/,' ')
end
- 1
def menu_item(child_class)
- 9
view.content_tag(:li, menu_link(child_class))
end
- 1
def menu_link(child_class)
- 9
title = clean_page_description(child_class)
- 9
path = view.new_admin_page_child_path(self, :page_class => child_class.name)
- 9
text = link_text_for_child_class(child_class.name)
- 9
view.link_to(text, path, :title => title)
end
- 1
def link_text_for_child_class(given_class_name)
- 9
translation_key = if given_class_name == 'Page' || given_class_name.blank?
- 3
'normal_page'
else
- 6
given_class_name.sub('Page','').underscore
end
- 9
fallback = given_class_name == 'Page' ? 'Page' : given_class_name.sub('Page','').titleize
- 9
I18n.t(translation_key, :default => fallback)
end
end
- 1
class PageField < ActiveRecord::Base
- 1
validates_presence_of :name
end
- 1
class PagePart < ActiveRecord::Base
# Default Order
- 17
default_scope {order("name")}
# Associations
- 1
belongs_to :page
# Validations
- 1
validates_presence_of :name
- 1
validates_length_of :name, :maximum => 100
- 1
validates_length_of :filter_id, :maximum => 25, :allow_nil => true
- 1
object_id_attr :filter, TextFilter
- 1
def after_initialize
self.filter_id ||= TrustyCms::Config['defaults.page.filter'] if new_record?
end
end
- 1
class Status
- 1
attr_accessor :id, :name
- 1
def initialize(options = {})
- 5
options = options.symbolize_keys
- 5
@id, @name = options[:id], options[:name]
end
- 1
def symbol
- 61
@name.to_s.downcase.intern
end
- 1
def self.[](value)
- 80
@@statuses.find { |status| status.symbol == value.to_s.downcase.intern }
end
- 1
def self.find(id)
- 24
@@statuses.find { |status| status.id.to_s == id.to_s }
end
- 1
def self.find_all
- 9
@@statuses.dup
end
- 1
def self.selectable
- 9
find_all - [self['Scheduled']]
end
- 1
def self.selectable_values
- 6
self.selectable.map(&:name)
end
- 1
@@statuses = [
Status.new(:id => 1, :name => 'Draft' ),
Status.new(:id => 50, :name => 'Reviewed' ),
Status.new(:id => 90, :name => 'Scheduled'),
Status.new(:id => 100, :name => 'Published'),
Status.new(:id => 101, :name => 'Hidden' )
]
end
- 1
class TextFilter
- 1
include Simpleton
- 1
include Annotatable
- 1
annotate :filter_name, :description
- 1
def filter(text)
text
end
- 1
class << self
- 1
def inherited(subclass)
subclass.filter_name = subclass.name.to_name('Filter')
end
- 1
def filter(text)
instance.filter(text)
end
- 1
def descendants_names
descendants.map { |s| s.filter_name }.sort
end
- 1
def find_descendant(filter_name)
descendants.each do |s|
return s if s.filter_name == filter_name
end
nil
end
end
end
- 1
require 'digest/sha1'
- 1
class User < ActiveRecord::Base
- 1
has_many :pages, :foreign_key => :created_by_id
# Default Order
- 25
default_scope {order("name")}
# Associations
- 1
belongs_to :created_by, :class_name => 'User'
- 1
belongs_to :updated_by, :class_name => 'User'
# Validations
- 1
validates_uniqueness_of :login
- 1
validates_confirmation_of :password, :if => :confirm_password?
- 1
validates_presence_of :name, :login
- 1
validates_presence_of :password, :password_confirmation, :if => :new_record?
- 1
validates_length_of :name, :maximum => 100, :allow_nil => true
- 1
validates_length_of :login, :within => 3..40, :allow_nil => true
- 1
validates_length_of :password, :within => 5..40, :allow_nil => true, :if => :validate_length_of_password?
- 1
validates_length_of :email, :maximum => 255, :allow_nil => true
- 1
attr_writer :confirm_password
- 1
def has_role?(role)
- 130
respond_to?("#{role}?") && send("#{role}?")
end
- 1
def sha1(phrase)
- 19
Digest::SHA1.hexdigest("--#{salt}--#{phrase}--")
end
- 1
def self.authenticate(login_or_email, password)
- 20
user = where(["login = ? OR email = ?", login_or_email, login_or_email]).first
- 20
user if user && user.authenticated?(password)
end
- 1
def authenticated?(password)
- 19
self.password == sha1(password)
end
- 1
def after_initialize
@confirm_password = true
end
- 1
def confirm_password?
- 3
@confirm_password
end
- 1
def remember_me
update_attribute(:session_token, sha1(Time.now + TrustyCms::Config['session_timeout'].to_i)) unless self.session_token?
end
- 1
def forget_me
- 1
update_attribute(:session_token, nil)
end
- 1
def send_password_reset
generate_token(:password_reset_token)
update_attribute(:password_reset_sent_at, Time.zone.now)
PasswordMailer.password_reset(self).deliver_now
end
- 1
private
- 1
def generate_token(column)
self[column] = SecureRandom.urlsafe_base64 if User.exists?(column => self[column])
end
- 1
def validate_length_of_password?
- 3
new_record? or not password.to_s.empty?
end
- 1
before_create :encrypt_password
- 1
def encrypt_password
self.salt = Digest::SHA1.hexdigest("--#{Time.now}--#{login}--sweet harmonious biscuits--")
self.password = sha1(password)
end
- 1
before_update :encrypt_password_unless_empty_or_unchanged
- 1
def encrypt_password_unless_empty_or_unchanged
- 2
user = self.class.find(self.id)
- 2
case password
when ''
- 1
self.password = user.password
when user.password
else
encrypt_password
end
end
end
- 1
class UserActionObserver < ActiveRecord::Observer
- 1
observe User, Page, Layout
- 1
def current_user=(user)
- 136
self.class.current_user = user
end
- 1
def self.current_user=(user)
- 136
Thread.current[:current_user] = user
end
- 1
def current_user
- 9
self.class.current_user
end
- 1
def self.current_user
- 9
Thread.current[:current_user]
end
- 1
def before_create(model)
- 7
model.created_by = self.current_user
end
- 1
def before_update(model)
- 2
model.updated_by = self.current_user
end
end
- 1
class TrustyCms::AdminUI::RegionPartials
- 1
def initialize(template)
- 244
@partials = Hash.new {|h,k| h[k] = "<strong>`#{k}' default partial not found!</strong>" }
- 244
@template = template
end
- 1
def [](key)
- 194
@partials[key.to_s]
end
- 1
def method_missing(method, *args, &block)
- 195
if block_given?
# Ruby 1.9.2 yields self in instance_eval... see https://gist.github.com/479572
# lambdas are as strict as methods in 1.9.x, making sure that the args match, Procs are not.
- 195
if RUBY_VERSION =~ /^1\.9/ and block.lambda? and block.arity != 1
raise "You can only pass a proc ('Proc.new') or a lambda that takes exactly one arg (for self) to TrustyCms::AdminUI::RegionPartials' method_missing."
end
- 195
@partials[method.to_s] = @template.capture(&block)
else
@partials[method.to_s]
end
end
end
- 1
module TrustyCms::AvailableLocales
# Returns the list of available locale files in options_for_select format.
#
- 1
def self.locales
- 7
available_locales = {}
- 7
TrustyCms.configuration.i18n.load_path.each do |path|
- 196
if File.exists?(path) && path !~ /_available_tags/
- 182
locale_yaml = YAML.load_file(path)
- 182
stem = File.basename(path, '.yml')
- 182
if locale_yaml[stem] && lang = locale_yaml[stem]["this_file_language"]
- 14
available_locales[lang] = stem
end
end
end
- 21
available_locales.collect {|k,v| [k, v]}.sort_by { |s| s[0] }
end
end
- 1
module TrustyCms
- 1
module Pagination
- 1
module Controller
# for inclusion into public-facing controllers
- 1
def configure_pagination
# unconfigured parameters remain at will_paginate defaults
# will_paginate controller options are not overridden by tag attribetus
- 21
WillPaginate::ViewHelpers.pagination_options[:param_name] = TrustyCms::Config["pagination.param_name"].to_sym unless TrustyCms::Config["pagination.param_name"].blank?
- 21
WillPaginate::ViewHelpers.pagination_options[:per_page_param_name] = TrustyCms::Config["pagination.per_page_param_name"].blank? ? :per_page : TrustyCms::Config["pagination.per_page_param_name"].to_sym
# will_paginate view options can be overridden by tag attributes
- 21
[:class, :previous_label, :next_label, :inner_window, :outer_window, :separator, :container].each do |opt|
- 147
WillPaginate::ViewHelpers.pagination_options[opt] = TrustyCms::Config["pagination.#{opt}"] unless TrustyCms::Config["pagination.#{opt}"].blank?
end
end
- 1
def pagination_parameters
{
:page => params[WillPaginate::ViewHelpers.pagination_options[:param_name]] || 1,
:per_page => params[WillPaginate::ViewHelpers.pagination_options[:per_page_param_name]] || TrustyCms::Config['pagination.per_page'] || 20
}
end
- 1
def self.included(base)
- 1
base.class_eval {
- 1
helper_method :pagination_parameters
- 1
before_action :configure_pagination
}
end
end
end
end
- 1
require 'spec_helper'
- 1
describe ApplicationController, :type => :controller do
- 13
routes { TrustyCms::Engine.routes }
- 1
it 'should initialize the javascript and stylesheets arrays' do
- 1
controller.send :set_javascripts_and_stylesheets
- 1
expect(controller.send(:instance_variable_get, :@javascripts)).not_to be_nil
- 1
expect(controller.send(:instance_variable_get, :@javascripts)).to be_instance_of(Array)
- 1
expect(controller.send(:instance_variable_get, :@stylesheets)).not_to be_nil
- 1
expect(controller.send(:instance_variable_get, :@stylesheets)).to be_instance_of(Array)
end
- 1
describe 'self.template_name' do
- 1
it "should return 'index' when the controller action_name is 'index'" do
- 1
allow(controller).to receive(:action_name).and_return('index')
- 1
expect(controller.template_name).to eq('index')
end
- 1
['new', 'create'].each do |action|
- 2
it "should return 'new' when the action_name is #{action}" do
- 2
allow(controller).to receive(:action_name).and_return(action)
- 2
expect(controller.template_name).to eq('new')
end
end
- 1
['edit', 'update'].each do |action|
- 2
it "should return 'edit' when the action_name is #{action}" do
- 2
allow(controller).to receive(:action_name).and_return(action)
- 2
expect(controller.template_name).to eq('edit')
end
end
- 1
['remove', 'destroy'].each do |action|
- 2
it "should return 'remove' when the action_name is #{action}" do
- 2
allow(controller).to receive(:action_name).and_return(action)
- 2
expect(controller.template_name).to eq('remove')
end
end
- 1
it "should return 'show' when the action_name is show" do
- 1
allow(controller).to receive(:action_name).and_return('show')
- 1
expect(controller.template_name).to eq('show')
end
- 1
it "should return the action_name when the action_name is a non-standard name" do
- 1
allow(controller).to receive(:action_name).and_return('other')
- 1
expect(controller.template_name).to eq('other')
end
end
- 1
describe "set_timezone" do
- 1
it "should use TrustyCms::Config['local.timezone']" do
- 1
TrustyCms::Config['local.timezone'] = 'UTC'
- 1
controller.send(:set_timezone)
- 1
expect(Time.zone.name).to eq('UTC')
end
- 1
it "should default to config.time_zone" do
- 1
TrustyCms::Config.initialize_cache # to clear out setting from previous tests
- 1
controller.send(:set_timezone)
- 1
expect(Time.zone.name).to eq('UTC')
end
end
end
- 1
require 'spec_helper'
- 1
describe Admin::UsersController, :type => :controller do
- 1
routes { TrustyCms::Engine.routes }
end
- 1
require 'spec_helper'
- 1
RSpec.describe Admin::WelcomeController, :type => :controller do
- 1
routes { TrustyCms::Engine.routes }
end
- 1
FactoryBot.define do
- 1
factory :layout do
- 1
name 'Main Layout'
- 1
content <<-CONTENT
<html>
<head>
<title><r:title /></title>
</head>
<body>
<r:content />
</body>
</html>
CONTENT
end
end
- 1
FactoryBot.define do
- 1
factory :page do
- 1
title 'Page'
- 1
breadcrumb { title }
- 1
slug { title.slugify }
- 1
trait :with_parts do
- 1
page_parts { [FactoryBot.create(:page_part, name: 'body')] }
end
- 1
trait :with_children do
- 1
children { [FactoryBot.create(:page, :with_parts)] }
end
- 1
factory :page_with_layout do
- 1
layout
end
- 1
factory :page_with_page_parts do
- 1
page_parts
end
- 1
factory :file_not_found_page, class: FileNotFoundPage do
end
- 1
factory :parent do
end
- 1
factory :published_page do
- 1
status_id Status[:published].id
- 1
factory :article do
- 1
title { generate(:article_title)}
- 1
slug { generate(:article_slug)}
end
- 1
factory :page_with_body_page_part do
- 1
after(:create) { |page| page.parts.create(name: 'body', content: "#{page.title} body.") }
end
- 1
factory :page_with_body_and_sidebar_parts do
- 1
after(:create) { |page| page.parts.create(name: 'body', content: "#{page.title} body.") }
- 1
after(:create) { |page| page.parts.create(name: 'sidebar', content: "#{page.title} sidebar.") }
end
end
- 1
factory :home do |home|
- 1
title 'Home'
- 1
slug '/'
- 1
status_id Status[:published].id
- 1
parent_id nil
end
end
- 1
sequence :article_slug do |n|
"article#{('-' + n.to_s) unless n == 1 }"
end
- 1
sequence :article_title do |n|
"Article#{(' ' + n.to_s) unless n == 1 }"
end
end
- 1
FactoryBot.define do
- 1
factory :page_part do
- 1
name 'unnamed'
- 1
content { name }
end
end
- 1
FactoryBot.define do
- 1
factory :user do
- 1
name 'User'
- 1
email 'email@test.com'
- 1
login 'user'
- 1
password 'password'
- 1
password_confirmation { password }
- 1
factory :admin do
- 1
name 'Admin'
- 1
login 'admin'
- 1
email 'admin@example.com'
- 1
admin true
end
- 1
factory :existing do
- 1
name 'Existing'
- 1
login 'existing'
- 1
email 'existing@example.com'
end
- 1
factory :designer do
- 1
name 'Designer'
- 1
login 'designer'
- 1
email ''
- 1
designer true
end
- 1
factory :non_admin do
- 1
name 'Non Admin'
- 1
login 'non_admin'
- 1
admin false
end
end
end
- 1
require 'rails_helper'
- 1
describe 'Administration Interface Login' do
- 1
fixtures :users
- 1
it 'shows a login page' do
- 1
visit '/'
- 1
expect(page).to have_field 'Username or E-mail Address'
- 1
expect(page).to have_field 'Password'
- 1
expect(page).to have_button 'Login'
end
- 1
it 'shows an error if the username is wrong' do
- 1
log_in_as 'nonexistent_username'
- 1
expect(find('#error')).to have_content "Invalid username, e-mail address, or password."
end
- 1
describe 'as an admin user' do
- 1
before(:each) do
- 7
@admin = users(:captain_janeway)
end
- 1
context 'after login' do
- 1
before(:each) do
- 6
log_in_as @admin.login
end
- 1
it 'shows the admin interface' do
- 1
expect(page).to have_content "Logged in as"
end
- 1
it 'has correct links in header' do
- 1
expect(page).to have_link @admin.name, href: '/admin/preferences/edit'
- 1
expect(page).to have_link 'Logout', href: '/admin/logout'
- 1
expect(page).to have_link 'View Site', href: '/'
end
- 1
it 'has correct links in navigation' do
- 1
within '#navigation' do
- 1
expect(page).to have_link "Content", href: '/admin/pages'
- 1
expect(page).to have_link "Design", href: '/admin/layouts'
- 1
expect(page).to have_link "Settings", href: '/admin/configuration'
end
end
- 1
it 'outputs table header as html' do
- 1
expect(page).to have_selector "table#pages th.name"
end
- 1
it 'can navigate to create new page' do
- 1
visit '/admin/pages/new'
- 1
expect(page).to have_selector "h1", text: "New Page"
end
- 1
it 'can log out' do
- 1
click_link "Logout"
- 1
expect(page).to have_content "You are now logged out."
- 1
visit '/admin/pages/new'
- 1
expect(page).to have_content "Please Login"
end
end
- 1
it 'shows an error if the password is wrong' do
- 1
log_in_as @admin.login, 'passwordwhoops'
- 1
expect(find('#error')).to have_content "Invalid username, e-mail address, or password."
end
end
- 1
describe 'as a regular user after login' do
- 1
before(:each) do
- 2
@user = users(:neelix)
- 2
log_in_as @user.login
end
- 1
it 'can log in to the admin interface' do
- 1
expect(page).to have_content "Logged in as"
end
- 1
it 'has correct links in navigation' do
- 1
within '#navigation' do
- 1
expect(page).to have_link "Content", href: '/admin/pages'
- 1
expect(page).not_to have_link "Design"
- 1
expect(page).to have_link "Settings", href: '/admin/configuration'
end
end
end
end
- 1
require 'rails_helper'
- 1
describe 'Configuration (Settings)' do
- 1
fixtures :users
- 1
before(:each) do
- 3
@admin = users(:captain_janeway)
- 3
log_in_as @admin.login
- 3
click_link 'Settings'
end
- 1
it 'has personal and site preferences' do
- 1
expect(page).to have_content 'Personal Preferences'
- 1
expect(page).to have_content 'Configuration'
end
- 1
it 'lets you edit your personal preferences' do
- 1
click_button 'Edit Preferences'
- 1
fill_in 'Name', with: 'Captain Kathryn Janeway'
- 1
click_button 'Save Changes'
- 1
expect(page).to have_content 'Name Captain Kathryn Janeway'
end
- 1
it 'lets you edit the site preferences' do
- 1
click_button 'Edit Configuration'
- 1
fill_in 'Site Title', with: 'My Special Site'
- 1
click_button 'Save Changes'
- 1
within '#site_title' do
- 1
expect(page).to have_content 'My Special Site'
end
end
end
- 1
require 'rails_helper'
- 1
describe 'Layouts (Design)' do
- 1
fixtures :users
- 1
before(:each) do
- 4
@admin = users(:captain_janeway)
- 4
log_in_as @admin.login
- 4
click_link 'Design'
end
- 1
context 'without any layouts' do
- 1
it 'says it has no layouts' do
- 1
expect(page).to have_content 'No Layouts'
end
- 1
it 'lets you add a layout' do
- 1
click_link 'New Layout'
- 1
fill_in 'Name', with: 'Petunias'
- 1
fill_in 'Body', with: 'Wisteria'
- 1
click_button 'Create Layout'
- 1
expect(page).to have_content 'Petunias'
end
end
- 1
context 'with a layout' do
- 1
before(:each) do
- 2
Layout.create!(name: 'Petunias', content: 'Wisteria')
- 2
visit '/admin/layouts'
end
- 1
it 'lets you edit the layout' do
- 1
click_link 'Petunias'
- 1
expect(page).to have_content 'Edit Layout'
- 1
expect(page).to have_field 'Name', with: 'Petunias'
- 1
expect(page).to have_field 'Body', with: 'Wisteria'
- 1
expect(page).to have_button 'Save Changes'
- 1
expect(page).to have_content 'Last Updated by Kathryn Janeway'
end
- 1
it 'lets you remove the layout' do
- 1
click_link 'Remove'
- 1
expect(page).to have_content 'Are you sure you want to permanently remove the following layout?'
- 1
click_button 'Delete Layout'
- 1
expect(page).to have_content 'No Layouts'
- 1
expect(page).to have_link 'New Layout'
end
end
end
- 1
require 'rails_helper'
- 1
describe 'Pages' do
- 1
fixtures :users
- 1
before(:each) do
- 3
@admin = users(:captain_janeway)
- 3
log_in_as @admin.login
end
- 1
context 'without any pages' do
- 1
it 'can create a new homepage' do
- 1
click_link 'New Homepage'
- 1
fill_in 'Page Title', with: 'Voyager Home'
- 1
fill_in 'Breadcrumb', with: 'Home'
- 1
click_button 'Create Page'
- 1
within 'table#pages' do
- 1
expect(page).to have_selector 'tbody tr', count: 1
- 1
expect(page).to have_link 'Voyager Home'
- 1
expect(page).to have_link 'Add Child'
- 1
expect(page).to have_link 'Normal Page'
- 1
expect(page).to have_link 'File Not Found'
- 1
expect(page).to have_link 'Remove'
end
end
end
- 1
context 'with only a homepage' do
- 1
before(:each) do
- 2
Page.create!(title: 'Voyager Home', breadcrumb: 'Home', slug: '/')
- 2
visit '/admin/pages'
end
- 1
it 'lets you edit the homepage' do
- 1
click_link 'Voyager Home'
- 1
expect(page).to have_field 'Page Title', with: 'Voyager Home'
- 1
expect(page).to have_button 'Save Changes'
- 1
expect(page).to have_content 'Last Updated by Kathryn Janeway'
end
- 1
it 'lets you remove the homepage' do
- 1
click_link 'Remove'
- 1
expect(page).to have_content 'Are you sure you want to permanently remove the following Page?'
- 1
click_button 'Delete Page'
- 1
expect(page).to have_content 'No Pages'
- 1
expect(page).to have_link 'New Homepage'
end
end
end
- 1
require 'spec_helper'
- 1
describe Layout do
- 1
let(:layout){ FactoryBot.build(:layout) }
- 1
describe 'name' do
- 1
it 'is invalid when blank' do
- 1
layout = FactoryBot.build(:layout, name: '')
- 1
layout.valid?
- 1
expect(layout.errors[:name]).to include("this must not be blank")
end
- 1
it 'should validate uniqueness of' do
- 1
layout = FactoryBot.build(:layout, name: 'Normal', content: "Content!")
- 1
layout.save!
- 1
other = FactoryBot.build(:layout, name: 'Normal', content: "Content!")
- 2
expect{other.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
- 1
it 'should validate length of' do
- 1
layout = FactoryBot.build(:layout, name: 'x' * 100)
- 1
expect(layout.errors[:name]).to be_blank
- 1
layout = FactoryBot.build(:layout, name: 'x' * 101)
- 2
expect{layout.save!}.to raise_error(ActiveRecord::RecordInvalid)
- 1
expect(layout.errors[:name]).to include("this must not be longer than 100 characters")
end
end
end
# This file is copied to spec/ when you run 'rails generate rspec:install'
- 1
ENV["RAILS_ENV"] ||= 'test'
- 1
require 'spec_helper'
- 1
require 'rspec/rails'
- 1
require 'capybara/rails'
- 1
require 'capybara/poltergeist'
- 1
Capybara.javascript_driver = :poltergeist
- 1
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, timeout: 60)
end
- 1
require 'database_cleaner'
- 1
DatabaseCleaner.strategy = :truncation, {except: %w[config]}
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
- 1
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
- 1
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
- 1
config.fixture_path = "#{::TRUSTY_CMS_ROOT}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
- 1
config.use_transactional_fixtures = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
- 1
config.infer_spec_type_from_file_location!
- 1
config.before(:suite) do
- 1
TrustyCms::Config.initialize_cache
- 1
configs = [
['admin.title', 'TrustyCMS'],
['admin.subtitle', 'Publishing for Small Teams'],
['defaults.page.parts', 'body, extended'],
['defaults.page.status', 'Draft'],
['defaults.page.filter', nil],
['defaults.page.fields', 'Keywords, Description'],
['defaults.snippet.filter', nil],
['session_timeout', '1209600'], # 2.weeks.to_s ????
['default_locale', 'en'],
]
- 1
configs.each do |key, value|
- 9
c = TrustyCms::Config.find_or_initialize_by(key: key)
- 9
c.value = value
- 9
c.save
end
end
- 1
config.after(:each) do
- 39
DatabaseCleaner.clean
end
end
- 1
require "rails_helper"
- 1
RSpec.describe "routes for Welcome", :type => :routing do
- 1
it "routes /admin/welcome to the admin/welcome controller" do
- 1
expect(get("/admin/welcome")).
to route_to("admin/welcome#index")
end
- 1
it "routes /admin/login to the admin/welcome controller" do
- 1
expect(get("/admin/login")).
to route_to("admin/welcome#login")
end
- 1
it "routes /admin/logout to the admin/welcome controller" do
- 1
expect(get("/admin/logout")).
to route_to("admin/welcome#logout")
end
end
# Commonly occurring user actions in tests.
# This takes a username and by default assumes the password is 'password'.
- 1
def log_in_as(login, plaintext_password = 'password')
- 20
visit '/'
- 20
fill_in 'username_or_email', with: login
- 20
fill_in 'password', with: plaintext_password
- 20
click_on 'Login'
end