在 Rails 中通过设计重定向后如何登录用户?

How to sign in the user after redirect through devise in Rails?

我想先重定向用户,然后以编程方式让用户登录。

我有一个多租户应用程序,当用户尝试在根域登录时,我的应用程序不仅应该将用户重定向到他的子域,还应该让用户登录。

到目前为止,我正在尝试通过以下代码完成此操作:

# In sessions#create ( Root )
redirect_to "http://#{account.subdomain}.localhost.com:3000/users/sign_in"
Apartment::Tenant.switch(account.subdomain)
sign_in(:user, account.owner) # Basically, owner is the user here.

当我 运行 代码时,它成功重定向到子域,但没有让用户登录。

我收到以下错误:

Completed 302 Found in 93ms (ActiveRecord: 39.7ms)

此外,当我执行 Apartment::Tenant.switch(account.subdomain) 时它不会切换 schema,因为在 运行ning Apartment::Tenant.switch(account.subdomain) 之后当我 运行 user = User.first,在日志中可以看到查询是:

  User Load (0.9ms)  SELECT  "public"."users".* FROM "public"."users"   ORDER BY "public"."users"."id" ASC LIMIT 1

这里的public对应的是根域的schema,不是子域的schema

经过大量搜索后的(唯一)解决方案是修改 config/initializers/session_store.rb 中的以下行:

Rails.application.config.session_store :cookie_store, key: '_examples_session', :domain => :all

好吧,这无论如何都不是完美的解决方案,但它可以完成工作。 确切地 所做的实际上是通过所有子域维护一个会话。

例如,如果我在 bugs.example.com 登录,我的会话也会在 attendance.example.com 工作并且喜欢这些子域。

我还写了一个 before_action 检查用户尝试登录的子域是否属于用户,如果是,我让用户登录,如果不是,我重定向用户到他所属的子域,如果用户属于 none,我将他重定向到根 url。同样,通过一个 session,用户将能够登录那里的每个子域,因此 这种 检查非常重要。