From 610100d7ccfdf47cf325fbc6c1cf48a3329f8d65 Mon Sep 17 00:00:00 2001 From: Colin Darie Date: Tue, 29 May 2018 13:09:42 +0200 Subject: [PATCH] Added Pundit. --- Gemfile | 1 + Gemfile.lock | 3 ++ app/controllers/application_controller.rb | 8 ++++ app/policies/application_policy.rb | 53 +++++++++++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 app/policies/application_policy.rb diff --git a/Gemfile b/Gemfile index 3a119d1..2db3ac3 100644 --- a/Gemfile +++ b/Gemfile @@ -14,6 +14,7 @@ gem 'puma', '~> 3.11' gem 'devise', '~> 4.4' gem 'devise-i18n', '~> 1.6' gem 'simple_form', '~> 4.0' +gem 'pundit', '~> 1.1' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' diff --git a/Gemfile.lock b/Gemfile.lock index 978f671..65be68a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -162,6 +162,8 @@ GEM pry (>= 0.10.4) public_suffix (3.0.2) puma (3.11.4) + pundit (1.1.0) + activesupport (>= 3.0.0) rack (2.0.5) rack-proxy (0.6.4) rack @@ -296,6 +298,7 @@ DEPENDENCIES pry-byebug pry-rails puma (~> 3.11) + pundit (~> 1.1) rails (~> 5.2.0) rails-i18n (~> 5.1) rubocop (~> 0.56.0) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 37ba566..6a3bd7a 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,4 +1,7 @@ class ApplicationController < ActionController::Base + include Pundit + rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized + before_action :configure_devise_parameters, if: :devise_controller? protected @@ -7,4 +10,9 @@ class ApplicationController < ActionController::Base devise_parameter_sanitizer.permit(:sign_up, keys: [:tos_accepted]) devise_parameter_sanitizer.permit(:account_update, keys: [:notifications_enabled]) end + + def user_not_authorized + flash[:alert] = I18n.t("user_not_authorized", scope: :flashes) + redirect_to(request.referrer || root_path) + end end diff --git a/app/policies/application_policy.rb b/app/policies/application_policy.rb new file mode 100644 index 0000000..b91c7f5 --- /dev/null +++ b/app/policies/application_policy.rb @@ -0,0 +1,53 @@ +class ApplicationPolicy + attr_reader :user, :record + + def initialize(user, record) + @user = user + @record = record + end + + def index? + false + end + + def show? + scope.where(id: record.id).exists? + end + + def create? + false + end + + def new? + create? + end + + def update? + false + end + + def edit? + update? + end + + def destroy? + false + end + + def scope + Pundit.policy_scope!(user, record.class) + end + + class Scope + attr_reader :user, :scope + + def initialize(user, scope) + @user = user + @scope = scope + end + + def resolve + scope + end + end +end