Simple Remember me functionality in Ruby on Rails with expiration date .

I have gone through ton of code for completing remember me functionality, i sink every time ,last i decided to code my own and i got it. Now you can use it.

You need to make changes only in two files.
1>app/controllers/*.rb (eg. account.rb)
2>app/views/your directory/*.rhtml (eg. login.rhtml)

before_filter :loginformcookies

def loginformcookies
if !cookies[:remember_me_id].blank? && !User.count.zero?
if ( User.find(cookies[:remember_me_id]) and Digest::SHA1.hexdigest(User.find(cookies[:remember_me_id]).email)[4,18] == cookies[:remember_me_code])
params[:username]=User.find(cookies[:remember_me_id].to_i).login
params[:test]=cookies[:remember_me_pass]
end
end
end

def login
case request.method
when :post
if  session[:user] = User.authenticate(params[:user_login], params[:user_password])
if params[:rememberme]
userId = session[:user][:id].to_s
cookies[:remember_me_id] = { :value => userId, :expires => 30.days.from_now }
userCode = Digest::SHA1.hexdigest(session[:user][:email])[4,18]
cookies[:remember_me_pass] = {:value =>params[:user_password],  :expires => 10.days.from_now}
cookies[:remember_me_code] = {:value =>userCode, :expires => 10.days.from_now}
else
cookies.delete :remember_me_pass
cookies.delete :remember_me_code
cookies.delete :remember_me_id
end
flash[:notice]  = “Login successful”
cookies[:is_admin] = “yes”
redirect_back_or_default :controller => “admin/general”, :action => “index”
else
flash.now[‘notice’]  = “Login unsuccessful”

@login = params[:user_login]
end
end
end

In view file just pass that variable which you are getting in filter (loginformcookies).

and have fun.

Advertisements

One thought on “Simple Remember me functionality in Ruby on Rails with expiration date .

  1. dharmdip says:

    yes ! Chephz you can do that
    timestamp =Time.now or any else dynamic ..
    cookies[:remember_me_pass] = {:value =>params[:user_password], :expires => timestamp}

    if not working then tell me ..

    Thanks,
    Dharmdip

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s