I'm working on a Spree Commerce application and attempting to create a custom API controller/page that requires authentication and I want to use the spree_devise_auth gem. However, I'm encountering issues with authentication despite providing valid authentication tokens. Here's a simplified version of my setup:
I have a custom controller named Api::V2::CustomController located in app/controllers/api/v2/custom_controller.rb:
class Api::V2::CustomController < Spree::Api::V2::BaseController
before_action :authenticate_spree_user!
def index
render json: { message: 'Custom Controller Working!' }
end
end
I've set up a route for this controller in config/routes.rb:
Rails.application.routes.draw do
namespace :api do
namespace :v2 do
get '/custom', to: 'custom#index'
end
end
end
When I attempt to access the /api/v2/custom endpoint with a valid authentication token, I receive the following response:
{
"error": "You need to sign in or sign up before continuing."
}
But actually the most intriguing aspect of this issue is that while I was typping this question I tryied to make the request again and got:
{
"error": "The access token expired"
}
So now I'm very confused xD because its checking the token and all that but it just doesn't authenticate!
Here's what I've tried so far to troubleshoot the issue:
Double-checked the authentication token to ensure it's correct. Verified that other "default" endpoints from spree, such as /api/v2/storefront/account, work correctly with the same authentication token.
I'm not sure what else to try to resolve this issue :/ Any ideas on what am I doing wrong?
Nevermind! I realise that the helper_method
spree_current_useris available through out the application. When theaccess_tokenis correct, the helper returns the user object and if not returnsnull. So I can actually just make a simplebefore_actione.g.:check_if_current_userand authenticate it.