REST API:使用 cookie 和会话的自定义方法 [英] REST API: Custom method using cookies and sessions
问题描述
我正在尝试使用 REST API,因此我想从 RoR APP1 中获取 APP2 中的 @current_user.
I am trying to use REST API, so I want get a @current_user in APP2 from a RoR APP1.
在 APP1/config/routes.rb 中,我有这个代码:
In APP1/config/routes.rb I have this code:
resources :users do
collection do
get 'current'
end
end
在 APP1/controllers/application_controller.rb 中,我有这个代码:
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
在 APP1/controllers/users_controller.rb 中,我有这个代码:
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
在 APP2/models/user.rb 我有这个代码:
In APP2/models/user.rb I have this code:
class User < ActiveResource::Base
self.site = "http://APP1"
end
在 APP2/controllers/application_controller.rb 我有这个代码:
In APP2/controllers/application_controller.rb I have this code:
before_filter :current_profile
def current_profile
@current_profile = User.get(:current)
end
现在,如果我在 APP1 中登录我的 User2 并转到 http://APP1/users/current.xml URL我得到了正确的@current_user(User2 对象),但是如果我去 http://APP2/,即使我有 'before_filter's,@current_profile 将始终是 default_current_user(User.find_by_id(1) 对象) 而不是 User2.
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.
似乎不关心来自 APP1/controllers/application_controller.rb 的这段代码:
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_user_id])
end
怎么了?
已编辑
也许我们可以通过APP1/config/routes.rb参数(?!)来解决这个问题:
Maybe we can solve this problem through APP1/config/routes.rb parameters (?!):
示例:在APP1/config/routes.rb
Example: in APP1/config/routes.rb
resources :users do
collection do
get 'current', :current_user => @current_user # ?!
end
end
或类似的东西.
推荐答案
当您向另一个网站发出请求时,当前用户的 cookie 无法访问.请求是从服务器到服务器的,因此应用程序对请求它的用户一无所知.我认为一个解决方案是自己发送参数并检查这些参数.
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.
这篇关于REST API:使用 cookie 和会话的自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!