nejdetkadir / devise-api

The devise-api gem is a convenient way to add authentication to your Ruby on Rails application using the devise gem. It provides support for access tokens and refresh tokens, which allow you to authenticate API requests and keep the user's session active for a longer period of time on the client side
MIT License
152 stars 22 forks source link

resource_owner_id is null on login #21

Closed SaimonL closed 1 year ago

SaimonL commented 1 year ago

What

This error occurs when you try to login

{
    "status": 500,
    "error": "Internal Server Error",
    "exception": "#<ActiveRecord::NotNullViolation:\"PG::NotNullViolation: ERROR:  null value in column \\\"resource_owner_id\\\" of relation \\\"devise_api_tokens\\\" violates not-null constraint\\nDETAIL:  Failing row contains (1, User, null, aVVZU8x26XqyetX4LWXSc6ovS5Ri2P-27yzPDyb_PwAvw7UUSzkHboLMxEyJ, SjVyHn43yomfgMbqQGHmMFAHmg8sV4xCCymTFcB2kX4HA2dn-ffzDux5XM5f, 3600, null, null, 2023-05-29 13:02:32.346515, 2023-05-29 13:02:32.346515).\\n\">",

Why

Because the resource_owner_id is null and database migration has null: false

t.belongs_to :resource_owner, null: false, type: :uuid, polymorphic: true, index: true

Additional Info

This is what happens if I remove the null: false from the migration

[
  {
    "id": 1,
    "resource_owner_type": "User",
    "resource_owner_id": null,
    "access_token": "JbxfzM9-NVEx1SSiz_Y616cQtA36hMHQsqe_yxSthqRQkzzZbycZdx3hF8tZ",
    "refresh_token": "xuj_jozE1gA4py886MVSp83-dapP4g3VhzyusVyCyra9v-ecsi5YGSBDhPzM",
    "expires_in": 3600,
    "revoked_at": null,
    "previous_refresh_token": null,
    "created_at": "2023-05-29 13:08:16.431017",
    "updated_at": "2023-05-29 13:08:16.431017"
  }
]

Need to know what in Rails 7 resource_owner_id is coming as null. The Users table is "users" the standard table.

route.rb

  devise_for :users
  resources :users

User Model

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :confirmable, :lockable, :timeoutable, :trackable,
         :api

The API response I get after login

{
    "token": "JbxfzM9-NVEx1SSiz_Y616cQtA36hMHQsqe_yxSthqRQkzzZbycZdx3hF8tZ",
    "refresh_token": "xuj_jozE1gA4py886MVSp83-dapP4g3VhzyusVyCyra9v-ecsi5YGSBDhPzM",
    "expires_in": 3600,
    "token_type": "Bearer",
    "resource_owner": {
        "id": 1,
        "email": "s@s.com",
        "created_at": "2023-05-29T13:08:10.694Z",
        "updated_at": "2023-05-29T13:08:16.449Z"
    }
}

However in the database "resource_owner_id" is null (if I remove not null in the migration)

nejdetkadir commented 1 year ago

please check the #11