Class: Caboose::UsersController

Inherits:
ApplicationController show all
Defined in:
app/controllers/caboose/users_controller.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#add_ga_event, #admin_bulk_add, #admin_bulk_update, #before_before_action, #hashify_query_string, #init_cart, #logged_in?, #logged_in_user, #login_user, #logout_user, #parse_url_params, #reject_param, #under_construction_or_forwarding_domain?, #user_is_allowed, #user_is_allowed_to, #validate_cookie, #validate_token, #var, #verify_logged_in

Instance Method Details

#admin_addObject


214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'app/controllers/caboose/users_controller.rb', line 214

def admin_add
  return if !user_is_allowed('users', 'add')
  
  resp = StdClass.new({
      'error' => nil,
      'redirect' => nil
  })
  
  user = User.new()
  user.email = params[:email] ? params[:email].strip.downcase : nil
  user.site_id = @site.id
  
  if user.email.length == 0
    resp.error = "Please enter a valid email address."
  elsif User.where(:site_id => @site.id, :email => user.email).exists?
    resp.error = "That email is already in the system for this site."
  else
    user.save
    resp.redirect = "/admin/users/#{user.id}"
  end
  
  render :json => resp
end

#admin_add_to_roleObject


350
351
352
353
354
355
356
357
358
# File 'app/controllers/caboose/users_controller.rb', line 350

def admin_add_to_role
  return if !user_is_allowed('users', 'edit')
  user = get_edit_user(params[:id], @site.id)
  role = Role.where(:id => params[:role_id], :site_id => @site.id).first
  if user && role && !RoleMembership.where(:user_id => user.id, :role_id => role.id).exists?
    RoleMembership.create(:user_id => user.id, :role_id => role.id)
  end
  render :json => true
end

#admin_bulk_deleteObject


328
329
330
331
332
333
334
335
336
# File 'app/controllers/caboose/users_controller.rb', line 328

def admin_bulk_delete
  return unless user_is_allowed_to 'delete', 'users'
  params[:model_ids].each do |user_id|
    user = get_edit_user(user_id, @site.id)
    user.destroy if user
  end
  resp = Caboose::StdClass.new('success' => true)
  render :json => resp
end

#admin_deleteObject


339
340
341
342
343
344
345
346
347
# File 'app/controllers/caboose/users_controller.rb', line 339

def admin_delete
  return if !user_is_allowed('users', 'delete')
  user = get_edit_user(params[:id], @site.id)
  user.destroy
  resp = StdClass.new({
    'redirect' => '/admin/users'
  })
  render :json => resp
end

#admin_delete_formObject


143
144
145
146
147
# File 'app/controllers/caboose/users_controller.rb', line 143

def admin_delete_form
  return if !user_is_allowed('users', 'edit')
  @edituser = get_edit_user(params[:id], @site.id)
  redirect_to '/admin/users' if @edituser.nil?
end

#admin_editObject


83
84
85
86
87
88
89
# File 'app/controllers/caboose/users_controller.rb', line 83

def admin_edit
  return if !user_is_allowed('users', 'edit')
  @edituser = get_edit_user(params[:id], @site.id)
  @all_roles = Role.tree(@site.id)
  @roles = Role.roles_with_user(@edituser.id) if @edituser
  redirect_to '/admin/users' if @edituser.nil?
end

#admin_edit_passwordObject


131
132
133
134
135
# File 'app/controllers/caboose/users_controller.rb', line 131

def admin_edit_password
  return if !user_is_allowed('users', 'edit')
  @edituser = get_edit_user(params[:id], @site.id)
  redirect_to '/admin/users' if @edituser.nil?
end

#admin_edit_payment_methodObject


125
126
127
128
# File 'app/controllers/caboose/users_controller.rb', line 125

def admin_edit_payment_method
  return if !user_is_allowed('users', 'edit')
  @edituser = get_edit_user(params[:id], @site.id)
end

#admin_edit_rolesObject


92
93
94
95
96
97
98
# File 'app/controllers/caboose/users_controller.rb', line 92

def admin_edit_roles
  return if !user_is_allowed('users', 'edit')
  @edituser = get_edit_user(params[:id], @site.id)
  @all_roles = Role.tree(@site.id)
  @roles = Role.roles_with_user(@edituser.id) if @edituser
  redirect_to '/admin/users' if @edituser.nil?
end

#admin_exportObject


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'app/controllers/caboose/users_controller.rb', line 108

def admin_export
  return unless (user_is_allowed_to 'edit', 'users')      
  resp = Caboose::StdClass.new
  e = Caboose::Export.create(
    :kind => 'users',
    :date_created => DateTime.now.utc,        
    :params => params.to_json,
    :status => 'pending'
  )
  e.delay(:queue => 'caboose_general', :priority => 8).user_process if Rails.env.production?
  e.user_process if Rails.env.development?
  resp.new_id = e.id
  resp.success = true
  render :json => resp
end

#admin_export_singleObject


101
102
103
104
105
# File 'app/controllers/caboose/users_controller.rb', line 101

def admin_export_single
  return unless (user_is_allowed_to 'edit', 'users')
  e = Caboose::Export.where(:id => params[:id]).first      
  render :json => e
end

#admin_importObject


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
# File 'app/controllers/caboose/users_controller.rb', line 150

def admin_import
  return if !user_is_allowed('users', 'add')
  
  resp = StdClass.new
  csv_data = params[:csv_data]
  arr = []
  good_count = 0
  bad_count = 0            
  csv_data.strip.split("\n").each do |line|        
    data = CSV.parse_line(line)

    if data.count < 3
      arr << [line, true, "Too few columns"] 
      bad_count = bad_count + 1
      next
    end
    
    first_name = data[0].nil? ? nil : data[0].strip
    last_name  = data[1].nil? ? nil : data[1].strip
    email      = data[2].nil? ? nil : data[2].strip.downcase
    username   = data.count >= 4 && !data[3].nil? ? data[3].strip.downcase : nil
    password   = data.count >= 5 && !data[4].nil? ? data[4].strip : random_string(8)
    
    first_name = data[0]
    last_name  = data[1]
    email      = data[2]
    username   = data.count >= 4 ? data[3] : nil
    password   = data.count >= 5 ? data[4] : random_string(8)

    if first_name.nil? || first_name.length == 0
      arr << [line, false, "Missing first name."]
      bad_count = bad_count + 1
    elsif last_name.nil? || last_name.length == 0
      arr << [line, false, "Missing last name."]
      bad_count = bad_count + 1          
    elsif email.nil? || email.length == 0 || !email.include?('@')
      arr << [line, false, "Email is invalid."]
      bad_count = bad_count + 1          
    elsif Caboose::User.where(:email => email).exists?
      arr << [line, false, "Email already exists."]
      bad_count = bad_count + 1                    
    else                  
      Caboose::User.create(
        :first_name => first_name,
        :last_name  => last_name,
        :email      => email,
        :username   => username,          
        :password   => Digest::SHA1.hexdigest(Caboose::salt + password),
        :site_id    => @site.id
      )
      good_count = good_count + 1
    end
  end
  
  resp.success = "#{good_count} user#{good_count == 1 ? '' : 's'} were added successfully."     
  if bad_count > 0
    resp.success << "<br />#{bad_count} user#{bad_count == 1 ? '' : 's'} were skipped."
    resp.success << "<br /><br />Please check the log below for more details."
    resp.log = arr
  end      
  render :json => resp
end

#admin_import_formObject


78
79
80
# File 'app/controllers/caboose/users_controller.rb', line 78

def admin_import_form
  return if !user_is_allowed('users', 'edit')      
end

#admin_indexObject


22
23
24
# File 'app/controllers/caboose/users_controller.rb', line 22

def admin_index
  return if !user_is_allowed('users', 'view')            
end

#admin_jsonObject


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/controllers/caboose/users_controller.rb', line 27

def admin_json
  return if !user_is_allowed('users', 'view')
  pager = PageBarGenerator.new(params, {
      'site_id'         => @site.id,
		  'first_name_like' => '',
		  'last_name_like'	=> '',
		  'username_like'	  => '',
		  'email_like' 		  => '',
		},{
		  'model'          => 'Caboose::User',
	    'sort'			     => 'last_name, first_name',
		  'desc'			     => false,
		  'base_url'		   => '/admin/users',
		  'use_url_params' => false,
      'additional_where' => [ "(site_id = #{@site.id})" ]
	})    	    	      
	render :json => {
	  :pager => pager,
	  :models => pager.items.as_json(:include => :roles)    	  
	}
end

#admin_json_singleObject


50
51
52
53
54
# File 'app/controllers/caboose/users_controller.rb', line 50

def admin_json_single
  return if !user_is_allowed('users', 'view')    
  u = get_edit_user(params[:id], @site.id)
  render :json => u.as_json(:include => :roles)
end

#admin_newObject


72
73
74
75
# File 'app/controllers/caboose/users_controller.rb', line 72

def admin_new
  return if !user_is_allowed('users', 'add')
  @newuser = User.new
end

#admin_optionsObject


373
374
375
376
377
378
# File 'app/controllers/caboose/users_controller.rb', line 373

def admin_options
  return if !user_is_allowed('users', 'view')
  @users = User.where(:site_id => @site.id).reorder('last_name, first_name').all
  options = @users.collect { |u| { 'value' => u.id, 'text' => "#{u.first_name} #{u.last_name} (#{u.email})"}}
  render json: options
end

#admin_remove_from_roleObject


361
362
363
364
365
366
367
368
369
# File 'app/controllers/caboose/users_controller.rb', line 361

def admin_remove_from_role
  return if !user_is_allowed('users', 'edit')
  user = get_edit_user(params[:id], @site.id)
  role = Role.where(:id => params[:role_id], :site_id => @site.id).first
  if user && role
    RoleMembership.where(:user_id => user.id, :role_id => role.id).destroy_all
  end
  render :json => true
end

#admin_stripe_json_singleObject


57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'app/controllers/caboose/users_controller.rb', line 57

def admin_stripe_json_single
  return if !user_is_allowed('users', 'view')
  sc = @site.store_config
  u = get_edit_user(params[:id], @site.id)
  render :json => {
    :stripe_key     => sc.stripe_publishable_key.strip,        
    :customer_id    => u.stripe_customer_id,                   
    :card_last4     => u.card_last4,     
    :card_brand     => u.card_brand,       
    :card_exp_month => u.card_exp_month, 
    :card_exp_year  => u.card_exp_year
  }          
end

#admin_suObject


382
383
384
385
386
387
388
389
390
# File 'app/controllers/caboose/users_controller.rb', line 382

def admin_su
  return if !user_is_allowed('users', 'sudo')
  user = get_edit_user(params[:id], @site.id)
  if user                               
    logout_user
    (user, false)   
    redirect_to "/"
  end                        
end

#admin_su_tokenObject


393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'app/controllers/caboose/users_controller.rb', line 393

def admin_su_token
  return if params[:token].nil?
  user = get_edit_user(params[:id], @site.id)
  token = params[:token]      
  if user.token == params[:token]
    if logged_in? || logged_in_user.id == User::LOGGED_OUT_USER_ID
      Caboose.log(logged_in_user.id)          
      redirect_to "/logout?return_url=/admin/users/#{params[:id]}/su/#{user.token}"
      return
    end
    
    user.token = nil
    user.save                                
    (user)
    redirect_to '/'
  else
    render :json => false     
  end                    
end

#admin_updateObject


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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'app/controllers/caboose/users_controller.rb', line 239

def admin_update
  return if !user_is_allowed('users', 'edit')

  resp = StdClass.new     
  user = get_edit_user(params[:id], @site.id)

  save = true
  params.each do |name,value|
    case name
      when 'site_id'              then user.site_id             = value
      when 'first_name'           then user.first_name          = value     
      when 'last_name'            then user.last_name           = value 
      when "username"
        uname = value.strip.downcase
        if uname.length < 3
          resp.error = "Username must be at least three characters."
        elsif Caboose::User.where(:username => uname, :site_id => @site.id).where('id != ?',user.id).exists?
          resp.error = "That username is already taken."
        elsif uname == 'superadmin'
          resp.error = "Choose a different username."
        else
          user.username    = uname
        end
      when "email"
        email = value.strip.downcase
        if !email.include?('@')
          resp.error = "Invalid email address."
        elsif Caboose::User.where(:email => email, :site_id => @site.id).where('id != ?',user.id).exists?
          resp.error = "That email address is already in the system."
        else
          user.email    = email
        end
      when 'address'              then user.address             = value
      when 'address2'             then user.address2            = value
      when 'city'                 then user.city                = value
      when 'state'                then user.state               = value
      when 'zip'                  then user.zip                 = value
      when 'phone'                then user.phone               = value
      when 'fax'                  then user.fax                 = value
      when 'utc_offset'           then user.utc_offset          = value.to_f
      when 'locked'               then user.locked              = value
	  	when "password"			  
	  	  confirm = params[:password2]
	  		if (value != confirm)			
	  		  resp.error = "Passwords do not match.";
	  		  save = false
	  		elsif (value.length < 8)
	  		  resp.error = "Passwords must be at least 8 characters.";
	  		  save = false
	  		else
	  		  user.password = Digest::SHA1.hexdigest(Caboose::salt + value)
	  		end
	    when 'role_ids'             then user.toggle_roles(value[0], value[1])
	  	when "roles"
	  	  user.roles = [];
	  	  value.each { |rid| user.roles << Role.find(rid) } unless value.nil?
	  	  resp.attribute = { 'text' => user.roles.collect{ |r| r.name }.join(', ') }
	  	
	  	when 'card'
	  	  
	  	  sc = @site.store_config      
	  	  Stripe.api_key = sc.stripe_secret_key.strip    	  	              
  
	  	  c = nil
        if user.stripe_customer_id
          c = Stripe::Customer.retrieve(user.stripe_customer_id)
          begin          
            c.source = params[:token]
            c.save
          rescue          
            c = nil
          end
        end                  
        c = Stripe::Customer.create(:source => params[:token], :email => user.email, :metadata => { :user_id => user.id }) if c.nil?                  
        user.stripe_customer_id = c.id
        user.card_last4     = params[:card][:last4]
        user.card_brand     = params[:card][:brand]  
        user.card_exp_month = params[:card][:exp_month]
        user.card_exp_year  = params[:card][:exp_year]
        user.save
        
	  end
	end
	
	resp.success = save && user.save
	render json: resp
end

#before_actionObject


7
8
9
# File 'app/controllers/caboose/users_controller.rb', line 7

def before_action
  @page = Page.page_with_uri(request.host_with_port, '/admin')
end

#random_string(length) ⇒ Object


137
138
139
140
# File 'app/controllers/caboose/users_controller.rb', line 137

def random_string(length)
  o = [('a'..'z'),('A'..'Z'),('0'..'9')].map { |i| i.to_a }.flatten
  return (0...length).map { o[rand(o.length)] }.join
end