Wednesday, 23 December 2020

Image upload by active storage

 

https://www.dailysmarty.com/posts/steps-for-using-active-storage-to-upload-files-to-s3-with-ruby-on-rails

https://github.com/jeygeethan/activestorage-backblaze

Add gem:

gem 'activestorage-backblaze'   is gem only user for backblaze ke liye hai.

gem "aws-sdk-s3", require: false


Image upload on backblaze:

backblaze:

  service: Backblaze

  bucket_name: <%= ENV['BUCKET_NAME'] %>

  bucket_id: <%= ENV['BUCKET_ID'] %>

  key_id: <%= ENV['KEY_ID'] %>

  key_token: <%= ENV['KEY_TOKEN'] %>



Run the command:

rails active_storage:install

Followed by:

rails db:migrate

 

Step 2 - Update Storage Parameters

In the config/storage.yml file, uncomment the 'amazon' configuration options. Make sure to add your region and bucket name.

Add this code config/storage.yml

amazon:

  service: S3

  access_key_id: <%= ENV['AWS_ACCESS_KEY'] %>

  secret_access_key: <%= ENV['AWS_SECRET_KEY'] %>

  region: <%= ENV['AWS_RESION'] %>

  bucket: <%= ENV['AWS_BUCKET'] %>



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


In the config/environments/development.rb there should be a line that says:

config.active_storage.service = :local

And in the config/environments/production.rb you'll need to remove the line:

config.active_storage.service = :local

And add the line:

This is amazon

config.active_storage.service = :amazon

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

This is backblaze

config.active_storage.service = :backblaze


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


Add a model:

has_one_attached :featured_image


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

Image upload form minio

Add this code config/storage.yml

minio_dev:

  service: S3

  access_key_id: <%= ENV['STORAGE_ACCESS_KEY'] %>

  secret_access_key: <%= ENV['STORAGE_SECRET_ACCESS_KEY'] %>

  region: <%= ENV['STORAGE_REGION'] %>

  bucket: <%= ENV['STORAGE_BUCKET'] %>

  endpoint: <%= ENV['Endpoint'] %>

  force_path_style: true


and config/development.rb and production.rb

config.active_storage.service = :minio_dev

---------------------------------

If in case getting this erro:
undefined method `has_one_attached' for #<Class:0x000055cfabb92460> (NoMethodError)


Add this line in application.rb

ActiveSupport.on_load(:active_record) do
  include ActiveStorage::Reflection::ActiveRecordExtensions
  ActiveRecord::Reflection.singleton_class.prepend(ActiveStorage::Reflection::ReflectionExtension)
  include ActiveStorage::Attached::Model
end
On top:


attribute :profile_image do |object|

      if object.profile_pic.attached?

        # ENV["API_BASE_URL"] + Rails.application.routes.url_helpers.rails_blob_url(object.profile_pic, only_path: true)

        object.profile_pic.service_url

      end

    end

Thursday, 5 November 2020

elasticsearch Install And Setup Elasticsearch Engine On Linux

 Elasticsearch install step by step

java -v

java -version

echo $JAVA_HOME

ls /usr/lib/jvm//java-

for Result

java-1.7.0-openjdk-amd64/ java-1.8.0-openjdk-amd64/ java-7-openjdk-amd64/     java-8-openjdk-amd64/


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

for run Tab ke through check karna hai: echo /usr/lib/jvm/java-8-openjdk-amd64/

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

Set environment variable:

sudo nano /etc/environment


JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/

PATH=$PATH:$HOME/bin:$JAVE_HOME/bin

export JAVE_HOME

export JRE_HOME

export PATH


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


Run: echo $JAVA_HOME

For result: /usr/lib/jvm/java-8-openjdk-amd64/



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


sudo apt-get install apt-transport-https

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


wget https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -


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


sudo add-apt-repository "deb https://artifacts.elastic.co/packages/6.x/apt stable main"


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


sudo apt update


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


sudo apt install elasticsearch


Getting this error: sudo apt install elasticsearch

Reading package lists... Done

Building dependency tree       

Reading state information... Done

E: Unable to locate package elasticsearch


For solve: 
On terminal: wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo gpg --dearmor -o /usr/share/keyrings/elasticsearch-archive-keyring.gpg

echo "deb [signed-by=/usr/share/keyrings/elasticsearch-archive-keyring.gpg] https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-7.x.list > /dev/null

sudo apt update

sudo apt-get install elasticsearch

sudo systemctl enable elasticsearch

------------------------------------------------

When getting this error:

sudo systemctl enable elasticsearch Synchronizing state of elasticsearch.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable elasticsearch


Then run this command: sudo systemctl is-enabled elasticsearch


---------------------------------------------

sudo systemctl start elasticsearch

Check the status: sudo systemctl status elasticsearch


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


sudo nano /etc/elasticsearch/elasticsearch.yml
is file me must nhi hai change karna, kyu ki default me port 
9200 hota hai and host 127.0.0.1 hota hai


Only for:


Uncomment line


cluster.name: my-elasticsearch


node.name: elasticsearch-1


path.data: /var/lib/elasticsearch

path.logs: /var/log/elasticsearch


http.port: 9200


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


sudo systemctl start elasticsearch


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


Check status:


sudo systemctl status elasticsearch.service


For this resulte


elasticsearch.service - Elasticsearch

   Loaded: loaded (/usr/lib/systemd/system/elasticsearch.service; enabled; vendor preset: enabled)

   Active: active (running) since Thu 2020-11-05 17:48:01 IST; 11s ago

     Docs: https://www.elastic.co

 Main PID: 8632 (java)

    Tasks: 63

   Memory: 1.2G

      CPU: 59.206s

   CGroup: /system.slice/elasticsearch.service

           ├─8632 /usr/share/elasticsearch/jdk/bin/java -Xshare:auto -Des.networkaddress.cache.ttl=60 -Des.networkaddress.cache.negative.ttl=10

           └─8831 /usr/share/elasticsearch/modules/x-pack-ml/platform/linux-x86_64/bin/controller



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


curl -X GET http://127.0.0.1:9200


{

  "name" : "elasticsearch-1",

  "cluster_name" : "my-elasticsearch",

  "cluster_uuid" : "OL-ZPjVBTcG4b9HlEgnOdw",

  "version" : {

    "number" : "7.9.3",

    "build_flavor" : "default",

    "build_type" : "deb",

    "build_hash" : "c4138e51121ef06a6404866cddc601906fe5c868",

    "build_date" : "2020-10-16T10:36:16.141335Z",

    "build_snapshot" : false,

    "lucene_version" : "8.6.2",

    "minimum_wire_compatibility_version" : "6.8.0",

    "minimum_index_compatibility_version" : "6.0.0-beta1"

  },

  "tagline" : "You Know, for Search"

}


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



Link: https://www.youtube.com/watch?v=63nS1Z-pIfI


Tuesday, 19 May 2020

Export csv in rails with other table

Application.rb

require "csv"

========================================================
Controller:

def index
    if params[:q].blank?
      @clients = Client.order("client_id ASC").paginate(page: params[:page])
    else
      @clients = Client.joins(:profile).where(["LOWER(first_name) LIKE ? OR LOWER(last_name) LIKE ?","#{params[:q].downcase}%", "#{params[:q].downcase}%"]).paginate(page: params[:page])
    end
    respond_to do |format|
      format.html { render :index }
      format.js { render :search_users }


      format.csv { send_data @clients.to_csv, filename: "Filename.csv" }

    end
   
  end


======================================================
On model:


def self.to_csv
    CSV.generate(headers: true) do |csv|
      csv << ["Id", "Email", "First Name", "Last Name"]

      all.each do |user|
        row = [user.id, user.email, user.profile.first_name, user.profile.last_name]
        csv << row
      end
    end
  end

Sunday, 10 May 2020

Search other table User Join

if params[:q].blank?
      @admins = Admin.paginate(page: params[:page])
    else
      @admins = Admin.joins(:profile).where(["LOWER(first_name) LIKE ? OR LOWER(last_name) LIKE ?","#{params[:q].downcase}%", "#{params[:q].downcase}%"]).paginate(page: params[:page])

      # @admins = Admin.joins(:profile).where(["LOWER(first_name) LIKE ?","#{params[:q].downcase}%"]).paginate(page: params[:page])
    end
    respond_to do |format|
      format.html { render :index }
      format.js { render :search_users }
    end




def agent_search
    if params[:q].present?
      # @agent_name = agents.joins(:profile).where("profiles.first_name= ? ", params[:q])
      @agent_name = agents.joins(:profile).where(["LOWER(first_name) LIKE ?","#{params[:q].split("=").last.downcase}%"])

      # @agents_skill = agents.joins(:skills).where('skills.name IN(:search)', {search: params[:q]})
      @agents_skill = agents.joins(:skills).where(["LOWER(name) LIKE ?","#{params[:q].split("=").last.downcase}%"])

      @agents = (@agent_name + @agents_skill).uniq
    else
      @agents = agents
    end 
      respond_to do |format|
        format.js { render :agent_search }
      end
  end

Thursday, 9 January 2020

Authentication on jwt

Okay now we’re ready to generate rails project, type this on your terminal
$ rails new rails-jwt --api
Add Json Web Token (JWT) and bcrypt gem
  • JWT : Token encoder / decoder with expiration time
  • bcrypt : Password encryption
# Use Json Web Token (JWT) for token based authenticationgem 'jwt'
# Use ActiveModel has_secure_passwordgem 'bcrypt', '~> 3.1.7'
and then install dependencies by typing this on your terminal
$ bundle install
# config/routes.rbRails.application.routes.draw resources :users, param: :_username
  post '/auth/login', to: 'authentication#login'
  get '/*a', to: 'application#not_found'
======================================================================
Add new file: app/lib/json_web_token.rb

class JsonWebToken
SECRET_KEY = Rails.application.secrets.secret_key_base. to_s
def self.encode(payload, exp = 24.hours.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, SECRET_KEY)
end
def self.decode(token)
decoded = JWT.decode(token, SECRET_KEY)[0]
HashWithIndifferentAccess.new decoded
end
end
=======================================================================
For Application controller:

class ApplicationController < ActionController::API
def not_found
    render json: { error: 'not_found' }
  end

  def authorize_request
    header = request.headers['Token']
    header = header.split(' ').last if header
    begin
      @decoded = JsonWebToken.decode(header)
      @current_user = User.find(@decoded[:user_id])
    rescue ActiveRecord::RecordNotFound => e
      render json: { errors: e.message }, status: :unauthorized
    rescue JWT::DecodeError => e
      render json: { errors: e.message }, status: :unauthorized
    end
  end
end
=====================================================================
Create user model
$ rails g model user name:string username:string email:string password_digest:string
===================================================================
Add user.rb:

class User < ApplicationRecord
has_secure_password
mount_uploader :avatar, AvatarUploader
validates :email, presence: true, uniqueness: true
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
validates :username, presence: true, uniqueness: true
validates :password,
length: { minimum: 6 },
if: -> { new_record? || !password.nil? }
end
========================================================================
$ rails g controller users

class UsersController < ApplicationController
  before_action :authorize_request, except: :create
  before_action :find_user, except: %i[create index]

  # GET /users
  def index
    @users = User.all
    render json: @users, status: :ok
  end

  # GET /users/{username}
  def show
    render json: @user, status: :ok
  end

  # POST /users
  def create
    @user = User.new(user_params)
    if @user.save
      render json: @user, status: :created
    else
      render json: { errors: @user.errors.full_messages },
             status: :unprocessable_entity
    end
  end

  # PUT /users/{username}
  def update
    unless @user.update(user_params)
      render json: { errors: @user.errors.full_messages },
             status: :unprocessable_entity
    end
  end

  # DELETE /users/{username}
  def destroy
    @user.destroy
  end

  private

  def find_user
    @user = User.find_by_username!(params[:_username])
    rescue ActiveRecord::RecordNotFound
      render json: { errors: 'User not found' }, status: :not_found
  end

  def user_params
    params.permit(
      :avatar, :name, :username, :email, :password, :password_confirmation
    )
  end
end
======================================================================

Create authentication controller
$ rails g controller authentication

before_action :authorize_request, except: :login
# POST /auth/login
def login
@user = User.find_by_email(params[:email])
if @user&.authenticate(params[:password])
token = JsonWebToken.encode(user_id: @user.id)
time = Time.now + 24.hours.to_i
render json: { token: token, exp: time.strftime("%m-%d-%Y %H:%M"),
username: @user.username }, status: :ok
else
render json: { error: 'unauthorized' }, status: :unauthorized
end
end
private
def login_params
params.permit(:email, :password)
end

=======================================================================
Add a app/config/application.rb

load_path_strategy = Rails.env.production? ? :eager_load_paths : :autoload_paths
    config.public_send(load_path_strategy) << Rails.root.join('lib')