问题
Since I am based in European Union, I believe all the websites I make have to comply with this stupid EU regulation that bans cookie use without user's informed consent (and require the user to opt-in).
My intention is to go "full-overkill" and require user to (re-)accept Terms of Service whenever there's no "_#{app_name}_session" cookie sent from user and (re-)create it only after user clicks [ACCEPT] in said ToS.
Basically, whenever someone visits the app, the user will be forced to explicitly accept ToS or Sign in to be able to use the app/website.
How can I make this happen in in Rails 4?
In PHP I'd just need to add
if (session_status() != PHP_SESSION_ACTIVE){
header("Location: /terms-of-service");
}
to the beginning of the index.php
I would then need to make sure that the only session_start() is at the file that serves the /terms-of-service page and there is no other instance anywhere else in the project.
But how to do this with Rails?
回答1:
You can do this by creating a before_filter in your ApplicationController:
class ApplicationController < ActionController::Base
before_filter :validate_toc!
private
def validate_toc!
# check if guest user has not already accepted the toc from session
redirect_to toc_path, alert: 'Please accept ToC to continue.' if sesion[:tos].nil? || !user_logged_in?
end
end
Note: sesion[:tos] is where you set value when user accepts ToS. toc_path should be set in routes.rb, for example like this:
get '/path/to/toc' => 'pages#toc', :as => :toc
回答2:
I examined @User089247's answer and modified it to my needs
before_action :session_check!, except: [:terms_of_service_path]
private
def session_check!
redirect_to terms_of_service_path if !session.exists?
end
Basically, if there's no session open for the browser session, the user will be forced to accept the ToS. The ToS page will then create the session unless the user refuses to accept the ToS.
来源:https://stackoverflow.com/questions/26669639/force-disabling-cookies-in-ruby-on-rails-4-european-union-legislation-until-us