Skip to content

Instantly share code, notes, and snippets.

@jhilden
Last active June 16, 2018 04:11
Show Gist options
  • Save jhilden/6634320 to your computer and use it in GitHub Desktop.
Save jhilden/6634320 to your computer and use it in GitHub Desktop.
# Discourse SSO Rails::Engine gem to perform cookie-based SSO login in [Discourse](http://www.discourse.org/). It expects your main app to set a cookie readable by Discourse with a Discourse `user_id` as the value (encrypting the value is a very good idea). See: http://meta.discourse.org/t/give-me-those-authentication-hooks-d/3943
module DiscourseSso
module ControllerExtensions
def self.included(klass)
klass.append_before_filter :ensure_sso_login
end
private
def ensure_sso_login
if cookies[:discourse_sso_cookie].present?
cookie_user_id = cookies[:discourse_sso_cookie] # makes sense to have this value encrypted in the cookie
unless current_user && current_user.id == cookie_user_id
begin
user = User.find cookie_user_id
log_on_user(user)
redirect_to url_for # we need to "reload" the page, so the user sees that he's logged in
rescue => exception
notify_airbrake(exception)
end
end
else
reset_session
cookies[:_t] = nil
end
end
end
class Engine < Rails::Engine
engine_name 'discourse_sso'
initializer "discourse_sso.rails_initialization" do |app|
app.config.after_initialize do
ActiveSupport.on_load(:action_controller) do
include DiscourseSso::ControllerExtensions
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment