Login as various users during development can become pretty annoying especially since it’s very difficult to remember all of the passwords across users or apps. If your app authentication happen to be built with Sorcery here’s is a very easy and straightforward way how to implement auto login.
First we need a new route:
# in routes.rb if Rails.env.development? get 'autologin/:id', to: 'sessions#autologin', as: 'autologin' end
Restricting to development environment is important security wise although there might be cases when you want to do auto login in different environment. Good option is also to go with an environment variable.
I am adding the autologin method to
SessionsController to keep it together with other session actions:
class SessionsController < ApplicationController ... def autologin user = User.find(params[:id]) auto_login(user) redirect_to root_url end end
The method is simple since the heavy lifting is done by
auto_login method from Sorcery.
Finally we can add little HTML snipped next to our login form:
<% if Rails.env.development? %> Autologin: <br /> <% User.all.each do |user| %> <%= link_to user.email, autologin_path(user.id) %> <% end %> <% end %>
Here we generate a sign in link for every user in our development database. This would also make a nice helper.
← BUY THE PRE-RELEASE
I am writing a complete guide on web application deployment. Ruby with Puma, Python with Gunicorn, NGINX, PostgreSQL, Redis, networking, processes, systemd, backups, and all your usual suspects. Final release soon!