Commit 9618bd7
Changed files (3)
app
controllers
models
spec
models
app/controllers/application_controller.rb
@@ -12,12 +12,14 @@ class ApplicationController < ActionController::Base
@current_user ||= @current_session.user
end
+ def current_session(session_key = cookies.signed[:raphael])
+ @current_session ||= Session.authenticate!(session_key)
+ end
+
private
- def ensure_valid_session(user_session_id = cookies.signed[:raphael])
- unless @current_session = Session.find(user_session_id)
- redirect_to new_session_path
- end
+ def ensure_valid_session
+ redirect_to new_session_path unless current_session
rescue ActiveRecord::RecordNotFound
redirect_to new_session_path
end
app/models/session.rb
@@ -13,4 +13,10 @@ class Session < ActiveRecord::Base
raise "heck"
end
end
+
+ class << self
+ def authenticate!(session_key)
+ Session.find(session_key)
+ end
+ end
end
spec/models/session_spec.rb
@@ -9,4 +9,20 @@ describe Session do
expect(session.ip_address).to eql("127.0.0.1")
end
end
+
+ context ".authenticate" do
+ let(:user_session) { create(:session) }
+
+ context "when the session key is legit" do
+ it 'returns the session' do
+ expect(Session.authenticate!(user_session.id)).to eql(user_session)
+ end
+ end
+
+ context "when the session key is incorrect" do
+ it 'raises an error' do
+ expect(-> { Session.authenticate!('blah') }).to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+ end
end