2012-02-18 143 views
35

我有我的rails應用程序,我遇到了設計的一個主要問題。我有一個控制器:如何使用設計登錄用戶?

class Users::SessionsController < Devise::SessionsController 
    prepend_before_filter :require_no_authentication, :only => [ :new, :create ] 
    include Devise::Controllers::InternalHelpers 

def new 
    clean_up_passwords(build_resource) 

    respond_to do |format| 
     format.html { render :layout => "sessions" } 
     format.mobile 
    end 
    end 


    # POST /resource/sign_in 
    def create 
     resource = User.find_by_email(params[:user][:email]) 
     resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new") 
     set_flash_message :notice, :signed_in 
     sign_in_and_redirect(resource_name, resource) 
    end 

end 

問題是,它從來沒有登錄的用戶,它總是停在這條線

resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new") 

我甚至把噸的記錄器在實際的創業板文件,看看我可以看到任何東西但沒有,我真的不知道如何解決這個問題。如果我評論該線路輸出,則用戶獲取登錄失敗,但如果電子郵件是不是在數據庫和任何密碼的工作(這絕對不是正確的解決方案)

我該如何解決這個問題?

UPDATE

這工作,但似乎很hackish的

# POST /resource/sign_in 
def create 
    resource = User.find_by_email(params[:user][:email]) 

    redirect_to(new_user_session_path, :notice => 'Invalid Email Address or Password. Password is case sensitive.') and return if resource.encrypted_password.blank?  
    bcrypt = BCrypt::Password.new(resource.encrypted_password) 
    password = BCrypt::Engine.hash_secret("#{params[:user][:password]}#{resource.class.pepper}", bcrypt.salt) 
    valid = Devise.secure_compare(password, resource.encrypted_password) 
# resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new") 
    if valid 
    set_flash_message :notice, :signed_in 
    sign_in_and_redirect(resource_name, resource) 
    else 
    redirect_to(new_user_session_path, :notice => 'Invalid Email Address or Password. Password is case sensitive.') and return  
    end 

end 

回答

69

如果你想在用戶登錄,使用sign_in幫助你的控制器的動作裏面:

sign_in(:user, user) 
+1

這會將他們不管,即使密碼是錯誤的或不 – Trace 2012-02-18 17:21:38

+29

檢查' user.valid_password?(params [:password])'然後。 – 2012-02-20 13:22:12

+0

我想正是這樣,但得到錯誤的參數數目(2 0)。任何想法? – ishwr 2013-10-03 10:17:20

3
resource = warden.authenticate!(:scope => resource_name) 
    sign_in(resource_name, resource) 
0

我發現這篇文章對設置請求規範的登錄很有用。 https://makandracards.com/makandra/37161-rspec-devise-how-to-sign-in-users-in-request-specs

module DeviseRequestSpecHelpers 

    include Warden::Test::Helpers 

    def sign_in(resource_or_scope, resource = nil) 
    resource ||= resource_or_scope 
    scope = Devise::Mapping.find_scope!(resource_or_scope) 
    login_as(resource, scope: scope) 
    end 

    def sign_out(resource_or_scope) 
    scope = Devise::Mapping.find_scope!(resource_or_scope) 
    logout(scope) 
    end 

end 

包括在您spec_helper

RSpec.configure do |config| 
    config.include DeviseRequestSpecHelpers, type: :request 
end 

並登錄需要

sign_in create(:user, name: 'John Doe')