Search code examples
ruby-on-railsauthenticationrestful-authenticationruby-grape

API key authentication with grape and rails


This is my api/authentication/request.rb

module Authentication
  class Request < Grape::API
    version 'v1', using: :path

    helpers do
      def authenticate(token)
        error!('401 Unauthorized', 401) unless (AccessToken.where(token: params[:token]))
      end
    end

    resource :request do
      get :index

      params do
        Authreq.all
      end
    end

    params do
      requires :id, type: Integer
    end

    resource :request do
      get :all do
        params do
          requires :email ,type: String
        end

        Authreq.all
      end

      params do
        requires :email_id ,type: String
        requires :website ,type: String
        requires :token, type: String
      end

      post :authreq do
        authenticate(:token)

        Authreq.create!(
          email: params[:email_id],
          site_name: params[:website],
          accepted: 0
        )
      end
    end
  end
end

BTW, I've AccessToken Model as follows :

class AccessToken < ActiveRecord::Base
  before_create :generate_token

  private

  def generate_token
    begin
      self.token = SecureRandom.hex
    end while self.class.exists?(token: token)
  end
end

But I don't know why this is getting invalid. The authentication doesn't work. I want to use an API key based authentication for Grape with Rails and I use devise btw.

If anyone has any other ideas on how to implement authentication and authorization, It'd be awesome!


Solution

  • Figured it myself,

    Auth Function be like:

    helpers do
      def authenticate(token)
          error!('401 Unauthorized', 401) unless AuthToken.where(access_token: token).present?
      end
    end
    

    and call the function to authenticate

    like

    authenticate(params[:token])
    

    provided I'm asking the user to input the token ( using requires :token, type: String)