我有一个带有Rails后端的PhoneGap应用程序。我试图找出使用json从移动应用程序验证用户的最佳方法。
我目前正在使用设计,但我不必使用。在Phonegap中使用移动应用程序修改设计的最简单方法是什么?
我知道这里有很多帖子......但是,有些帖子已经过时或看起来非常复杂。希望可能有更多来自一些经过试验和测试的项目或教程的最新信息。
我发现的一个帖子也建议使用jsonp,但它看起来也是一个相当复杂的黑客。您可以在此处找到它:http://vimeo.com/18763953
我也想知道如果从头开始进行身份验证我是否会更好,如Railscast中所述:http://railscasts.com/episodes/250-authentication-from-scratch
谢谢!
答案 0 :(得分:12)
您应该覆盖设计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,但它只指向一些已经过时的指南。但也许它会帮助你。