Alan Coromano
Alan Coromano

Reputation: 26018

"Remember me" option - how do I implement it?

I have a simple authentication system in my Sinatra application. It's basically set the session[:user_id] to user's id when an user enters their correct login and password and that's it. This is enough for now, I won't use another solutions.

What I need to do is to make "remember me" option. So how can I do this for my simple solution? I can't figure it out.

Upvotes: 1

Views: 786

Answers (2)

Mario Camou
Mario Camou

Reputation: 2353

The way I've done it is this (we're using OmniAuth for the authentication and Mongoid for user storage - the login form uses AJAX so the reply is JSON). The HTML field that corresponds to the "Remember me" checkbox is called "remember":

post '/auth/identity/callback' do
  u = User.find(env['omniauth.auth']['uid'])
  session[:user] = u
  session.options[:expire_after] = 2592000 unless params['remember'].nil? # 30 days
  [200, {:msg => 'User logged in'}.to_json]
end

The key here is the sessions.options[:expire_after] line. If you don't set :expire_after, the cookie will be automatically deleted when the browser quits. Once you set it, the cookie becomes persisten across browser restarts, and is kept for the number of seconds specified.

Upvotes: 5

fmendez
fmendez

Reputation: 7338

You could leverage the Sinatra Cookies for that. Perhaps checking for a 'remember_me' param and assigning the user id to the cookies if it exist. For instance, this is a Rails example, but the intension is the same:

def login_user
    begin
      @user = User.authenticate(params)
      if @user
        if params[:remeberme] 
          cookies.permanent[:user_id] =  @user.id.to_s
        else
          cookies[:user_id] = @user.id.to_s
        end
      end
    rescue Exception => e
      @errors = [e]
    end
  end

Sinatra Cookies

Upvotes: 0

Related Questions