您应该重写设备的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