api

api

routes

namespace :api, :defaults => {:format => :json} do
      namespace :v1 do
      devise_scope :user do
      post "/sign_in", :to => 'sessions#create'
          post "/sign_up", :to => 'registrations#create'
    delete "/sign_out:id", :to => 'sessions#destroy'
          get "/users" , to: 'users#index'
          post "/users/update/:id" , to: 'users#update'
          get "/users/:id", :to => 'users#edit'
          post "/users/new" , to: 'users#create'
          get "/users/:id/destroy" , to: 'users#destroy'
          get "/users/:id/show" , to: 'users#show'
        end
    end
    end


========================================================================
user model rb


class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,:trackable
  has_many :articles, dependent: :destroy

    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
end



========================================================================

api-controller

class Api::V1::ApiController < ApplicationController
  respond_to :json
helper_method :current_user
def create
end

def destroy
end
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
=======================================================================

registrations controller signup




class Api::V1::RegistrationsController < Api::V1::ApiController
  skip_before_action  :verify_authenticity_token
  before_action :authenticate_user!, except: [:create,:destroy]
  def create
    user = User.new(registration_params)
    if user.save
      return render json: {status: 200, data: {user: user}, :message =>"Successfuly Signup"}
    else
      warden.custom_failure!
       return render json: {status: 401, data: {user: nil, errors: user.errors}, :message =>"SignUp Rollback"}
    end
  end
  def reset_password
    begin
      if params[:email].nil?
          rescue_section
      end
      @user = User.find_by_email(params[:email])
      if @user.present?
        @user.send_reset_password_instructions
        render :status=>200, :json=>{:status => true,:message=>'New Password Sent To Email'
            }
      else
        rescue_section
      end
    rescue
      rescue_section
    end
  end
  private
    def rescue_section
      return render json: {status: 500, data: {news: nil}, message: "Something Went Wrong"}
    end

    def registration_params
        params.require(:user).permit(:email, :password, :password_confirmation, :first_name, :last_name)
    end
end


========================================================================

sessions controller

login




class Api::V1::SessionsController < Api::V1::ApiController
  skip_before_action  :verify_authenticity_token
  # before_action :authenticate_user!, only: [:destroy]
  before_action :authenticate_user!, except: [:create]

  # ====================Sign IN====================================
  require 'base64'

  # eval(IO.read('doc/api_doc/auth/sign_in.html'), binding)
  def create
    # begin
      return render json: {status: 401, data: {user: nil}, message: "Request Parameter not valid"} unless params[:user]
      email = params[:user][:email]
      password = params[:user][:password]
      return render json: {status: 401, data: {user: nil}, message: "The request must contain the email and password."} unless email && password

      @user = User.where(email: email).first
      # @user = User.where(email: email).first unless @user
      return render json: {status: 401, data: {user: nil}, message: "User not found in database"} if @user.blank?
      return render json: {status: 401, data: {user: nil}, message: "Invalid email or password"} if not @user.valid_password?(password)

      sign_in(@user) 

      return render json: {status: 200, data: {user: @user}, message: "Login Successful"}
    # rescue
    #   rescue_section
    # end
  end


  # eval(IO.read('doc/api_doc/auth/sign_out.html'), binding)
  def destroy
    current_user.authentication_token = nil
    current_user.save
    return render json: {status: 200, data: nil, message: "Successfuly Log out"}
  end


   
  private
    def rescue_section
      return render json: {status: 500, data: {review: nil}, message: "Something Went Wrong"}
    end
    def registration_params
      params.require(:user).permit(:username, :email, :password, :password_confirmation, location_attributes: [:ids, :user_id, :latitude, :longitude, :device_id, :device_type, :is_active, :_destroy])
    end
end

========================================================================

user controller

user create, update. edit, show, delete


class Api::V1::UsersController < Api::V1::ApiController
      skip_before_action  :verify_authenticity_token   
  # before_action :authenticate_user!
  def index
    begin
      @users = User.all
      return render json: {status: 200, data: {users: @users}, message: "all users list"}
    rescue
      return render json: {status: 500, data: {users: nil}, message: "Something Went Wrong"}
    end
  end
  def users_as_json(data)
      # byebug
  @users = data[:users].map{ |m| m.as_json() }
end
  def create
     user = User.new(user_params)
    if user.save
      return render json: {status: 200, data: {user: user}, :message =>"user was successfully created"}
    else
      warden.custom_failure!
       return render json: {status: 401, data: {user: nil, errors: user.errors}}
    end
  end
  def edit
    user = User.find(params[:id])
    render json: user
  end
 def show
    @user = User.find_by_id(params[:id])
    if @user.present?
     render json: {status: 200, data: {user: @user}, message: "user Details"}
    else
      render json: { errors: "Please enter correct id" },status: :unprocessable_entity
    end
  end
  def update
   if params[:id].present?
    if User.all.map(&:id).include?(params[:id].to_i)
      @user = User.find(params[:id])
    if @user.update(user_params)
      render json: {status: 200, data: {user: @user}, message: "Successfully Updated"}
    else
      render json: { errors: @user.errors.full_messages }, status: :unprocessable_entity
    end
    else
      render json: { error: 'Could not be found for this id.' }
    end
    else
      render json: { error: 'Please Add parameter id.' }
    end
  end
  def destroy
    @user = User.find_by_id(params[:id])
    if @user.present?
      @user.delete
      render json: {status: 200, message: "Successfully Deleted"}
    else
      render json: { error: 'Could not be found for this id.' }
    end
  end
  private
    def rescue_section
      return render json: {status: 500, data: {news: nil}, message: "Something Went Wrong"}
    end

    def user_params
      params.permit(:first_name, :last_name, :email, :password, :password_confirmation, :image, :start_date, :end_date)
    end
end
========================================================================

user scheema rb



create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "first_name"
    t.string "last_name"
    t.string "authentication_token"
  *  t.integer "sign_in_count", default: 0, null: false
  *  t.datetime "current_sign_in_at"
  *  t.datetime "last_sign_in_at"
  *  t.string "current_sign_in_ip"
  *  t.string "last_sign_in_ip"
    t.string "image"
    t.datetime "start_date"
    t.datetime "end_date"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
=======================================================================

NOTE---- Five Column Add For  Users TableThis Star
========================================================================

Comments

Post a Comment

Popular posts from this blog

rvm setup new ruby install system

masking account number

Ruby install for new system