poniedziałek, 23 stycznia 2012

param_protected i Devise

Kilka dni temu pisałem już o gemie param_protected. Jeżeli używamy go razem z Devise, będziemy musieli zrobić zmodyfikować kontrolery i dodać definicję dozwolonych parametrów.

Po pierwsze musimy zmapować URL-e na nasze nowe kontrolery.

MyApp::Application.routes.draw do
devise_for :users, controllers: {
registrations: 'auth/devise/registrations',
sessions: 'auth/devise/sessions',
# ...
}
end
view raw routes.rb hosted with ❤ by GitHub

Nie będzie do rozwiązanie DRY. Dlatego zdefiniujemy klasę, która przygotuje nam potrzebny hash

# /lib/routes/devise_controllers.rb
class Routes::DeviseControllers
def self.to_hash
controllers = [:confirmations, :passwords, :registrations, :sessions, :unlocks]
Hash[*controllers.map {|controller| [controller, "auth/devise/#{controller}"]}.flatten]
end
end

Zmieniamy więc nasz plik routes.rb

BaseApp::Application.routes.draw do
devise_for :users, controllers: Routes::DeviseControllers.to_hash
end
view raw routes.rb hosted with ❤ by GitHub

Teraz najgorsza część. Musimy zdefiniować wszystkie kontrolery

# /app/controllers/auth/devise/confirmations_controller.rb
class Auth::Devise::ConfirmationsController < Devise::ConfirmationsController
param_accessible user: [:email], only: :create
end
# /app/controllers/auth/devise/passwords_controller.rb
class Auth::Devise::PasswordsController < Devise::PasswordsController
param_accessible user: [:email], only: :create
param_accessible :reset_password_token, only: :edit
param_accessible user: [:password, :password_confirmation, :reset_password_token], only: :update
end
# /app/controllers/auth/devise/registrations_controller.rb
class Auth::Devise::RegistrationsController < Devise::RegistrationsController
param_accessible user: [:username, :email, :password, :password_confirmation], only: [:create, :update]
param_accessible user: [:current_password], only: :update
end
# /app/controllers/auth/devise/sessions_controller.rb
class Auth::Devise::SessionsController < Devise::SessionsController
param_accessible user: [:login, :password, :remember_me]
end
# /app/controllers/auth/devise/unlocks_controller.rb
class Auth::Devise::UnlocksController < Devise::UnlocksController
param_accessible user: [:email], only: :create
end

Jest bardzo duża szansa że zapomniałem a jakimś parametrze (chociaż narazie wszystko u mnie działa ;)). Jeżeli tak, proszę o komentarz.

2 komentarze:

  1. Maybe this would be easier:

    https://gist.github.com/1987160

    ;)

    OdpowiedzUsuń
  2. well, yes it's a bit easier but I'm not big fan of evaling classes if I don't have to. Devise gave us really simple way to extend controllers so why wouldn't we use it? And it's more verbose to set those new controllers explicitly.

    + Devise will sooner or later need some customization so we will have to create those controllers anyway :)

    by the way - I have a new blog, in english: zlw@github:pages

    OdpowiedzUsuń