0

私は次のことを使用deviseして実行しようとしました:

ユーザーがサインイン/アップするとき、私は彼のrole_idで彼をリダイレクトしたいと思います(一部のユーザーには1のIDを、他のユーザーには2のIDを許可します)。

彼の role_id が 1 の場合は にリダイレクトしtasksadmins_path、それ以外の場合は にリダイレクトしworkers_pathます。

だから私は次のようなものを試しました:

routes.rb:

devise_for :users, :controllers => { :sessions => 'user_sessions'} do
   get '/users/sign_out' => 'devise/sessions#destroy'
   root to: "workers#index"
end

resources :tasksadmins

resources :workers

root to: "workers#index"

これは私のものapplication_controller.rbです:

class ApplicationController < ActionController::Base
    include ApplicationHelper

    protect_from_forgery
    before_filter :authenticate_user!

    rescue_from CanCan::AccessDenied do |exception|
        if current_user.role_ids == [2]
           redirect_to root_url
        else
           redirect_to tasksadmins_path
        end
    end
end
4

2 に答える 2

1

Deviseには、この状況に対応する特別な方法があります。after_sign_in_path_forを上書きできます。ApplicationControllerで

def after_sign_in_path_for(resource_or_scope)
 if resource_or_scope.is_a?(User)
  town_path
 else
  users_path
 end
end
于 2013-01-31T10:50:28.160 に答える
0

the after_sign_in_path_for doesn't work, so I added to 'create' the next lines:

in the beginning, I wrote:

resource = warden.authenticate!(:scope => resource_name)

and then I wrote in the end of the 'create' function:

sign_in(resource_name, resource)

if current_user.role_ids == [2]
   respond_with resource, :location => workers_path
else
   respond_with resource, :location => tasksadmins_path
end

so my create looks so:

class UserSessionsController < Devise::SessionsController
    include ApplicationHelper

    def create

        resource = warden.authenticate!(:scope => resource_name)

        require "uri"
        require "net/http"

        ## get the user id from the database
        user_id = session['warden.user.user.key'][1][0];

        ## get the row by id
        user = User.find(user_id)

        # ============================
        # Ensure that a user exists
        # ============================

        code, body = http_request(Net::HTTP::Put.new("/api/v1/users/external/#{user_id}"), email: user.email);
        if code != 200
           Rails.logger.error("Unable to register user #{current_user.email} at Licensario");
        end

        sign_in(resource_name, resource)

        if current_user.role_ids == [2]
           respond_with resource, :location => workers_path
       else
           respond_with resource, :location => tasksadmins_path
       end

    end
end
于 2013-02-03T12:44:56.853 に答える