CREATE API FOR USER SIGN UP, LOGIN AND CREATE PUBLISHER WITH CURRENT USER

User Registration in Devise through API

I have recently started developing REST APIs with rails 5. I am trying to do User crude actions through API calls. I have set up a basic devise for users.

In my routes I have this:

 namespace :api do                                                                            
     namespace :v1 do                                                                         
         devise_scope :user do                                                               
            post 'signup' => 'registrations#create'                                   
            post 'signin' => 'sessions#create'                                          
            delete 'signout' => 'sessions#destroy'                                    
         end                                                                                          
         resources :publishers                                                               
      end                                                                                             
  end                                                                                                 

 

I created ONE separate controllers api_controller  for  override action controller for Api.

controllers/api/api_controller.rb

class Api::ApiController < ActionController::Base
     protect_from_forgery with: :null_session
     rescue_from ActiveRecord::RecordNotFound, with: :not_found

     #--Overwrite devise method
     def current_user
         token = request.headers['Authorization'].presence
         if token
          @current_user ||= User.find_by_auth_token(token)
         end
     end

    def authenticate_with_token!
         render json: { errors: "Not authenticated"}, status: :unauthorized unless current_user.present?
    end

    def not_found
       render json: {errors: 'Not found' }, status: 404
    end
end                                                                                                                     

model/user.rb

class User < ActiveRecord::Base 
      devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

      has_many :publishers
      # Authorization token for api sessions
      before_create :generate_auth_token!
  
      # Function used to generate token for api authentication
      def generate_auth_token!
           begin
                self.auth_token = Devise.friendly_token
           end while self.class.exists?(auth_token: auth_token)
       end
end

I created two separate controllers sessions_controller and registrations_controller to override devise methods and make it accept JSON format.

controllers/api/v1/registrations_controller.rb

class Api::V1::RegistrationsController < Api::ApiController
     respond_to :json
     skip_before_action :verify_authenticity_token
     before_action :check_user, only: [:create]

    def create
        if params[:user][:email].blank? || params[:user][:password].blank? || params[:user][:password_confirmation].blank?
             render json: {status: "failed", message: "Missing parameters"}
        else
             @user = User.new(user_params)
             @user.generate_auth_token!
             if @user.save
                   render json: {status: "successful", user: { id: @user.id, email: @user.email, auth_token: @user.auth_token, created_at: @user.created_at, updated_at: @user.updated_at }}
             else
                   render json: {status: "failed", user: @user.errors}
             end
        end
    end
    private

    def user_params
           params.require(:user).permit(:email,:password,:password_confirmation)
    end

    def check_user
         if User.exists?(email: params[:user][:email])
              render  json: {status: "failed", message: "User already exists"}
         end
    end
end

I am trying to register a user passing in the following data:

http://localhost:4000/api/v1/signup
method: post

{"user": {"email": "rohityadav@gmail.com", "password": "12345678", "password_confirmation": "12345678"}}

Your JSON is not valid.You need to enclose the string with double quotes
  1. {
  2.    "status": "successful",
  3.    "user":
  4.    {
  5.        "id": 3,
  6.        "email": "rohityadavrohit@gmail.com",
  7.        "auth_token": "LdAsqp-725-BDXG3HyHv",
  8.        "created_at": "2017-11-10T07:39:30.944Z",
  9.        "updated_at": "2017-11-10T07:47:09.411Z"
  10.    }
  11. }

 

Signin/Login:-

controllers/api/v1/sessions_controller.rb

class Api::V1::SessionsController < Api::ApiController
     respond_to :json
     skip_before_action :verify_authenticity_token
     before_filter :ensure_params_exist, only: [:create]

     def create
            resource = User.find_for_database_authentication(email: params[:user][:email])
            return invalid_login_attempt unless resource
            if resource.valid_password?(params[:user][:password])
                  sign_in("user", resource)
                  render json: {status: "successful", user: { id: resource.id, email: resource.email, auth_token: resource.auth_token, created_at: resource.created_at, updated_at: resource.updated_at }}
                  return
            end
            invalid_login_attempt
      end

      def destroy
            if current_user.present?
                  sign_out(current_user)
                  render json: {status: "successful", message: "Your Account Logged Out Successfully" }
            else
                  render json: {status: "failed", message: "Authentication token is not valid" }
            end
       end

       protected

       def ensure_params_exist
              return unless params[:user].blank?
              render json: {status: "failed", message: "Missing User Parameter"}
       end

       def invalid_login_attempt
             warden.custom_failure!
             render json: {status: "failed", message: "Error with your Email or password"}
       end
end

I am trying to login a user passing in the following data:

http://localhost:4000/api/v1/signin
method: post

{"user": {"email": "rohityadavrohit@gmail.com", "password": "12345678"}}

Your JSON is not valid.You need to enclose the string with double quotes
  1. {
  2.    "status": "successful",
  3.    "user":
  4.    {
  5.        "id": 3,
  6.        "email": "rohityadavrohit@gmail.com",
  7.        "auth_token": "LdAsqp-725-BDXG3HyHv",
  8.        "created_at": "2017-11-10T07:39:30.944Z",
  9.        "updated_at": "2017-11-10T07:47:09.411Z"
  10.    }
  11. }

Now, we will create the publisher with the current user :- 

For finding current user authentication, we need to pass the Authorization token from Rest Client header :-

controllers/api/v1/publishers_controller.rb

class Api::V1::PublishersController < Api::ApiController
     respond_to :json
     skip_before_action :verify_authenticity_token
     before_action :check_publisher, only: [:show, :destroy, :update]
     before_action :check_user

    def create
         @publisher = current_user.publishers.new(publisher_params)
         @publisher.save
         render json: {status: "successful",publisher: @publisher}
    end

    def index
        render json: {status: "successful",publisher: current_user.publishers.all}
    end

    def show
        if @publisher.present?
            render json: {status: "successful",publisher: @publisher}
        else
            render json: {status: "failed", message: "Publisher not found"}   
        end
    end

    def destroy           
        if @publisher.present?
            @publisher.destroy
            render json: {status: "successful", message: "publisher informations successfully deleted"}
        else
            render json: {status: "failed", message: "publisher not found"}   
        end
    end

    def update
        if @publisher.present?
            @publisher.update(publisher_params)
            render json: {status: "successful",publisher: @publisher}
         else
             render json: { status: "failed", message: "Publisher not found"}
         end
    end

    private

    def publisher_params
         params.require(:publisher).permit(:first_name, :last_name, :email, :telephone_number, :po_box, :island, :country, :company_name, :business_hour, :newsfeed, :business_hour_close, :media_video_link, :jw_api_key, :jw_api_secret)
  end

     def check_publisher
        if params[:id].present?
            @publisher = Publisher.where(id: params[:id])[0]
        else
            render json: {status: "failed", message: "Publisher id not present"}
        end
     end

     def check_user
         unless current_user.present?
             render json: {status: "failed", message: "Your authentication token not valid"}
        else
        end
     end
end

Create publisher :-

http://localhost:4000/api/v1/publishers
method: post

I am trying to create a publisher in the following data:

Body content:-

{"publisher": {"first_name": "test", "last_name": "test", "email": "test@g.com"}}

Your JSON is not valid.You need to enclose the string with double quotes
  1. {
  2.    "status": "successful",
  3.    "publisher":
  4.    {
  5.        "id": 1,
  6.        "first_name": "test",
  7.        "last_name": "test",
  8.        "email": "test@g.com"
  9.    }
  10. }

 

Update publisher  :-

http://localhost:4000/api/v1/publishers/:publisher_id
method: put 


Body content:-

{"publisher": {"first_name": "rohit", "last_name": "yadav", "email": "rohit@g.com"}}

Your JSON is not valid.You need to enclose the string with double quotes
  1. {
  2.    "status": "successful",
  3.    "publisher":
  4.    {
  5.        "id": 1,
  6.        "first_name": "rohit",
  7.        "last_name": "yadav",
  8.        "email": "rohit@g.com"
  9.    }
  10. }

Index method Publisher :-

http://localhost:4000/api/v1/publishers
method: get


Body Content : Nothing
  1. {
  2.    "status": "successful",
  3.    "publisher":
  4.    {
  5.        "id": 1,
  6.        "first_name": "rohit",
  7.        "last_name": "yadav",
  8.        "email": "rohit@g.com"
  9.    }
  10. }

Show Publisher:-

http://localhost:4000/api/v1/publishers/:publisher_id
method: get


Body Content : Nothing
  1. {
  2.    "status": "successful",
  3.    "publisher":
  4.    {
  5.        "id": 1,
  6.        "first_name": "rohit",
  7.        "last_name": "yadav",
  8.        "email": "rohit@g.com"
  9.    }
  10. }

Delete Publisher:-

http://localhost:4000/api/v1/publishers/:publisher_id
method: delete

Body Content : Nothing


Your JSON is not valid.You need to enclose the string with double quotes

{
  "status": "successful",
  "message": "publisher informations successfully deleted"
}

     
     
    
    
    
    
     

    Popular posts from this blog

    UPLOAD ANY MEDIA FILE WITH CARRIER-WAVE RAILS

    SELECT COUNTRY WITH STATE AND IT'S CITIES RAILS