PhoneGap Mobile Rails Authentication (devise? authentication from scratch?)

前端 未结 1 473
悲哀的现实
悲哀的现实 2021-01-01 06:44

I have a PhoneGap app with a Rails backend. I\'m trying to figure out what the best way is to authenticate a user from the mobile app using json.

I am using devise c

相关标签:
1条回答
  • 2021-01-01 07:27

    You should override devise's sessions and registrations controller. I'll only show you how to override the sessions controller:

    First, go to your User model and add the Token Authenticatable module. Something like this:

    devise :token_authenticatable
    
    before_save :ensure_authentication_token
    

    Then edit your devise.rb file to configure that module:

    # 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
    

    Now edit your routes and point to your new controllers:

    devise_for :users, :controllers => { :registrations => 'registrations', :sessions => 'sessions' }
    

    And then create your controller like this:

    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 has a page about this, but it only points to some already outdated guides. But maybe it will help you.

    0 讨论(0)
提交回复
热议问题