Commit 4448194

mo khan <mo@mokhan.ca>
2015-03-14 18:29:06
redirect to login page when not signed in.
1 parent c39da75
app/controllers/application_controller.rb
@@ -2,6 +2,7 @@ class ApplicationController < ActionController::Base
   # Prevent CSRF attacks by raising an exception.
   # For APIs, you may want to use :null_session instead.
   protect_from_forgery with: :exception
+  before_action :authorize!
 
   protected
 
@@ -16,4 +17,8 @@ class ApplicationController < ActionController::Base
   def translate(key)
     I18n.translate("#{params[:controller]}.#{params[:action]}#{key}")
   end
+
+  def authorize!
+    redirect_to new_session_path if try(:current_user).nil?
+  end
 end
app/controllers/sessions_controller.rb
@@ -1,7 +1,6 @@
 class SessionsController < ApplicationController
-  
   layout "public"
-  
+
   def create
     user = User.authenticate(params[:user][:username], params[:user][:password])
     if user.present?
@@ -12,15 +11,13 @@ class SessionsController < ApplicationController
       redirect_to new_session_path
     end
   end
-  
+
   def new
     @user = User.new
-    
   end
-  
+
   def destroy
     reset_session()
     redirect_to root_path
   end
-  
 end
spec/controllers/items_controller_spec.rb
@@ -42,8 +42,8 @@ RSpec.describe ItemsController, type: :controller do
       end
 
       it "loads up the params for a new item" do
-        get :new, item: { name: 'hammer' }
-        expect(assigns(:item).name).to eql('hammer')
+        get :new, item: { name: "hammer" }
+        expect(assigns(:item).name).to eql("hammer")
       end
     end
 
@@ -95,7 +95,7 @@ RSpec.describe ItemsController, type: :controller do
 
       context "when some of the fields are invalid" do
         it "displays the errors" do
-          post :create, item: { name: '' }
+          post :create, item: { name: "" }
           expect(flash[:warning]).to_not be_empty
         end
       end
@@ -147,4 +147,13 @@ RSpec.describe ItemsController, type: :controller do
       end
     end
   end
+
+  context "when not logged in" do
+    describe "#index" do
+      it "redirects to the login page" do
+        get :index
+        expect(response).to redirect_to(new_session_path)
+      end
+    end
+  end
 end