您應該重寫設備的sessions和registrations控制器。我只會告訴你如何覆蓋會話控制器:
首先,轉到你的用戶模型並添加令牌認證模塊。事情是這樣的:
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,但它只指向一些已經過時的指南。但也許它會幫助你。
+1謝謝你。你知道關於在移動端存儲會話嗎?我聽說phonegap沒有cookies,所以這意味着我不得不使用localStorage存儲cookie,然後以某種方式發佈每個請求? – botbot
btw @Ashitaka,你說的對,那些文檔有點過時。我真的很驚訝這種設置沒有更多的文檔記錄,因爲移動應用程序和軌道似乎是近來的趨勢。 – botbot
只需搜索本地存儲,它非常容易。在您的Phonegap應用程序中,登錄時,對會話url進行ajax調用(您可以使用'rake routes'找到它),然後使用以下內容存儲該令牌:'localStorage.setItem('auth_token',authentication_token);'。然後你可以用'localStorage.getItem('auth_token')'檢索它。 – Ashitaka