Authlogic Rails 3.1 - ruby-on-rails-3

Which version of authlogic are people using with Rails 3.1.
I have the following entry in my gemfile:
gem 'authlogic', :git => 'https://github.com/AndreasWurm/authlogic.git'
The problem I have is with a piece of code in my base ApplicationController.
def require_no_user
if current_user
store_location
flash[:notice] = "You must be logged out to access this page"
redirect_to :controller => "home", :action => "index"
return false
end
end
def store_location
session[:return_to] = request.request_uri
end
The error I am getting is with the line:
session[:return_to] = request.request_uri
I am getting an error saying:
undefined method `request_uri' for #<ActionDispatch::Request:0x7dadd4d8>
Has Request_uri been removed from ActionDispatch and if so, what is the correct alternative?

The best solution is as said Vadim, using the new methods in ActionDispatch::Request :
You just replace :
def store_location
session[:return_to] = request.request_uri
end
by :
def store_location
session[:return_to] = request.url
end
and it's done !

fullpath will give you url(but without protocol, port, domain) with params
and request.url will give you everything that fullpath skips

Related

Redirect rails app to home page on crash

I want my app to redirect to my home page ie posts#index. It is a rails2 app which I am trying to migrate to rails 3.
def rescue_action_in_public(exception)
flash[:notice] = "There was an error. Please try again." # #{exception}
redirect_to :controller => :posts, :action => :index
end
This method I presume does this task. How ever, It won't work in rails 3 and I see the 'Sorry something went wrong!' page
How can I get this functionality working in rails 3? If any more info is, needed I am willing to paste here.
in rails 3 try this
def rescue_action_in_public(exception)
status = status_code(exception)
locale_path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
path = "#{public_path}/#{status}.html"
if locale_path && File.exist?(locale_path)
render(status, File.read(locale_path))
elsif File.exist?(path)
render(status, File.read(path))
else
render(status, '')
end
end
from apidock
You can right this way!
def rescue_action_in_public(exception)
flash[:notice] = "There was an error. Please try again." # #{exception}
redirect_to posts_path
end

how to stub or mock authlogic current_user in view specs

i am trying to write some views specs for my rails app, but i stumble on this error:
ActionView::Template::Error:
undefined local variable or method `current_user' for #<#<Class:0x007fa47d2612d0>:0x007fa47e267710>
Here is how i wrote my view spec :
describe "/newsletters/index.html.erb" do
include NewslettersHelper
include Authlogic::TestCase
def current_user(stubs = {})
#current_user ||= mock_model(User, stubs)
end
def user_session(stubs = {}, user_stubs = {})
#current_user_session ||= mock_model(UserSession, {:user => current_user(user_stubs)}.merge(stubs))
end
def login(session_stubs = {}, user_stubs = {})
UserSession.stub!(:find).and_return(user_session(session_stubs, user_stubs))
end
def logout
#user_session = nil
end
context "without a logged-in user" do
before(:each) do
activate_authlogic
logout()
assigns[:newsletters] = #newsletters = [ mock_model(Newsletter, :titre => "value for titre",
:sommaire => "value for sommaire", :content => "value for content") ]
end
it "renders a list of newsletters" do
# pending("find how to mock authlogic current user in views spec")
render
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for titre")
end
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for sommaire")
end
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for content")
end
end
end
Try controller.stub(:current_user) { mock_model(User) } I think it should help
The view spec is an isolated context so you need to stub the current_user method in the view context.
view.stub(:current_user).and_return(mock_model(User))
For further reading on the view spec I suggest you the view spec page on relish
None of the answers worked for me (using rspec 3.9 here), as I was getting errors like #<#<Class:0x007fb9ca387dc8> does not implement: current_user, trying to stub the view or controller objects, so I had to do it like:
before do
controller.singleton_class.class_eval do
# Just defining methods to being stubbed later
def current_user; end
def current_account; end
helper_method :current_user, :current_account
end
allow(controller).to receive(:current_user).and_return(user)
allow(controller).to receive(:current_account).and_return(account)
end
not the prettiest solution, but it worked.

Integrating ActiveAdmin and adauth

I have a running Rails application, using ActiveAdmin and its models to autenticate users. Now I'm interested in moving to an ActiveDirectory authentication, so my users can validate wiht the domain's users.
I've been trying adauth and it looks like a great gem, but I'm a little bit lost when trying to "mix" this gem with my ActiveAdmin authentication. I'm pretty sure I'm not the first one in doing it, so any help would be appreciated.
Thanks!
I finally was able to manage to integrate AD in ActiveAdmin.
Here's what I did, in case someone is interested:
Include gem 'adauth' in your gems
Execute bundle install
Execute rails g adauth:config
Configure the config/initializers/adauth.rb for your AD connection. For example, if your domain is example.com, you must include:
c.domain = "example.com"
c.server = "IP address of your domain controller"
c.base = "dc=example, dc=com"
Execute rails g adauth:sessions
Modify your application_controller.rb. Mine was:
class ApplicationController< ActionController::Base
protect_from_forgery
helper_method :current_user
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def authenticate_user!
if current_user.nil?
redirect_to '/sessions/new', :error => "Invalid Login"
end
end
end
Execute rails g adauth:user_model user install_adauth.
This creates the migration install_adauth, but for some reason it was empty. I had to fill it myself with:
class InstallAdauth < ActiveRecord::Migration
def up
create_table :users do |u|
u.string 'login'
u.text 'group_strings'
u.string 'name'
u.string 'ou_strings'
end
end
def down
drop_table :users
end
end
Execute rake db:migrate
Modify your sessions_controller.rb. Mine was:
class SessionsController < ApplicationController
def new
redirect_to '/admin' if current_user
end
def create
ldap_user = Adauth.authenticate(params[:username], params[:password])
if ldap_user
user = User.return_and_create_with_adauth(ldap_user)
session[:user_id] = user.id
redirect_to '/admin'
else
redirect_to '/sessions/new', :error => "Invalid Login"
end
end
def destroy
session[:user_id] = nil
redirect_to '/sessions/new'
end
end
So far the validation through ActiveAdmin still works. To switch to ActiveDirectory we must change the file initializers/active_admin.rb
# config.authentication_method = :authenticate_admin_user!
config.authentication_method = :authenticate_user!
#config.current_user_method = :current_admin_user
config.current_user_method = :current_user
In my case, I needed to restart Apache too.
If anytime we want to switch back to ActiveAdmin, we just need to undo the last change

Rails 3 error in Safari only - ActiveRecord::RecordNotFound (Couldn't find User with auth_token = ):

In following Railscast #274 to get reset password working in my Rails 3 app, I am experiencing a weird issue in Safari. If I run my app in Heroku I get the following error when I go to my root:
ActiveRecord::RecordNotFound (Couldn't find User with auth_token = ):
app/controllers/application_controller.rb:39:in `lookup_user'
app/controllers/application_controller.rb:32:in `current_user'
app/controllers/application_controller.rb:54:in `logged_in?'
app/controllers/users_controller.rb:8:in `new'
If use Firefox and Chrome (in incognito mode) it works. In Safari, I found that if I get the error, I can make it go away by navigating to /logout. Then the page renders perfectly.
Here's my route for /logout and root:
match "/logout" => "sessions#destroy", :as => "logout"
root :to => "users#new"
Here's my destroy action in sessions_controller:
def destroy
reset_session
cookies.delete(:auth_token)
redirect_to root_path, :notice => "You successfully logged out"
end
My application_controller:
protected
def current_user
#current_user ||= lookup_user
end
def lookup_user
if session[:user_id]
User.find_by_id(session[:user_id])
elsif cookies[:auth_token]
User.find_by_auth_token!(cookies[:auth_token])
end
end
And lastly, here's my new action in users_controller:
def new
#user = User.new
#user.profile = Profile.new
if logged_in?
redirect_to profile_path(current_user)
end
end
What I've tried:
To alter the new action to delete cookies with the following:
def new
#user = User.new
#user.profile = Profile.new
if logged_in?
redirect_to profile_path(current_user)
elsif
cookies.delete(:auth_token)
end
end
The rake task below, as suggested in the Railscast comments:
namespace :user do
desc "Rebuild Auth-Tokens"
task :rebuild_auth_token => :environment do
User.transaction do
User.all.each { |u|
u.generate_token(:auth_token)
u.save!
}
end
end
end
(I ran this with `heroku run rake user:rebuild_auth_token`)
Neither seems to have worked. Can anyone help me figure this out?
Anytime you regenerate the user :auth_code's you will need to delete your cookies for that domain. In a production, you should not regenerate :auth_codes and you will never have this issue, unless users edit their cookies.
In addition I have posted a response on the railscast.com authentication (revised) solution so Ryan can take a look at it.
Good luck!

Call back to Application Controller error - NameError (undefined local variable or method

I'm upgrading an application from Rails 2 to 3. I use a Rights and Role approach for authentication that worked fine under Rails 2. In my Application Controller (application.rb) I have:
class ApplicationController < ActionController::Base
def check_authentication
unless session[:user]
session[:intended_resource] = request.request_uri
session[:intended_action] = action_name
session[:intended_controller] = controller_name
redirect_to :controller => "sessions", :action => "new"
return false
end
end
def check_authorization
user = User.find(session[:user])
unless user.roles.detect{|role|
role.rights.detect{|right|
right.action == action_name && right.controller == self.class.controller_path
}
}
flash[:notice] = "You are not authorized to view the page you requested"
request.env["HTTP_REFERER"] ? (redirect_to :back) : (redirect_to :controller => "sessions", :action => "new")
return false
end
end
end
In my other controllers I've included a before filter.
before_filter :check_authentication,:check_authorization
I'm getting the following error message, for example, when I go to my Dashboard Controller.
NameError (undefined local variable or method `check_authentication' for DashboardController:0x0000010291a0c0):
Is there something else I need to change or add to make this work in Rails 3?
Thanks,
Aaron
Make sure that your DashboardController is inheriting from ApplicationController i.e. DashboardController < ApplicationController.
Problem solved. Somehow during my upgrade I had a file named application.rb and application_controller.rb in my controllers folder. Both were defined as ApplicationController < ActionController::Base. The code for my "real" Application Controller was sitting in application.rb and not in application_controller.rb, which was empty. A simple copy-n-paste and things were fine. I don't know how that happened. Running the rails_upgrade plugin didn't go as smoothly as planned.