开发者

REST API: Custom method using cookies and sessions

开发者 https://www.devze.com 2023-02-01 19:27 出处:网络
I am trying to use REST API, so I want get a @current_user in APP2 from a RoR APP1. In APP1/config/routes.rb I have this code:

I am trying to use REST API, so I want get a @current_user in APP2 from a RoR APP1.

In APP1/config/routes.rb I have this code:

  resources :users do
    collection do
      get 'current'
    end
  end

In APP1/controllers/application_controller.rb I have this code:

 before_filter :current_user

 def current_user
    if cookies[:remember_me]
      current_user = user_from_cookie
    else
      current_user = User.find_by_id(session[:current_user_id])
    end
    unless !current_user.nil?
      default_current_user = User.find_by_id(1)
    end
    return @current_user = current_user.nil? ? default_current_user : current_user
  end

In APP1/controllers/users_controller.rb I have this code:

  def index
      ...
  end

  def show
      ...
  end

  ...

  def current
    respond_to do |format|
      format.xml  { render :xml => @current_user }
    end
  end

In APP2/models/user.rb I have this code:

class User < ActiveResource::Base
  self.site = "http://APP1"
end

In APP2/controllers/application_controller.rb I have this code:

  before_filter :current_profile

  def current_profile
    @current_profile = User.get(:current)
  end

Now, if I Sign in my User2 in APP1 and I go to http://APP1/users/current.xml URL I get the correct @current_user (User2 object), but if I go to http://APP2/, even though I have 'before_filter's, the @current_profile will be always the default_current_user (User.find_by_id(1) object) instead of User2.

It seems do not care this code from APP1/controllers/application_controller.rb:

if cookies[:remember_me]
  current_user = user_from_cookie
else
  current_user = User.find_by_id(session[:current_u开发者_运维技巧ser_id])
end

What is wrong?

EDITED

Maybe we can solve this problem through APP1/config/routes.rb parameters (?!):

Example: in APP1/config/routes.rb

  resources :users do
    collection do
      get 'current', :current_user => @current_user # ?!
    end
  end

or something like that.


When you do a request to another website, the cookies of the current user are not accessible. The request is from server to server, so the application knows nothing about the user requesting it. I think a solution would be to send the parameters yourself and check for those.


If APP2 requests something from the APP1 via ActiveResource it is not the same as the APP1 logged in user requesting it. Users cookies are not 'forwarded'. Somebody correct me if this is nonsense. :)

Authentication part here http://api.rubyonrails.org/classes/ActiveResource/Base.html has a couple of valid options listed.

0

精彩评论

暂无评论...
验证码 换一张
取 消