How to access current_user with devise-token_authenticatable gem?

可紊 提交于 2021-02-11 15:26:26

问题


I’m working on a small project that is using devise and devise-token_authenticatable in a Rails/GraphQL/Apollo/React setup. Project is setup using webpacker, so the front and back ends are both served from the same domain. Sign-in, register, log-out are all handle by the front end (React). I also need to point out this is not an API only app.

It seems, server is not setting the current_user or the proper cookie and I’m getting a network error.

Heroku logs shows the following error:

NoMethodError (undefined method `authentication_token' for #<User:0x000055ca6c0e4c50>)

Is that mean it’s trying ‘authentication_token’ method on a nil class?

At the same time it’s showing this error in the console:

Network error: Unexpected token < in JSON at position 0 (I have no idea what this is)

In my login component’s sign-in mutation, I’m storing the authentication_token of the user in local storage after a successful login and in my Apollo setup I’m retrieving it from storage and attaching it to each request. But Chrome dev tool’s network tab shows I’m not getting the cookie set by devise after a signin in the response header. I’m pretty new to all of this so not sure this is the problem or something else. PS: I’m not using Devise sessions since sign-in is handle in the from end. I have devise_for: users, skip: :sessions in my routes.

Code snippets:

Apollo Provide

Component UserInfo

SignIn mutation

Any assistance is greatly appreciated. Thank you in advance for your help.

UPDATE: issue was fixed: (also see my answer below for additional info)

Issue was fixed by adding current_user private method in application_controller.rb.

Here's the code...

def current_user
 token = request.headers["Authorization"].to_s
 User.find_for_database_authentication(authentication_token: token)
end

回答1:


Marko Kacanski was right I should have elaborate on my findings & how I fixed it. :-(

I was wrong to assume that the current_user is automatically sent by the gem devise-token_authenticatable when it detects a authentication_token in the header. At least the way I have setup my project, I wasn't getting the current_user as expected, instead I get a nil object.

So... I created a current_user private method in application_controller.rb and, it fixed the issue.

Here's the code...

def current_user
 token = request.headers["Authorization"].to_s
 User.find_for_database_authentication(authentication_token: token)
end



回答2:


Fixed the issue. It had nothing to do with GraphQl/Apollo code. Thanks



来源:https://stackoverflow.com/questions/59057895/how-to-access-current-user-with-devise-token-authenticatable-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!