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

Cannot manually generate an access token and refresh token #31

Closed DerekCrosson closed 10 months ago

DerekCrosson commented 10 months ago

I am trying to create a token for my users factory to use in rspec tests. This is the factory code:

FactoryBot.define do
  factory :user do
    email { 'user@example.com' }
    password { 'password1234' }

    trait :with_token do
      after(:create) do |user|
        Devise::Api::Token.create!(resource_owner: user)
      end
    end
  end
end

This is the error which is returned:

  1) V1::Organisations API behaves like API Resource GET #index returns a list of resources
     Failure/Error: Devise::Api::Token.create!(resource_owner: user)

     ActiveRecord::RecordInvalid:
       Validation failed: Access token can't be blank, Refresh token can't be blank, Expires in can't be blank, Expires in is not a number
     Shared Example Group: "API Resource" called from ./spec/requests/v1/organisations_spec.rb:8
     # ./spec/factories/users.rb:9:in `block (4 levels) in <main>'
     # ./spec/support/api_resource_shared_examples.rb:15:in `block (2 levels) in <main>'
     # ./spec/support/api_resource_shared_examples.rb:19:in `block (3 levels) in <main>'

I get the same error when trying to generate a token for a user in the rails console like this:

u = User.first

Devise::Api::Token.create!(resource_owner: u)

Am I creating the token incorrectly?

EDIT:

I am now creating the token like this:

create_token_service = Devise::Api::TokensService::Create.new(resource_owner: user, previous_refresh_token: nil)
create_token_service.call

This code successfully creates the token but Devise::Api::Token.where(resource_owner: user).first does not return this newly created token. Instead it returns an old token.

Another edit: Devise::Api::Token.where(resource_owner: user).reload.last loads the new token.