Question

I am trying to make it possible for users to login as quick as possible, so I want users to be able to login and create records in the same form.

Is it possible to authenticate a user with the restful_authentication plugin from any controller by somehow calling the create method in the session controller, and return the authenticated user? It seems like this could be done easily somehow, but I just can't figure out how to do it in Rails.

Maybe something like:

#Records Controller

def create
    if params[:login] && params[:password]
        #This method would call /session/ and pass the login/password params
        user = authenticate_user(params[:login'], params[:password])
    end

    @record = Record.new(params[:record])
    @record.user = user

    if @question.save && user
        flash[:notice] = 'Record was successfully created.'
        redirect_to(@record)
    end
end

Any ideas on how to do this would be appreciated!

Was it helpful?

Solution

I've tested this code on Rails 2.3.4 and it works; the user remains logged in. Bear in mind that you should try to refactor so that the authentication code lives in a single place, rather than having it duplicated in several controllers.

Note also that the authentication code in this snippet is a simplified version of that in the Sessions controller, & so doesn't handle any of the 'remember me' functionality.

# POST /stacks
# POST /stacks.xml
def create
  @stack = Stack.new(params[:stack])

  if params[:login] && params[:password]
    logout_keeping_session!
    user = User.authenticate(params[:login], params[:password])
    self.current_user = user
  end

  respond_to do |format|
    if !user
      flash[:error] = 'Login details incorrect.'
      format.html { render :action => "new" }
      format.xml  { render :xml => @stack.errors, :status => :unprocessable_entity }
    elsif @stack.save
      flash[:notice] = 'Stack was successfully created.'
      format.html { redirect_to(@stack) }
      format.xml  { render :xml => @stack, :status => :created, :location => @stack }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @stack.errors, :status => :unprocessable_entity }
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top