Ruby rails - session management

Go To StackoverFlow.com

2

I am trying to manage session of users after authentication with ldap. The authentication part works very well, but can't seem to generate the session id. I get "undefined method `id' for true:TrueClass" error.

Model -

def self.Authenticate(login, pass)
  user = find_by_user_id(login)
  if user
    user
  else
    return false
  end
  conn = Net::LDAP.new(
    :host => SERVER,
    :port => PORT,
    :base => BASE,
    :auth => { 
      :username => "#{login}@#{DOMAIN}",
      :password => pass,
      :method => :simple 
    }
  )
  if conn.bind
    return true
  else
    return false
  end
rescue Net::LDAP::LdapError => e
  return false
end    

Controller -

def create
  user = User.Authenticate(params[:user_id], params[:password])

  if user
    session[:user_id] = user.id
    redirect_to theapp_url, :notice => "Logged in!"
  else
    flash.now.alert = "Invalid email or password"
    render "new"
  end
end

View -

<%= form_tag sessions_path do %>
  <p>
    <%= label_tag :Username %><br />
    <%= text_field_tag :user_id, params[:user_id] %>
  </p>
  <p>
    <%= label_tag :Password %><br />
    <%= password_field_tag :password %>
  </p>
  <p class="button"><%= submit_tag "Log in" %></p>
<% end %>

The error -

NoMethodError in SessionsController#create

undefined method `id' for true:TrueClass
Rails.root: /myapp

Application Trace | Framework Trace | Full Trace
app/controllers/sessions_controller.rb:12:in `create'
Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"OmzCrLHR1t/xfIXNcEzy2NCGfVpEKSyI4OZfqpPEFNw=",
 "user_id"=>"admin",
 "password"=>"[FILTERED]",
 "commit"=>"Log in"}
2012-04-05 00:33
by Kapish M


3

In the definition of User#Authenticate, it can return true. The controller's create action has session[:user_id] = user.id, but in this case, user is true. That is why you get the error message undefined method `id' for true:TrueClass

Modify your Authenticate method to always return a user, or modify your controller to accept true as a user value.

2012-04-05 00:51
by John Douthat
Thanks a lot John. That solved the issue. My other question is - in rails, does each session stays independent in case of multiple logins from the same user id - Kapish M 2012-04-05 01:12
yes, each session is independent - John Douthat 2012-04-05 01:14
Thanks... and lastly - How can I store additional attributes attached to the session? Like email address or full name - Kapish M 2012-04-05 01:22
Add them as columns on your users tabl - John Douthat 2012-04-05 01:47
Actually I have it done by putting in the table. But there are some ldap attributes that I have to read from ldap and store in the session. Can't really store them locally - Kapish M 2012-04-05 01:56
I would copy them from ldap and save it in your user object, OR query the ldap directory whenever you need to access it - John Douthat 2012-04-05 22:33
Ads