简体   繁体   中英

Rails 5 set current_user from external API

I use temporarily Rails as frontend app to communicate with an API.

After the authentication, I set the user_id in a cookie. I use the her gem to call the User from the API and save it into an instance variable.

The issue is that I do this request on every page I and would like to do it once. It's like @current_user is reset after each page.

def current_user
  #User.find -> Her model
  @current_user ||= User.find(cookies.signed[:user_id]) if cookies.signed[:user_id]
end

There no clear solution because your user coming from API. You can try to do something like that:

#remember user attributes without references
session['user'] = @current_user.attributes #remember
@user = OpenStruct(session['user']) #load, allow call @user.name etc, but not @user.posts

#use class variable
class User
  include Her::Model
  @@tmp = {}

  def remember
    @@tmp[id] = self
    #call job etc to delete user from tmp to prevent something that reminds "memory leak" 
  end

  def self.local_find(id)
    @@tmp[id]
  end
end

def current_user
  @current_user ||= User.local_find(cookies.signed[:user_id]) || 
    User.find(cookies.signed[:user_id]) if cookies.signed[:user_id]
end

The main reason not to store(remember) objects in the session(long-term variable) is that if the object structure changes, you will get an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM