2014-02-19 50 views
1

這是我的用戶:Rails的has_secure_password驗證錯誤

class User < ActiveRecord::Base 
    has_secure_password 
end 

這是一個人如何通過API認證:

module Api 
    class SessionsController < ApiController 
    def create 
     user = User.find_by_email(params[:user][:email]) 
     if user && user.authenticate(params[:user][:password]) 
     # some login logic 
     else 
     render json: {messages: user.errors.full_messages}, status: :unauthorized 
     end 
    end 
    end 
end 

如果我通過了不正確的密碼,我得到401未經授權預期。但是,user.errors是空白的。我如何訪問has_secure_password身份驗證錯誤?

+1

你不能手動添加'消息:「無效的電子郵件或密碼」'? - 您不驗證任何屬性,只能驗證用戶身份。 AFAIK'has_secure_password'在創建對象時提供驗證,但在用戶無法驗證時返回false。 – veritas1

回答

2

只有驗證錯誤會填充到活動記錄錯誤中。不正確的密碼不是驗證錯誤。爲什麼你不能明確地設置信息,因爲唯一可能的錯誤是電子郵件/密碼無效

module Api 
    class SessionsController < ApiController 
    def create 
     user = User.find_by_email(params[:user][:email]) 
     if user && user.authenticate(params[:user][:password]) 
     # some login logic 
     else 
     render json: {messages: ["Invalid Email or Password"]}, status: :unauthorized 
     end 
    end 
    end 
end 
1

這很容易做到。簡而言之,在用戶模型中添加一個方法(在本例中稱爲password_verified),如果authenticate失敗,則會添加錯誤。

# app/models/user.rb 
def password_verified(password) 
    verified = authenticate(password) 
    errors.add(:password, 'is invalid') unless verified 
    verified 
end 

現在,而不是調用authenticate電話password_verified。您例如,它應該是這樣的:

module Api 
    class SessionsController < ApiController 
    def create 
     user = User.find_by_email(params[:user][:email]) 
     # Here is where we call our wrapper method instead of authenticate 
     if user && user.password_verified(params[:user][:password]) 
     # some login logic 
     else 
     render json: {messages: user.errors.full_messages}, status: :unauthorized 
     end 
    end 
    end 
end 

這是加載ActiveModel使用錯誤::就像自定義驗證的意思做,所以它有據可查(即Rails的指南,ActiveRecord的驗證,errors.add)。儘管我在這裏將password_verified放在用戶模型上,但它可以像服務或關注一樣去任何地方。