12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- #---
- # Excerpted from "Agile Web Development with Rails",
- # published by The Pragmatic Bookshelf.
- # Copyrights apply to this code. It may not be used to create training material,
- # courses, books, articles, and the like. Contact us if you are in doubt.
- # We make no guarantees that this code is fit for any purpose.
- # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
- #---
- class ApplicationController < ActionController::Base
- before_action :set_i18n_locale_from_params
- # ...
- before_action :authorize
- # Prevent CSRF attacks by raising an exception.
- # For APIs, you may want to use :null_session instead.
- protect_from_forgery with: :exception
- # ...
- protected
- def authorize
- if request.format == Mime::HTML
- unless User.find_by(id: session[:user_id])
- redirect_to login_url, notice: "Please log in"
- end
- else
- authenticate_or_request_with_http_basic do |username, password|
- user = User.find_by(name: username)
- user && user.authenticate(password)
- end
- end
- end
- def set_i18n_locale_from_params
- if params[:locale]
- if I18n.available_locales.map(&:to_s).include?(params[:locale])
- I18n.locale = params[:locale]
- else
- flash.now[:notice] =
- "#{params[:locale]} translation not available"
- logger.error flash.now[:notice]
- end
- end
- end
- def default_url_options
- { locale: I18n.locale }
- end
- end
|