• Stars
    star
    732
  • Rank 61,915 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 14 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easily switch current user

switch_user

Build Status AwesomeCode Status for flyerhzm/switch_user

Inspired from hobo, switch_user provides a convenient way to switch current user without needing to log out and log in manually.

Use Case

switch_user is very useful in such use cases

  1. switch current users in development so that you don't waste your time to logout, login and input email (login) or password any more.

  2. reproduce the user specified error on production. Sometimes the error is only raised for specified user, which is difficult to reproduce for developers, switch_user can help you reproduce it by login as that user.

Example

Visit here: http://switch-user-example.herokuapp.com/admin, switch the current user in the select box.

And source code here: https://github.com/flyerhzm/switch_user_example

Install

Add in Gemfile.

gem "switch_user"

If you get the following error: undefined method `before_action' for SwitchUserController:Class, you are probably using an older version of Rails (<4). You can use this gem: https://github.com/pschambacher/rails3-before_action

Usage

Add following code into your layout page.

erb

<%= switch_user_select %>

or haml

= switch_user_select

If you want to add a class or styles

<%= switch_user_select class: 'special-select', styles: 'width: 220px' %>

= switch_user_select class: 'special-select', styles: 'width: 220px'

If there are too many users (on production), the switch_user_select is not a good choice, you should call the switch user request by yourself.

<%= link_to user.login, "/switch_user?scope_identifier=user_#{user.id}" %>
<%= link_to admin.login, "/switch_user?scope_identifier=admin_#{admin.id}" %>

= link_to user.login, "/switch_user?scope_identifier=user_#{user.id}"
= link_to admin.login, "/switch_user?scope_identifier=admin_#{admin.id}"

If you have a wildcard route in your project, add a route before the wildcard route.

# config/routes.rb
get 'switch_user', to: 'switch_user#set_current_user'
get 'switch_user/remember_user', to: 'switch_user#remember_user'
# wildcard route that will get
get ':id' => 'pages#show'

Configuration

By default, you can switch between Guest and all users in users table, you don't need to do anything. The following is some of the more commonly used configuration options.

SwitchUser.setup do |config|
  # provider may be :devise, :authlogic, :clearance, :restful_authentication, :sorcery, or {name: :devise, store_sign_in: true}
  config.provider = :devise

  # available_users is a hash,
  # key is the model name of user (:user, :admin, or any name you use),
  # value is a block that return the users that can be switched.
  config.available_users = { user: -> { User.all } } # use User.scoped instead for rails 3.2

  # available_users_identifiers is a hash,
  # keys in this hash should match a key in the available_users hash
  # value is the name of the identifying column to find by,
  # defaults to id
  # this hash is to allow you to specify a different column to
  # expose for instance a username on a User model instead of id
  config.available_users_identifiers = { user: :id }

  # available_users_names is a hash,
  # keys in this hash should match a key in the available_users hash
  # value is the column name which will be displayed in select box
  config.available_users_names = { user: :email }

  # controller_guard is a block,
  # if it returns true, the request will continue,
  # else the request will be refused and returns "Permission Denied"
  # if you switch from "admin" to user, the current_user param is "admin"
  config.controller_guard = ->(current_user, request) { Rails.env.development? }

  # view_guard is a block,
  # if it returns true, the switch user select box will be shown,
  # else the select box will not be shown
  # if you switch from admin to "user", the current_user param is "user"
  config.view_guard = ->(current_user, request)  { Rails.env.development? }

  # redirect_path is a block, it returns which page will be redirected
  # after switching a user.
  config.redirect_path = ->(request, params) { '/' }
end

If you need to override the default configuration, run rails g switch_user:install and a copy of the configuration file will be copied to config/initializers/switch_user.rb in your project.

If you want to switch both available users and available admins

config.available_users = { :user => -> { User.available }, :admin => -> { Admin.available } }

If you want to use name column as the user identifier

config.available_users_identifiers => { user: :name }

If you want to display the login field in switch user select box

config.available_users_names = { user: :login }

If you only allow switching from admin to user in production environment

config.controller_guard = ->(current_user, request) { Rails.env.production? && current_user.admin? }

If you only want to display switch user select box for admins in production environment

config.view_guard = ->(current_user, request) { Rails.env.production? && current_user && current_user.admin? }

If you want to redirect user to "/dashboard" page

config.redirect_path = ->(request, params) { "/dashboard" }

If you want to hide a 'Guest' item in the helper dropdown list

config.helper_with_guest = false

Switch Back

Sometimes you'll want to be able to switch to an unprivileged user and then back again. This can be especially useful in production when trying to reproduce a problem a user is having. The problem is that once you switch to that unprivileged user, you don't have a way to safely switch_back without knowing who the original user was. That's what this feature is for.

You will need to make the following modifications to your configuration:

config.switch_back = true
config.controller_guard = ->(current_user, request, original_user) { current_user && current_user.admin? || original_user && original_user.super_admin? }
# Do something similar for the view_guard as well.

This example would allow an admin user to user switch_user, but would only let you switch back to another user if the original user was a super admin.

Using SwitchUser with RSpec and Capybara

Add the following code to spec/support/switch_user.rb or spec/spec_helper.rb:

require 'switch_user/rspec'

You can now write your specs like so :

feature "Your feature", type: :feature do
  background do
    @user = User.make(email: '[email protected]', password: 'password')
  end

  scenario "Your scenario" do
    switch_user @user
    # or
    # switch_user :user, @user.id

    visit '/'
  end
end

How it works

Click the checkbox next to switch_user_select menu to remember that user for this session. Once this has been checked, that user is passed in as the 3rd option to the view and controller guards. This allows you to check against current_user as well as that original_user to see if the switch_user action should be allowed.

Warning

This feature should be used with extreme caution because of the security implications. This is especially true in a production environment.

Contributing

Run tests

bundle exec rspec spec

Credit

Copyright ยฉ 2010 - 2017 Richard Huang ([email protected]), released under the MIT license

More Repositories

1

bullet

help to kill N+1 queries and unused eager loading
Ruby
7,081
star
2

rails_best_practices

a code metric tool for rails projects
Ruby
4,163
star
3

chinese_pinyin

translate chinese hanzi to pinyin
Ruby
430
star
4

activemerchant_patch_for_china

A rails plugin to add an active_merchant patch for china online payment platform including alipay (ๆ”ฏไป˜ๅฎ), 99bill (ๅฟซ้’ฑ) and tenpay (่ดขไป˜้€š)
Ruby
305
star
5

css_sprite

automatically css sprite
Ruby
242
star
6

uniform_notifier

uniform notifier for rails logger, customized logger, javascript alert, javascript console, growl and xmpp
Ruby
235
star
7

rails-bestpractices.com

HTML
200
star
8

redis-sentinel

another redis automatic master/slave failover solution for ruby by using built-in redis sentinel (deprecated)
Ruby
188
star
9

eager_group

fix n+1 aggregate sql functions for rails
Ruby
122
star
10

seo_checker

check your website if it is seo.
Ruby
117
star
11

simple_cacheable

a simple cache implementation for rails
Ruby
91
star
12

code_analyzer

code analyzer tool which is extracted from rails_best_practices
Ruby
86
star
13

resque-restriction

resque-restriction is an extension to resque queue system that restricts the execution number of certain jobs in a period time.
Ruby
86
star
14

rfetion

rfetion is a ruby gem for China Mobile fetion service that you can send SMS free.
Ruby
61
star
15

chinese_regions

provides all chinese regions, cities and districts
Ruby
60
star
16

mongoid-eager-loading

eager loading for mongoid (DEPRECATED)
Ruby
54
star
17

rails-brakeman.com

online security check for rails projects
Ruby
52
star
18

contactlist

java api to retrieve contact list of email(hotmail, gmail, yahoo, sohu, sina, 163, 126, tom, yeah, 189 and 139) and im(msn)
Java
49
star
19

regexp_crawler

A crawler which uses regular expression to catch data from website.
Ruby
45
star
20

chinese_permalink

This plugin adds a capability for AR model to create a seo permalink with your chinese text. It will translate your chinese text to english url based on google translate.
Ruby
41
star
21

apis-bench

Ruby
34
star
22

sitemap

This plugin will generate a sitemap.xml from sitemap.rb whose format is very similar to routes.rb
Ruby
32
star
23

twitter_connect

facebook connect style twitter oauth
Ruby
30
star
24

taobao

Ruby Client Library for Taobao Open Platform
Ruby
27
star
25

huangzhimin.com

my homepage
HTML
24
star
26

railsbp.com

railsbp.com
JavaScript
23
star
27

multiple_mailers

extend actionmailer to allow one smtp account per mailer class.
Ruby
23
star
28

contactlist-client

The contactlist-client gem is a ruby client to contactlist service which retrieves contact list of email(hotmail, gmail, yahoo, sohu, sina, 163, 126, tom, yeah, 189 and 139) and im(msn)
Ruby
20
star
29

donatecn

demo for activemerchant_patch_for_china
Ruby
17
star
30

monitor

Monitor gem can display ruby methods call stack on browser based on unroller
JavaScript
17
star
31

authlogic_renren_connect

Extension of the Authlogic library to add Renren Connect support built upon the renren plugin
Ruby
5
star
32

rails3-template

rails3 template includes a lot of useful plugins/gems
Ruby
5
star
33

nodeslide

node.js related slideshows [deprecated], move to nodeslide.heroku.com
JavaScript
4
star
34

rubyslide.com

collect ruby rails related presentations [deprecated], moved to rubyslide.heroku.com
Ruby
4
star
35

visual_partial

This plugin provides a way that you can see all the partial pages rendered. So it can prevent you from using partial page too much, which hurts the performance.
Ruby
4
star
36

codelinestatistics

The code line statistics takes files and directories from GUI, counts the total files, total sizes of files, total lines, lines of codes, lines of comments and lines of blanks in the files, displays the results and can also export results to html file.
Ruby
4
star
37

clock_chrome_extension

google chrome extension to display multiple clock analogs for multiple timezones
2
star
38

dotfiles

Vim Script
2
star
39

showoff-understanding-mongoid

My understanding mongoid showoff presentation
Ruby
2
star
40

enough_fields

only select specified fields used
Ruby
2
star
41

skype_archive

company hackathon
Ruby
1
star
42

bullet_test

Ruby
1
star
43

play_skype

JavaScript
1
star
44

test_code_analyzer

test code for code_analyzer gem
Ruby
1
star
45

blog.huangzhimin.com

HTML
1
star
46

test_error

raise an error to test if exception_notification really works.
Ruby
1
star
47

try-ripper

code mirror of try-ripper.heroku.com
CSS
1
star