Restful_authenticationと別のコントローラでユーザを認証
-
12-09-2019 - |
質問
私はそれが可能ユーザーは、可能な限り迅速にログインできるようにするためにしようとしていますので、私は、ユーザーが同じ形式でレコードをログインし、作成することができるようにしたい。
これは何とかセッションコントローラで作成したメソッドを呼び出すことにより、任意のコントローラからrestful_authenticationプラグインでユーザーを認証し、認証されたユーザーを返すことは可能ですか?これは簡単に何とか行うことができるが、私はちょうどRailsの中でそれを行う方法を見つけ出すことはできませんように思えるます。
たぶん何かます:
#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
これを行う方法上の任意のアイデアをいただければ幸いです!
解決
私はRailsの2.3.4でこのコードをテストしてみた、それが動作します。ユーザーは、認証コードではなく、それが複数のコントローラに複製持つよりも、単一の場所に住んでいるようにリファクタリングしてみてください念頭に置いて。クマにログインしたままになります。
このスニペットで認証コードが「私を覚えている」機能のいずれかを処理していないので、セッションコントローラのそのの簡易版である、ともあることに注意してください。
# 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
所属していません StackOverflow