Skip to content

Instantly share code, notes, and snippets.

@pawelniewie
Created February 5, 2017 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pawelniewie/cc03c782d0872930b1a662eb30a9b372 to your computer and use it in GitHub Desktop.
Save pawelniewie/cc03c782d0872930b1a662eb30a9b372 to your computer and use it in GitHub Desktop.
Header/param based sessions for iframes
//= require_self
//= require service_buttons
//= require error_reporting
$(function () {
var token = $('meta[name=token]').attr('content');
AJS.$.ajaxPrefilter(function(options) {
if (token) {
options.url += ~options.url.indexOf('?') ? '&' : '?';
options.url += 'X-Cookie' + '=' + token;
}
});
AJS.$.ajaxSetup({
ajaxComplete: function (event, xhr) {
token = xhr.getResponseHeader('X-Cookie');
}
});
});
class ProtectedController < ApplicationController
before_action do |_controller|
authenticate_user_by_other_means unless session[:user_id]
end
end
module ApplicationHelper
def create_session_token
session.id
end
end
class Session < ActiveRecord::SessionStore::Session
default_scope -> { where('expires_at > ? OR expires_at IS NULL', Time.now) }
end
doctype html
html
head
/ Parts ommited for brevity
meta name = 'token' content = create_session_token
= yield :head
= render 'analytics'
= stylesheet_link_tag :application
= javascript_include_tag :application
body class=body_class
== yield
# Be sure to restart your server when you modify this file.
Logger.silencer = false
ActiveRecord::SessionStore::Session.serializer = :json
ActionDispatch::Session::ActiveRecordStore.session_class = Session
class HeaderSessionStore < ActionDispatch::Session::ActiveRecordStore
private
def set_cookie(_request, response, cookie)
response.headers[key] = cookie[:value]
Session.find_by_session_id(cookie[:value])
.update_attribute(:expires_at, cookie[:expires]) if cookie[:expires].present?
end
end
Rails.application.config.session_store HeaderSessionStore, key: "X-Cookie", cookie_only: false, expire_after: 1.hour
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment