From 11db4d765aedaba287fbc08f666a6ef9409fc275 Mon Sep 17 00:00:00 2001 From: Alexis Fellenius Date: Sun, 22 Nov 2015 12:42:33 +0100 Subject: [PATCH] Simple basic auth * Implemented very simple authentication with basic auth. * Introduced a logged_in? method in the application controller to easily use in the views to show/hide authenticated user actions and information. --- app/controllers/application_controller.rb | 7 +++++++ app/controllers/articles_controller.rb | 2 ++ app/helpers/application_helper.rb | 3 +++ app/views/articles/index.html.erb | 8 ++++---- app/views/articles/show.html.erb | 8 ++++++++ app/views/layouts/application.html.erb | 3 +++ 6 files changed, 27 insertions(+), 4 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index d83690e..fae5698 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -2,4 +2,11 @@ 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 + + protected + def authenticate + authenticate_or_request_with_http_basic do |username, password| + username == ENV['BASIC_AUTH_USERNAME'] && password == ENV['BASIC_AUTH_PASSWORD'] + end + end end diff --git a/app/controllers/articles_controller.rb b/app/controllers/articles_controller.rb index c7f624b..9122b52 100644 --- a/app/controllers/articles_controller.rb +++ b/app/controllers/articles_controller.rb @@ -1,4 +1,6 @@ class ArticlesController < ApplicationController + before_filter :authenticate, :except => [:index, :show] + def index @articles = Article.all.order("created_at DESC") end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index de6be79..30d8529 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,2 +1,5 @@ module ApplicationHelper + def logged_in? + not request.authorization.nil? + end end diff --git a/app/views/articles/index.html.erb b/app/views/articles/index.html.erb index 705a24d..4f57da5 100644 --- a/app/views/articles/index.html.erb +++ b/app/views/articles/index.html.erb @@ -8,10 +8,10 @@ diff --git a/app/views/articles/show.html.erb b/app/views/articles/show.html.erb index 5910650..4c65018 100644 --- a/app/views/articles/show.html.erb +++ b/app/views/articles/show.html.erb @@ -13,3 +13,11 @@ +<% if logged_in? %> +
+
+ <%= link_to 'Edit', edit_article_path(@article) %> + <%= link_to 'Destroy', article_path(@article), method: :delete, data: { confirm: 'Are you sure?' } %> +
+
+<% end %> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 4c3da6e..ffc2e90 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -22,6 +22,9 @@