您应该覆盖设计的会话和注册控制器。我只会向您展示如何覆盖会话控制器:
首先,转到您的 User 模型并添加 Token Authenticatable 模块。像这样的东西:
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
Devise有一个关于此的页面,但它只指向一些已经过时的指南。但也许它会帮助你。