application_controller.rb 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. class ApplicationController < ActionController::Base
  10. before_action :set_i18n_locale_from_params
  11. # ...
  12. before_action :authorize
  13. # Prevent CSRF attacks by raising an exception.
  14. # For APIs, you may want to use :null_session instead.
  15. protect_from_forgery with: :exception
  16. # ...
  17. protected
  18. def authorize
  19. if request.format == Mime::HTML
  20. unless User.find_by(id: session[:user_id])
  21. redirect_to login_url, notice: "Please log in"
  22. end
  23. else
  24. authenticate_or_request_with_http_basic do |username, password|
  25. user = User.find_by(name: username)
  26. user && user.authenticate(password)
  27. end
  28. end
  29. end
  30. def set_i18n_locale_from_params
  31. if params[:locale]
  32. if I18n.available_locales.map(&:to_s).include?(params[:locale])
  33. I18n.locale = params[:locale]
  34. else
  35. flash.now[:notice] =
  36. "#{params[:locale]} translation not available"
  37. logger.error flash.now[:notice]
  38. end
  39. end
  40. end
  41. def default_url_options
  42. { locale: I18n.locale }
  43. end
  44. end