Wednesday, 23 October 2019

Configuring Git

#### If you want to use SQLite (not recommended)
rails new myapp
 
#### If you want to use MySQL
rails new myapp -d mysql
 
#### If you want to use Postgres
# Note that this will expect a postgres user with the same username
# as your app, you may need to edit config/database.yml to match the
# user you created earlier
rails new myapp -d postgresql  
 
# Move into the application directory
cd myapp

# If you setup MySQL or Postgres with a username/password, modify the
# config/database.yml file to contain the username/password that you specified

# Create the database
rake db:create

rails server 

Wednesday, 16 October 2019

Mobile Rails API with Devise

Mobile Rails API with Devise

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

1. rails g migration AddAuthenticationtokenToUsers authentication_token:string

2. rails generate controller Api/V1/Api

3. create a user model (User.rb)

       class User < ApplicationRecord
         devise :database_authenticatable, :registerable,
               :recoverable, :rememberable, :validatable

        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

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. ApplicationController

     class ApplicationController < ActionController::Base
        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

    end

6. routes.rb

       namespace :api do
        namespace :v1 do
          devise_scope :user do
            post "/sign_in", :to => 'sessions#create'
            post "/sign_up", :to => 'registrations#create'
            get "/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

Flow of registration controller :=>
Sign Up

1. routes.rb
       post "/sign_up", :to => 'registrations#create'
       get "/users", :to => 'registrations#index'

2. registrations_controller.rb

class Api::V1::RegistrationsController < Api::V1::ApiController
 
   /*--------------------------------------  Create   -------------------------------------------------*/
        def new
          user = User.new
        end

        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
  /*--------------------------------------  Index   -------------------------------------------------*/
       def index
         user = User.all
        if user.present?
          return render json: {status: 200, data: {user: user}, :message =>"All
             Users"}
        else
          return render json: {status: 401, data: {user: nil, errors: user.errors},
             :message =>" Rollback"}
        end
      end
  /*--------------------------------------  Update   -------------------------------------------------*/
     first select which user update so please select user token 
        def update
           user =  current_user
            if params[:user][:email].present?
              user.email = params[:user][:email]
            end
            if params[:user][:password].present?
             user.password = params[:user][:password]
            end
           if user.save
              return render json: {status: 200, data: {user: user}, :message
                   =>"User Profile Successfully Updated"}
          end
       end  
/*--------------------------------------  Destroy   -------------------------------------------------*/
     def destroy
       
     end

end

3. sessions_controller.rb

    class Api::V1::SessionsController < Api::V1::ApiController
       
            def create
              email = params[:user][:email]
              password = params[:user][:password]
             @user = User.where(email: email).first
                 return render json: {status: 200, data: {user: @user}, message:  
                    "Login Successful"}
           end

           def destroy
           end








    end
 

      




Tuesday, 15 October 2019

Social login facebook,twitter ..

Social Login fb/twitter/linkedin

1. Gemfile:

    gem "oauth"
    gem "oauth2"
    gem 'omniauth-oauth2'
    gem 'omniauth-facebook'
    gem 'omniauth-twitter'
    gem 'omniauth-google-oauth2'
    gem 'omniauth-linkedin'
    gem 'omniauth-github'
    gem 'omniauth-pinterest'

2. Model generate:

   rails g model authentication provider:string uid:string user_id:integer  
   token:text token_expired_at:datetime

3. app/model/authentication.rb:
class Authentication < ActiveRecord::Base
    
     belongs_to :user
     # validates :provider, :uid, :presence => true
     def self.from_omniauth(auth)
    if auth[:provider] == "twitter"
        email =  auth[:info][:nickname] + '@' + 'gmail.com'
    end

    if auth[:provider] == "linkedin"
        email =  auth.extra.raw_info.requestId.to_s+"@gmail.com"
    else
        email = auth[:email].present? ? auth[:email] :  auth[:info][:email]
    end

    if auth[:provider] == "instagram"
        email =  auth[:info][:nickname] + '@' + 'gmail.com'   
    end
   
            authenticate = where(provider: auth[:provider], :uid=>auth[:uid]).first_or_initialize
    if authenticate.user
         authenticate.provider = auth[:provider]
        authenticate.uid =auth[:uid]
    else
        if auth['provider'].downcase == "facebook"
           email = auth[:email].present? ? auth[:email] :  auth[:uid].to_s+"@facebook.com"
        elsif auth['provider'].downcase == "google"
            email = auth[:email].present? ? auth[:email] :  auth[:uid].to_s+"@google.com"
        end
        user = User.find_or_initialize_by(:email => email)
        authenticate.provider = auth[:provider]
        authenticate.uid = auth[:uid]
        user.email = email
        user.save(validate: false)
        authenticate.user_id = user.id
       end
            authenticate.save
            authenticate.user
     end
    
end

4. User.rb
      # before_create :confirmation_token
       has_many :authentications, dependent: :destroy
       validates :email, :uniqueness => {:allow_blank => true}

5. Config/initializers/omniauth.rb
      Rails.application.config.middleware.use OmniAuth::Builder do

         provider :facebook, '433592010474964',   
             '547da79dec038a932f4c846986398f63'
         provider :linkedin, '81q662zzjusm67', 'xZyEHlGAaZI8Gm9q'
         provider :google_oauth2,      
           244615150400-05thnta81fhg631up71t8v7e167i8pta.apps.googleusercontent.com',   'XW9LFZYGtLjruVh9kOpmCaRY'
        provider :twitter, 'y6kILe3VwuGpaFIIfPXdnv8pw',    
            'Gb76xJS6ZvTrzzxp0jNFLnZG2nNhNaaNPfx5FAWLrL5y11e14D'

     end

6. routes.rb
       match '/auth/:provider/callback', :to => 'sessions#create', via: [:get, :post]
       match '/auth/failure', :to => 'sessions#failure', via: [:get, :post]

7. app/controller/sessions_controller.rb
      
  class SessionsController < ApplicationController

     # skip_before_action :authenticate_user!
  def create
    user = Authentication.from_omniauth(request.env["omniauth.auth"])
    if user
      flash[:notice] = "Authentication successful."
      sign_in(user)
      sign_in_and_redirect(user)
    else
        flash[:notice] = "Authentication Failed."
    end
  end
 
end

8. Add links
       
<li><a href="/auth/facebook" class="icoFacebook ib" title="Facebook"><i class="fa fa-facebook"></i></a></li>
              <li><a href="/auth/twitter" class="icoTwitter ib" title="Twitter"><i class="fa fa-twitter"></i></a></li>
              <li><a href="/auth/google_oauth2" class="icoGoogle ib" title="Google +"><i class="fa fa-google-plus"></i></a></li>
              <li><a href="/auth/linkedin" class="icoLinkedin ib" title="Linkedin"><i class="fa fa-linkedin"></i></a></li>




Start server in https mode for facebook login 
  Step 1:- Gemfile  
         group :development do
            gem 'thin'
        end
Step 2: bundle install
Step 3: Start server ( thin start --ssl )
Step 4: https://localhost:3000

Thursday, 10 October 2019

ssh key add gen

How to find ssh key of any System (PC)

1.  cat ~/.ssh/  
     output:-   id_rsa       id_rsa.pub   known_hosts  system ssh/
2.  cat ~/.ssh/id_rsa.pub
     
output:-  ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCeD9RuCKA9ZvJMSgTTi29iHJk0ZDoO6UKvT8XsmNdeq+FtW6NW1gdfRDAw+nfhWyTwxKpATbR5OrsvrY2JmqWAOfOeEwOZf7LMVta9pxakiO80Jt+EUAs1SGRZr8BA8bvP5cX617598UJZG2j+uenk36cBUhcMWks6JYGP5EK//XvsN0S5PW0lD2C0S1I3Cfe9DSEiUhCU4COgOHMYzKOhgyhNDLzHbAaf6TlGCls/gIqat4E2au6AQsnl/IX2vY/KqgWLdQpHkjwAUgXuIH+KVAW3ye2s3xPNGwfWWgxd30nhrLFLdK28T5LEUz81MRLc23sej9+prG9ZLpBpMg5RqJrLuZocPkUWsctMqVdzQipdMPZu1qdWfTQFwjJO8ARyP3SJdt7DuTTX3IscaPnut8oUXx16yFoOLQmq2gGuu63+niB5rv/0bcTQoNhYCCUGboOMp5AwKjTcJDT4J/wrPXarheH5dzXk6X5x8C2IVGl2RScyf8KQijL28tj/awc4wgB671VbQk3GvUyzteTjcXKzfrMKRn0FUCCrdEGVU2Dv3SqOkB7lcTGYOQP7gLUc8uBPenFq76nqQJzhXdrz+CLS+SXveDZEiY5XU0GAXFXrvMNQ5hmai5jver8hBXeztcNrdOOYLjAqKaKBKHMe9Q4uRCil2Zkr62DcyInZgQ== shikha@bittern.co

3. set git config username and email
     
     git config user.name "Arvind Kushwah"
     git config user.email "arvindkushwah9@gmail.com"
4. Add remote origin:-   
    git remote add origin git@bitbucket.org:arvindkushwah9/jcss.org.sg.git
    git remote add origin2 https://arvindkushwah9@bitbucket.org   
    /arvindkushwah9/jcss.org.sg.git


5.  Generate ssh key cmd:=>  ssh-keygen
6.  Add ssh key on my system:=> ssh-add



 

Wednesday, 9 October 2019

How to install mysql in ubuntu 18.04 and Import mysql database

How to install mysql in ubuntu 18.04

1.  sudo apt-get install mysql-server mysql-client libmysqlclient-dev
2.  sudo service mysql status
3.  mysql -u root -p
4.  sudo mysql -u root -p
5.  uninstall plugin validate_password;
6.  ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';
7.  ALTER USER 'root'@'localhost' IDENTIFIED WITH 
      mysql_native_password  BY 'root';
8.  SELECT user,authentication_string,plugin,host FROM mysql.user;
9.   ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
      BY 'password';
10.  ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
       BY 'root';

  Import database:-  (mysql -u username -p database_name < file.sql)

  Common Git Commands   Take clone of a repository git clone <remote-repository-url> ex: git clone  https://github.com/agricor/RegTech...