Wednesday, 13 December 2017

Mobile Rails API with Devise

1. Add column in User table

   rails g migration AddAuthenticationtokenToUsers authentication_token:string

2.  rails generate controller Api/V1/Api

3. User.rb
 
   before_save :ensure_authentication_token
   def ensure_authentication_token
    if authentication_token.blank?
      self.authentication_token = generate_authentication_token
    end
  end

  private
  def generate_authentication_token
 loop do
   token = Devise.friendly_token
   break token unless User.find_by(authentication_token: token)
 end
  end

4.  ApiController

  class Api::V1::ApiController < ApplicationController
  def create
  end

  def destroy
  end
  respond_to :json
helper_method :current_user
def getting_started
end
def current_user
 @current_user ||= User.where(authentication_token: request.headers['User-Token']).first
end
def authenticate_user!
 return render json:{error:'401 Unauthorized!'},status: 401 unless current_user
end
end

5.  application controller with user over
 
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up) do |user|
      user.permit(:email, :password,:password_confirmation, :remember_me)
    end
    devise_parameter_sanitizer.permit(:sign_in) do |user|
      user.permit(:email, :password)
    end
    devise_parameter_sanitizer.permit(:account_update) do |user|
      user.permit(:email, :password,:password_confirmation, :current_password)
    end
  end


routes.rb

namespace :api do
    namespace :v1 do
      devise_scope :user do
        post "/sign_in", :to => 'sessions#create'
        post "/sign_up", :to => 'registrations#create'
        put '/change_password', to: 'registrations#change_password'
        get "/profile", :to => 'registrations#profile'
        post "/update_account", :to => 'registrations#update'
        # delete "/sign_out", :to => 'sessions#destroy'
        # get "/reset_password", :to => 'registrations#reset_password'
        # get "/reset_password_link", :to => 'registrations#reset_password_link'
      end
    end
  end

6. Apipie Doc

  gem 'apipie-rails'

 bundle install
 rails g apipie:install

config/initializers/apipie.rb

Apipie.configure do |config|
  config.translate = false
  config.app_name                = "project_name"
  config.api_base_url            = ""
  config.doc_base_url            = "/apipie"
  # where is your API defined?
  config.api_controllers_matcher = ["#{Rails.root}/app/controllers/*/*/*.rb", "#{Rails.root}/app/controllers/*/*.rb", "#{Rails.root}/app/controllers/*.rb"]
  config.authenticate = Proc.new do
    authenticate_or_request_with_http_basic do |username, password|
      username == "admin" && password == "password"
    end
  end
end



Doc URL:

 https://jee-appy.blogspot.in/2016/03/how-to-make-rest-api-in-rails.html