Skip to content

Instantly share code, notes, and snippets.

@delba
Last active December 17, 2015 00:29
Show Gist options
  • Save delba/5521513 to your computer and use it in GitHub Desktop.
Save delba/5521513 to your computer and use it in GitHub Desktop.
Redirect to action after authentication
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
private
def signed_in?
!!session[:user_id]
end
helper_method :signed_in?
def current_user
return unless signed_in?
@_current_user ||= User.find(session[:user_id])
end
helper_method :current_user
def current_user=(user)
session[:user_id] = user.id
end
def authenticate
return_to signin_url(return_to) unless signed_in?
end
def return_to
{ return_to: request.url } if request.get?
end
helper_method :return_to
end
<% unless signed_in? %>
<%= link_to "Sign In", signin_path(return_to) %>
<% end %>
class ItemsController < ApplicationController
before_action :authenticate
def new
@item = Item.new
end
end
<%= form_tag signin_path(return_to: params[:return_to]) do %>
<%= label_tag :email %>
<%= email_field_tag :email %>
<%= label_tag :password %>
<%= password_field_tag :password %>
<%= submit_tag "Log In" %>
<% end %>
class SessionsController < ApplicationController
def create
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
self.current_user = user
redirect_to onsite_url(params[:return_to]) || root_url
else
flash.now.alert = 'Wrong email/password combination'
render :new
end
end
private
def onsite_url(url)
URI.parse(url).path if url
# URI.join(root_url, URI.parse(url).path).to_s if url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment