I'm using the devise-jwt
gem for authenticating my Rails backend and React frontend. Everything was working perfectly with this until I created a second user and tried logging them in. Even though the backend is processing the correct email and password, it returns the wrong user in the response. Any ideas here?
class Users::SessionsController < Devise::SessionsController
include RackSessionFix
respond_to :json
private
def respond_with(resource, _opts = {})
render json: {
status: {code: 200, message: 'Logged in sucessfully.'},
data: UserSerializer.new(resource).serializable_hash[:data][:attributes]
}, status: :ok
end
def respond_to_on_destroy
if current_user
render json: {
status: 200,
message: "logged out successfully"
}, status: :ok
else
render json: {
status: 401,
message: "Couldn't find an active session."
}, status: :unauthorized
end
end
end
class CurrentUserController < ApplicationController
before_action :authenticate_user!
def index
render json: UserSerializer.new(current_user).serializable_hash[:data][:attributes], status: :ok
end
end
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
include Devise::JWT::RevocationStrategies::JTIMatcher
devise :database_authenticatable, :validatable,
:jwt_authenticatable, :timeoutable, jwt_revocation_strategy: self
end
ActiveRecord::Schema[7.0].define(version: 2023_02_17_165020) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "foods", force: :cascade do |t|
t.string "name"
t.float "price"
t.string "category"
t.text "add_ons"
t.text "details"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
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 "jti", null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["jti"], name: "index_users_on_jti", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
end
There's much more to this file, but the most important:
config.jwt do |jwt|
jwt.secret = Rails.application.credentials.fetch(:secret_key_base)
jwt.dispatch_requests = [
['POST', %r{^/login$}]
]
jwt.revocation_requests = [
['DELETE', %r{^/logout$}]
]
jwt.expiration_time = 15.seconds
end