PhoneGap Mobile Rails身份验证(从头开始设计?身份验证?)

bot*_*bot 3 ruby ruby-on-rails devise cordova

我有一个带有Rails后端的PhoneGap应用程序.我试图找出使用json从移动应用程序验证用户的最佳方法.

我目前正在使用设计,但我不必使用它.在Phonegap中使用移动应用程序修改设计的最简单方法是什么?

我知道这里有很多帖子......但是,其中一些已经过时或者看起来非常复杂.希望可能有更多来自一些经过试验和测试的项目或教程的最新信息.

我发现的一个帖子也建议使用jsonp,但它看起来也是一个相当复杂的黑客.你可以在这里找到它:http://vimeo.com/18763953

我也想知道如果从头开始进行身份验证我是否会更好,如本Railscast中所述:http: //railscasts.com/episodes/250-authentication-from-scratch

谢谢!

Ash*_*aka 12

您应该覆盖设计的会话注册控制器.我只会告诉你如何覆盖会话控制器:

首先,转到您的用户模型并添加令牌可验证模块.像这样的东西:

devise :token_authenticatable

before_save :ensure_authentication_token
Run Code Online (Sandbox Code Playgroud)

然后编辑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
Run Code Online (Sandbox Code Playgroud)

现在编辑您的路线并指向您的新控制器:

devise_for :users, :controllers => { :registrations => 'registrations', :sessions => 'sessions' }
Run Code Online (Sandbox Code Playgroud)

然后像这样创建你的控制器:

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
Run Code Online (Sandbox Code Playgroud)

Devise 有一个关于此的页面,但它只指向一些已经过时的指南.但也许它会对你有所帮助.

  • 一个月前,我和几个朋友用Devise和Phonegap做了一个大学项目.你可以看看,但带上一粒盐.这是我们第一次使用Phonegap,所以它不是一个漂亮的应用程序,但嘿,我们完成了工作.这是**[服务器](https://github.com/GuilhermeSimoes/rails_alacarte_server/blob/master/app/controllers/sessions_controller.rb#L1)**,这里是**[客户端](https:/ /github.com/Penetra/alacarte_android_client/blob/master/assets/www/login.html#L50)**.希望能帮助到你! (3认同)