2012-11-29 137 views
3

我有一個帶有Rails後端的PhoneGap應用程序。我試圖找出使用json從移動應用程序認證用戶的最佳方式。PhoneGap Mobile Rails身份驗證(從零開始設計?身份驗證?)

我目前使用設計,,但我不必使用。什麼是最簡單的方法來修改設計與Phonegap中的移動應用程序一起工作?

我知道這裏有不少帖子......但是,其中一些已經過時或看起來像非常複雜的黑客。希望可以從一些經過測試的項目或教程中獲得更多的最新信息。

我發現的一個帖子也建議使用jsonp,但它也看起來像一個非常複雜的黑客。你可以在這裏找到它:http://vimeo.com/18763953

我也想知道,如果我只想過得更好與認證從頭開始了,在這個Railscast佈局:http://railscasts.com/episodes/250-authentication-from-scratch

謝謝!

回答

12

您應該重寫設備的sessionsregistrations控制器。我只會告訴你如何覆蓋會話控制器:

首先,轉到你的用戶模型並添加令牌認證模塊。事情是這樣的:

devise :token_authenticatable 

before_save :ensure_authentication_token 

然後編輯devise.rb文件來配置該模塊:

# You can skip storage for :http_auth and :token_auth by adding those symbols to the array below. 
config.skip_session_storage = [:token_auth] 

# Defines name of the authentication token params key 
config.token_authentication_key = :auth_token 

現在編輯您的路線和點到新的控制器:

devise_for :users, :controllers => { :registrations => 'registrations', :sessions => 'sessions' } 

然後像這樣創建你的控制器:

class SessionsController < Devise::SessionsController 
    def create 
    respond_to do |format| 
     format.html { 
     super 
     } 
     format.json { 
     build_resource 
     user = User.find_for_database_authentication(:email => params[:user][:email]) 
     return invalid_login_attempt unless resource 

     if user.valid_password?(params[:user][:password]) 
      render :json => { :auth_token => user.authentication_token }, success: true, status: :created 
     else 
      invalid_login_attempt 
     end 
     } 
    end 
    end 

    def destroy 
    respond_to do |format| 
     format.html { 
     super 
     } 
     format.json { 
     user = User.find_by_authentication_token(params[:auth_token]) 
     if user 
      user.reset_authentication_token! 
      render :json => { :message => 'Session deleted.' }, :success => true, :status => 204 
     else 
      render :json => { :message => 'Invalid token.' }, :status => 404 
     end 
     } 
    end 
    end 

    protected 
    def invalid_login_attempt 
    warden.custom_failure! 
    render json: { success: false, message: 'Error with your login or password' }, status: 401 
    end 
end 

設計has a page about this,但它只指向一些已經過時的指南。但也許它會幫助你。

+0

+1謝謝你。你知道關於在移動端存儲會話嗎?我聽說phonegap沒有cookies,所以這意味着我不得不使用localStorage存儲cookie,然後以某種方式發佈每個請求? – botbot

+1

btw @Ashitaka,你說的對,那些文檔有點過時。我真的很驚訝這種設置沒有更多的文檔記錄,因爲移動應用程序和軌道似乎是近來的趨勢。 – botbot

+1

只需搜索本地存儲,它非常容易。在您的Phonegap應用程序中,登錄時,對會話url進行ajax調用(您可以使用'rake routes'找到它),然後使用以下內容存儲該令牌:'localStorage.setItem('auth_token',authentication_token);'。然後你可以用'localStorage.getItem('auth_token')'檢索它。 – Ashitaka