This repository has been archived by the owner on Nov 17, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
auto_admin_controller.rb
292 lines (264 loc) · 10.8 KB
/
auto_admin_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
class AutoAdminController < AutoAdmin::AutoAdminConfiguration.controller_super_class
include AutoAdminHelper
include AutoAdminSaveAs
self.view_paths = AutoAdmin::AutoAdminConfiguration.view_directory
def template_layout
'layout.html.erb'
end
# Just the action name, thanks; we use our custom template_root to
# handle the rest.
def default_template_name(action_name = self.action_name)
super.split('/').last
end
layout :template_layout
# TODO: Write out a form containing the entire contents of params
# (except the bits that go in the URL), with a message of "Please
# click 'OK' to save your changes to 'Foo'", determined via a case
# statement over the requested action
verify :method => :post, :only => %w( save delete )
#, :redirect_to => { :action => 'confirm_post' }
helper AutoAdmin::AutoAdminConfiguration.helpers
AutoAdmin::AutoAdminConfiguration.controller_includes.each do |inc|
include inc
end
before_filter :require_valid_user, :except => [ :login, :asset ]
# Used as a before filter to check if we have a valid user (i.e., an admin
# or something like that)
def require_valid_user
return unless has_user?
valid_user = false
if user
if permit_user_to_access_admin( user )
valid_user = true
else
flash[:warning] = 'Not permitted to access administration interface'
end
end
redirect_to :action => 'login', :model => nil unless valid_user
end
# A valid user must pass these checks.
def permit_user_to_access_admin user
user &&
(!user.respond_to?( :active? ) || user.active?) &&
(!user.respond_to?( :enabled? ) || user.enabled?) &&
(!user.respond_to?( :disabled? ) || !user.disabled?) &&
(!user.respond_to?( :admin? ) || user.admin?)
end
private :permit_user_to_access_admin
def user_history_includes
AutoAdmin::AutoAdminConfiguration.admin_model.to_s.downcase.to_sym
end
def user_history_identity
{ AutoAdmin::AutoAdminConfiguration.admin_model_id => (user && user.id) }
end
def user_history_items(num=10)
conditions = []
condition_values = []
user_history_identity.each {|k,v| conditions << "#{k} = ?"; condition_values << v }
AdminHistory.find( :all,
:conditions => [conditions.join(' AND '), *condition_values],
:order => 'created_at DESC', :limit => num )
end
private :user_history_items
def index
@no_crumbs = true
@history_items = user_history_items if has_history?
end
def login
if request.post?
auth_method = [ :authenticate, :login ].detect {|m| AutoAdmin::AutoAdminConfiguration.admin_model.respond_to? m }
if session[AutoAdmin::AutoAdminConfiguration.admin_model_id] = AutoAdmin::AutoAdminConfiguration.admin_model.send( auth_method || :find_by_username_and_password, params[:username], params[:password] )
redirect_to :action => 'index'
end
flash.now[:warning] = "Invalid username or password"
end
@no_crumbs = true
end
def logout
session[AutoAdmin::AutoAdminConfiguration.admin_model_id] = nil
redirect_to :action => 'index'
end
class AssociationCollector
attr_reader :model, :associations
def initialize(model)
@model, @associations = model, []
end
def method_missing method, field=nil, options={}
associations << field if field && model.reflect_on_association( field )
end
end
def collect_associations_for_model
collector = AssociationCollector.new(model)
model.list_columns.build collector
collector.associations
end
private :collect_associations_for_model
def list
params[:filter] ||= {}
params[:filter] = model.filter_defaults.merge(params[:filter])
conditions = model.filter_conditions( params[:filter] )
unless sort_column = model.find_column( params[:sort] )
sort_column = model.find_column( params[:sort] = model.sort_column )
params[:sort_reverse] = model.sort_reverse
end
params[:sort_reverse] ||= false
order = sort_column && "#{model.table_name}.#{sort_column.name} #{params[:sort_reverse] ? 'DESC' : 'ASC'}"
options = { :conditions => conditions, :order => order }
options[:include] = collect_associations_for_model
if params[:search] && model.searchable?
model.append_search_condition! params[:search], options
end
respond_to do |format|
format.html do
options.update(:page => params[:page], :per_page => (params[:per_page] || model.paginate_every).to_i)
@objects = model.paginate(options)
session[:admin_list_params] ||= {}
session[:admin_list_params][params[:model]] = params
end
save_as_blocks self, format, options
end
end
def save
model.transaction do
@object = params[:id] ? model.find( params[:id] ) : model.new
# Use the active theme's FormProcessor to perform any required
# translations within the parameter hash
processor = AutoAdmin::AutoAdminConfiguration.form_processor.new( @object, params[:model], model, self, params[params[:model]] )
model.active_admin_fieldsets.each do |set|
set.build processor
end
# Save attributes on the primary object
@object.attributes = params[params[:model]]
unless @object.save
flash[:warning] = "Failed to update the #{human_model.downcase} \"#{@object.to_label}\". "
render :action => 'edit' and return
end
# Save child objects... seems to work at the moment (for tables,
# at least)
model.admin_fieldsets.each do |set|
case set.fieldset_type
when :tabular, :child_input
next if set.options[:read_only]
is_blank = lambda do |info|
if set.options[:blank]
case set.options[:blank]
when Hash
set.options[:blank].all? do |k,v|
!info.include?(k) ||
(Proc === v ? v.call(info[k]) : info[k] === v)
end
when Proc
set.options[:blank].call(info)
end
else
info.values.all? {|v| v.blank? }
end
end
children = @object.send( set.field )
child_class = children.build.class
child_params = params[set.field.to_s]
child_params.each do |child_index, child_info|
child_info = child_info.dup
next unless Hash === child_info
child_id = child_info.delete :id
if child_info.delete(:delete) == 'DELETE' || is_blank.call(child_info)
child_class.find( child_id ).destroy if child_id
next
end
o = child_id ? child_class.find( child_id ) : children.build
unless o.update_attributes child_info
set_name = 'Child list'
set_name = set.name if set.respond_to?(:name) && !set.name.blank?
flash[:warning] = "Failed to #{o.new_record? ? 'add' : 'change'} the #{o.class.name.titleize.downcase} \"#{o.to_label}\" (#{set_name})"
o.errors.each_full {|s| flash[:warning] << "; " << s }
flash[:warning] << ". "
render :action => 'edit' and return
end
end if child_params
end
end
if params[:id]
flash[:notice] = "The #{human_model.downcase} \"#{@object.to_label}\" was changed successfully. "
else
flash[:notice] = "The #{human_model.downcase} \"#{@object.to_label}\" was added successfully. "
end
if has_history?
history = { :object_label => @object.to_label, :model => params[:model], :obj_id => @object.id }
history.update user_history_identity
if params[:id]
history.update :change => 'edit', :description => 'Record modified'
else
history.update :change => 'add', :description => 'Record created'
end
AdminHistory.new( history ).save
end
end
if params[:_continue]
flash[:notice] << "You may edit it again below."
redirect_to :action => 'edit', :model => params[:model], :id => @object
elsif params[:_addanother]
flash[:notice] << "You may add another #{human_model.downcase} below."
redirect_to :action => 'edit', :model => params[:model]
else
redirect_to list_page_for_current
end
end
def edit
@object = params[:id] ? model.find( params[:id] ) : model.new
end
# Returns a bunch (50, actually) of the latest records from the history
# table used to register admins' actions. To use this feature you need to
# add a database table like the following one:
#
# create_table :admin_histories do |t|
# t.column :obj_id, :integer
# t.column :object_label, :string
# t.column :model, :string
# t.column :user_id, :integer
# t.column :change, :string
# t.column :description, :string
# t.column :created_at, :datetime
# t.column :updated_at, :datetime
# t.column :lock_version, :integer, :default => 0
# end
#
# *Nota* *Bene*: the <tt>:user_id</tt> *must* actually be
# <em><admin model></em>_id, i.e. the same value of
# AutoAdmin::AutoAdminConfiguration#admin_model_id.
def history
@object = params[:id] ? model.find( params[:id] ) : model.new
@histories = AdminHistory.find :all, :conditions => ['model = ? AND obj_id = ?', params[:model], params[:id]], :order => 'admin_histories.created_at DESC', :limit => 50, :include => [*user_history_includes]
end
# FIXME: Force use of POST, showing a confirmation page on GET. Isn't
# there a plugin that does that? I can't find it on the Wiki atm...
def delete
object = model.find( params[:id] )
label = object.to_label
if has_history?
history_hash = { :object_label => label, :model => params[:model], :obj_id => params[:id], :change => 'delete', :description => 'Record deleted' }
history_hash.update user_history_identity
history_obj = AdminHistory.new( history_hash )
end
object.destroy
flash[:notice] = "The #{human_model.downcase} \"#{label}\" was deleted successfully."
history_obj.save! if history_obj
redirect_to list_page_for_current
end
def asset
mime_type = case params[:path].last
when /\.css$/; 'text/css'
when /\.gif$/; 'image/gif'
when /\.png$/; 'image/png'
else; 'text/plain'
end
roots = [ File.join(File.dirname(File.dirname(__FILE__)), 'public') ]
roots.unshift AutoAdmin::AutoAdminConfiguration.asset_root
filename = roots.map {|dir| File.join( dir, params[:path] ) }.detect {|file| File.exist?( file ) }
raise "Unable to locate asset #{File.join(params[:path]).inspect} in any of #{roots.size} asset roots" unless filename
# FIXME: Should we do this in develpment mode? "Development"
# generally means of the application, but what if we're working on a
# theme?
headers['Expires'] = (Time.now + 1.day).utc.to_formatted_s(:rfc822)
send_file filename, :type => mime_type
end
end