getting error when signing-in after a sign_out: rails 7 devise user authentication for both api and web

83 Views Asked by At

I wanted to build a rails-7 app which will work for both API and web. It works fine for web and for API I've used devise-jwt gem. It works perfectly for sign_up, sign_out and sign_in also but after a user signs out once, sign_in doesn't work. It gives 401 unauthorized error

"error": "You need to sign in or sign up before continuing."

when I'm trying to make a request POST in URL http://localhost:3000/api/v1/users/sign_in using Postman.

Here is the code for session controller:

class Api::V1::Users::SessionsController < Devise::SessionsController
  respond_to :json
  before_action :sign_in_params
  skip_before_action :verify_authenticity_token

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

  private 

  def respond_with(resource, _opts = {})
    puts "I am here============================="
    render json: {
      status: { code: 200, message: "User signed in successfully",
        data: UserSerializer.new(resource).serializable_hash[:data][:attributes] }
    }
  end

  def respond_to_on_destroy
    jwt_payload = JWT.decode(request.headers['Authorization'].split(' ')[1], Rails.application.credentials.fetch(:secret_key_base)).first
    current_user = User.find(jwt_payload['sub'])
    if current_user 
      render json: {
        status: 200,
        message: "Logged out successfully"
      }, status: :ok
    else
      render json: { 
        status: 401,
        message: "User has no active session."
      }, status: :unauthorized
    end

  end
end

In routes I have added:

#FOR API 
  namespace :api do
    namespace :v1, defaults: { format: :json } do
      get '/chat_rooms', to: 'chat_rooms#index'
      get '/current_user', to: 'current_user#index'
      devise_for :users, controllers: {
        sessions: 'api/v1/users/sessions',
        registrations: 'api/v1/users/registrations'
      }
    end
  end

I've tried to find a solution but haven't got any proper resource to fix my problem. All I get is for API-only application. why I'm getting this error?

Also I've found out that 401 unauthorized error occurs before it enters into respond_with method in session controller.

0

There are 0 best solutions below