2011-01-20 63 views
16

我有一個基本的設計認證的應用程序。登錄後,我想查找用戶帳戶(用戶belongs_to帳戶,帳戶has_many用戶),並將其存儲在會話中,以便它可用,如@current_user成功登錄Devise後可以執行自定義操作嗎?

什麼是這種存儲會話的軌道方式? 有沒有一個鉤子,我可以使用Devise在成功登錄後執行代碼?

回答

16

編輯:請認爲這曾經是一個很好的解決方案,但可能有更好的方法來處理這個問題。我只是把它留在這裏給人們另一種選擇,並保存歷史,請不要冷落。

是的,你可以做到這一點。我想看的第一個資源是http://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in。另外,請查看How to redirect to a specific page on successful sign up using rails devise gem?的一些想法。

你可以這樣做:

def after_sign_in_path_for(resource_or_scope) 
    session[:my_account] = current_user.account 
    profile_url 
end 

您可以在您的ApplicationController或自定義RegistrationsController此方法。

+11

似乎很哈克 – 2013-07-17 01:24:02

+2

[這](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable#after_database_authentication-instance_method)似乎少哈克的方式。 – Anjan 2014-12-31 09:47:53

+0

這在2011年得到了回答,並且是當時被接受的解決方案。感謝您對另一種方法的更新。 – 2015-01-09 17:26:34

28

實際上,在Devise中結合使用Omniauth和數據庫登錄模塊時,接受的答案無法正常工作。

了在設計中動作每全成符號(不考慮用戶認證信道)之後,執行的本機鉤是warden.set_user(由色器件稱爲sign_in助手:http://www.rubydoc.info/github/plataformatec/devise/Devise/Controllers/SignInOut#sign_in-instance_method)。

爲了在全成用戶登錄之後執行自定義動作(根據看守文檔:https://github.com/hassox/warden/wiki/Callbacks),將此放入初始化(在配置例如after_sign_in.rb /初始化

Warden::Manager.after_set_user except: :fetch do |user, auth, opts| 
    #your custom code 
end 

更新2015-04-30:感謝@seanlinsley建議(請參閱下面的評論),我已更正答案,其中包括,但以下情況除外::獲取以便僅在用戶通過身份驗證時觸發回調,而不是每次都是組。

2

我通過重寫會話控制器的create方法類似以下

class Admin::SessionsController < Devise::SessionsController 

    def create 
    super 
    # here goes my code 
    # my settings, etc 
    # do something with current_admin.fullname, for example 
    end 
end 

換句話說,如果認證成功(通過調用super),那麼我執行我的設置解決了這個問題。

2

我使用rails 5和設計4.2。1,我的解決方案是用戶模型超越控制色器件功能:

def after_database_authentication 
    # here's the custom code 
end 

和用戶模型將是這樣的:

class User < ApplicationRecord 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, 
     :timeoutable, :lockable 
    def after_database_authentication 
     # here's the custom code 
    end 
end 

它只是驗證後調用, 我從這個devise documentation閱讀,希望能幫助

相關問題