Giter Site home page Giter Site logo

elorest / petergate Goto Github PK

View Code? Open in Web Editor NEW
194.0 8.0 23.0 561 KB

Easy to use and read action and content based authorizations.

License: MIT License

Ruby 87.28% JavaScript 1.13% CSS 0.95% HTML 8.97% SCSS 1.67%
hacktoberfest hacktoberfest2020

petergate's Introduction

Petergate

Build Status Gitter Gem Version

If you like the straight forward and effective nature of Strong Parameters and suspect that cancan might be overkill for your project then you'll love Petergate's easy to use and read action and content based authorizations."

-- 1 Peter 3:41

Installation

Get the gem

Add this line to your application's Gemfile:

gem 'petergate'

And then execute:

bundle

Or install it yourself as:

gem install petergate
Prerequisites: Setup Authentication (Devise)

Make sure your user model is defined in app/models/user.rb and called User.

If you're using devise you're in luck, otherwise you'll have to add following methods to your project:

current_user
after_sign_in_path_for(current_user)
authenticate_user!
Run the generators
rails g petergate:install
rake db:migrate

This will add a migration and insert petergate into your User model.

Usage

User Model

Configure available roles by modifying this block at the top of your user.rb.

############################################################################################
## PeterGate Roles                                                                        ##
## The :user role is added by default and shouldn't be included in this list.             ##
## The :root_admin can access any page regardless of access settings. Use with caution!   ##
## The multiple option can be set to true if you need users to have multiple roles.       ##
petergate(roles: [:admin, :editor], multiple: false)                                      ##
############################################################################################
Instance Methods
user.role => :editor
user.roles => [:editor, :user]
user.roles=(v) #sets roles
user.available_roles => [:admin, :editor]
user.has_roles?(:admin, :editors) # returns true if user is any of roles passed in as params.
Class Methods

User.#{role}_editors => #list of editors. Method is created for all roles. Roles [admin, :teacher] will have corresponding methods role_admins, role_teachers, etc.

Controllers

Setup permissions in your controllers the same as you would for a before filter like so:

access all: [:show, :index], user: {except: [:destroy]}, company_admin: :all

# one other option that might seem a bit weird is to put a group of roles in an array:
access [:all, :user] => [:show, :index]

Inside your views you can use logged_in?(:admin, :customer, :etc) to show or hide content.

<%= link_to "destroy", destroy_listing_path(listing) if logged_in?(:admin, :customer, :etc) %>

If you need to access available roles within your project you can by calling:

User::ROLES
# or from an instance
User.first.available_roles
# ROLES is a CONSTANT and will still work from within the User model instance methods
# like in this default setter:

def roles=(v)
  self[:roles] = v.map(&:to_sym).to_a.select{|r| r.size > 0 && ROLES.include?(r)}
end

If you need to deny access you can use the forbidden! method:

before_action :check_active_user

def check_active_user
  forbidden! unless current_user.active
end

If you want to change the permission denied message you can add to the access line:

access user: [:show, :index], message: "You shall not pass"

User Admin Example Form for Multiple Roles

= form_for @user do |f| 
  - if @user.errors.any? 
    #error_explanation 
      h2 = "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:" 
      ul 
        - @user.errors.full_messages.each do |message| 
          li = message 
 
  .field 
    = f.label :email 
    = f.text_field :email 
  - if @user.new_record? || params[:passwd] 
    .field 
      = f.label :password 
      = f.text_field :password 
    .field 
      = f.label :password_confirmation 
      = f.text_field :password_confirmation 
  .field 
    = f.label :roles 
    = f.select :roles, @user.available_roles, {}, {multiple: true} 
  .actions = f.submit 

User Admin Example Form for Single Role Mode

= form_for @user do |f| 
  - if @user.errors.any? 
    #error_explanation 
      h2 = "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:" 
      ul 
        - @user.errors.full_messages.each do |message| 
          li = message 
 
  .field 
    = f.label :email 
    = f.text_field :email 
  - if @user.new_record? || params[:passwd] 
    .field 
      = f.label :password 
      = f.text_field :password 
    .field 
      = f.label :password_confirmation 
      = f.text_field :password_confirmation 
  .field 
    = f.label :role 
    = f.select :role, @user.available_roles
  .actions = f.submit 

Credits

PeterGate is written and maintaned by Isaac Sloan and friends.

Contributing

  1. Fork it ( https://github.com/isaacsloan/petergate/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

petergate's People

Contributors

carlosagp avatar dburnsii avatar elorest avatar gitter-badger avatar jakemoldham avatar lasaldan avatar sethgw avatar sutanto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

petergate's Issues

undefined method `inject' for nil:NilClass when subclassing a controller.

When subclassing a controller that has a parent with petergate authorization the following error is thrown.

NoMethodError - undefined method `inject' for nil:NilClass:
  petergate (1.1.4) lib/petergate.rb:66:in `parse_permission_rules'
  petergate (1.1.4) lib/petergate.rb:85:in `permissions'
  petergate (1.1.4) lib/petergate.rb:40:in `check_access'
  petergate (1.1.4) lib/petergate.rb:53:in `block in included'

Failure when setting roles

See below for an example. The following might work for setting roles.
def roles=(v)
self[:roles] = v.map(&:to_sym).to_a.select{|r| ROLES.include?(r)}
end

2.2.2 :005 > u = User.second
User Load (0.4ms) SELECT users.* FROM users ORDER BY users.id ASC LIMIT 1 OFFSET 1
=> #<User id: 2, email: "[email protected]", encrypted_password: "$2a$10$HHaM8URgTWy2AAVOGQ63Y.a8nB93Hot7./5yQejW/6Q...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, first_name: "Test", last_name: "User", phone_number: nil, created_at: "2015-08-18 19:43:23", updated_at: "2015-08-18 19:43:23", recurly_account_id: nil, recurly_account_state: nil, recurly_card_last_four: nil, subscription_aasm_state: "invalid", roles: [:user]>
2.2.2 :006 > u.roles = [:super_admin]
NoMethodError: undefined method size' for :super_admin:Symbol from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/petergate-1.2.0/lib/petergate/active_record/base.rb:33:inblock in roles='
from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/petergate-1.2.0/lib/petergate/active_record/base.rb:33:in select' from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/petergate-1.2.0/lib/petergate/active_record/base.rb:33:inroles='
from (irb):6
from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in start' from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands/console.rb:9:instart'
from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in console' from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:inrun_command!'
from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands.rb:17:in <top (required)>' from bin/rails:4:inrequire'
from bin/rails:4:in <main>' 2.2.2 :007 > u.roles = [:user, :super_admin] NoMethodError: undefined methodsize' for :user:Symbol
from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/petergate-1.2.0/lib/petergate/active_record/base.rb:33:in block in roles=' from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/petergate-1.2.0/lib/petergate/active_record/base.rb:33:inselect'
from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/petergate-1.2.0/lib/petergate/active_record/base.rb:33:in roles=' from (irb):7 from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands/console.rb:110:instart'
from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in start' from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:inconsole'
from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in run_command!' from /Users/junckdawg/.rvm/gems/ruby-2.2.2/gems/railties-4.2.0/lib/rails/commands.rb:17:in<top (required)>'
from bin/rails:4:in require' from bin/rails:4:in

'

write tests for multirole auth

Create a new testing crud and a user with multiple roles. Test that they can see actions with any of the roles but not actions without any of their roles.

Can't find generator 'petergate:install'

Simply create a new rails app (5.1.2), install devise (4.3.0), install petergate, and can't get it to run install.

Could not find generator 'petergate:install'. Maybe you meant 'devise:install', 'responders:install' or 'integration_test'

Setting role that are not available on available_roles clears all the roles except :user role?

I don't know is this issue or intended behaviour. When I try to set roles that are not available on available_roles then roles are reset to :users only, clearing all other roles set previously.

u = User.first
u.available_roles # gives [:root_admin, :admin, :manager]
u.roles # gives [:admin, :user]
u.update(roles: :test) #sets role to :user only clearing all other previously set roles.
u.roles # gives [:user]

Is this behaviour intended or is an issue.
Needed insight if I want to add error message on user object if invalid role is tried to set, without clearing previously set roles.

Unauthenticated user role

Imagine a testcase where a specific controller has access privileges for its actions.
Let's say there's a controller "Test" and it has actions like "show", "new", "create" and i created an access privilege using petergate for different roles.
access user: [show], admin: [new create]
The test case that's bugging me is that what if the user is NOT AUTHENTICATED and want to access a page of this "Test" controller ??
I tried to create a replica of "Test" contoller, create new views for it and on form submission, i tried to push the form data into the "Test" model. But it's not allowing me to do so as Test controller is linked to Test model.

Need help on this !

Uninitialized constant for controller concern in Heroku production sstem

I am getting an error when running the app (or using Rails Console) on Heroku where the petergate action_controller finds a missing constant for a concern module:

/app/vendor/bundle/ruby/2.4.0/gems/petergate-1.8.0/lib/petergate/action_controller/base.rb:10:in `const_missing': uninitialized constant ApplicationController::SetI18nLocale (NameError)

This works OK in development and there is no issue with the concern. I tried to add include Petergate::ActionController::Base before the include for the concern in the ApplicationController but this also does not work. I am using Ruby 2.4.1 and Rails 5.1.3. Any suggestions on how to proceed? Thanks.

bundler cannot see i18n-0.8.6 when attempting to install petergate gem

What I tried to do

I tried to run
rails g petergate:install
What I expected to happen

I expected it to add a migration and insert petergate into my User model.

What actually happened

I got an error in terminal saying:


Could not find i18n-0.8.6 in any of the sources
Run `bundle install` to install missing gems.

I ran bundle install and retried rails g petergate:install, but the same error keeps occurring.
When I view my gems, I do have i18n-0.8.6

danales-MacBook-Pro:dancortesPortfolio danale$ rails g petergate:install
Could not find i18n-0.8.6 in any of the sources
Run `bundle install` to install missing gems.
danales-MacBook-Pro:dancortesPortfolio danale$ bundle install
Using rake 12.0.0
Using concurrent-ruby 1.0.5
Using i18n 0.8.6

Petergate doesnt work with MongoID

hello everyone im trying to use petergate with mongo Db but Im getting this exception.

There was an error while trying to load the gem 'petergate'. (Bundler::GemRequireError)
Gem Load Error is: uninitialized constant ActiveRecord

someone can help me? Thank you so much

Get user roles from ActiveRecord

Not sure if this counts as an issue, but i am new to rails and dont know if or how it is doable.

I want to be able to have a model called UserRoles and dynamically create new roles. How do i need to modify User model to provide this?

Thanks in advance!

Undefined method `access' when using ActionController::API

Hi there!

First of all I am new to Ruby and Ruby on Rails. Via the Udemy course: Dissecting Ruby on Rails 5 I ran into this library.

Currently I am building an REST API and would like to use Petergate for Authorization (Authentication via knock) but ran into a problem.

I generated an new rails app with the --api flag. When you do this Rails creates an ApplicationController that extends from ActionController::API and here is where the problem lies. When you then try to use the access method you get the following error:

ActionController::RoutingError (undefined method `access' for UsersController:Class):

Is this expected behaviour? When I change the ApplicationContoller to extend from ActionController::Base everything works fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.