rails app create - from scratch :: new

 1. create new rails application in postgres database :: $rails new hrmsfinance -d postgresql

 2. Add password settings in database.yml -- 

..............................................................................................

default: &default

  adapter: postgresql

  encoding: unicode

  # For details on connection pooling, see Rails configuration guide

  # https://guides.rubyonrails.org/configuring.html#database-pooling

  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

  username: postgres

  password: postgres

development:

  <<: *default

  database: hrmsfinance_development

test:
  <<: *default
  database: hrmsfinance_test

production:
  <<: *default
  database: hrmsfinance_production
  username: hrmsfinance
  password: postgres

$ rails db:create
..............................................................................................

3. Add jwt ::

1. in routes.rb --
 
resources :users, param: :_username
post '/auth/login', to: 'authentication#login'
get '/*a', to: 'application#not_found'

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

3. application_controller.rb ::

  def not_found
    render json: { error: 'not_found' }
  end

  def authorize_request
    header = request.headers['Authorization']
    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

4. $  rails g model user name:string username:string email:string password_digest:string

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

6. create user controller ::
$   rails g controller users

7. Implement in authentication_controller ::

class AuthenticationController < ApplicationController
  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
end

8. 



Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5