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