Skip to content

Instantly share code, notes, and snippets.

@ketanghumatkar
Created January 6, 2018 09:34
Show Gist options
  • Save ketanghumatkar/aa5cbd4ecbc3c0fbfe82206fe16bb868 to your computer and use it in GitHub Desktop.
Save ketanghumatkar/aa5cbd4ecbc3c0fbfe82206fe16bb868 to your computer and use it in GitHub Desktop.
New Governance Approach in rails
### NEW Governance approach
## Model Governance
### For delete action validation
class Sample
include Mongoid::Document
before_destroy :authorize
def authorize
error.add :base, "You are not authorized perform this action"
end
end
### For create/update custom validation
#### Govenance Validator
class AuthorizeValidator < ActiveModel::Validator
def validate(record)
unless policy_class.new(record, current_user).on?
record.errors[:base] << "You are not authorized to perform this action"
end
end
def current_user
RequestStore.store[:current_user]
end
end
#### Mongoid Model
Class Sample
include Mongoid::Document
validates_with AuthorizeValidator, on: :create
def policy_class
SamplePolicy
end
end
## Controller Governance
### Call authorize in before action of base controller to cover by defualt authorization
class ApplicationController < ActionController::Base
## Before actions
before_action :authorize
### Raise NotAuthorizedError if permission is not granted for controller_name and action_name for current_user
def authorize
raise Pundit::NotAuthorizedError unless Authorize::permission(controller_name, action_name, current_user)
end
end
### Skip authorization for session and registration controller
class UserSessionController < ActionController::Base
skip_before_action :authorize
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment