flexible_permissions 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 2e7958a77bb44a097cd42940e17ce51c95643829
4
+ data.tar.gz: 224b4e8da1d047c3d7e598bdfbbbfb341135399d
5
+ SHA512:
6
+ metadata.gz: 674c7c6deeedf9251f212438c7b6c76347b55f1f3e554e9aa095db93ad542c613c3ccb6f8d8da91cf001e8d1c13b33501ca929cae0cb3f41beaa8e0a5fc09d04
7
+ data.tar.gz: 91cc301f74360440ee8cec2ef3084c1694380c6150f2fea2b000c3cfea1cbfa1c063980710273593fa77bce154a5836f9e25f0a84ecdd6aa0fb5bf79aaec66e5
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.gem
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at vasilakisfil@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in flexible_permissions.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Filippos Vasilakis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # FlexiblePermissions
2
+
3
+ *At the moment this gem is tied to ActiveRecord but it's easy to change that
4
+ by overriding default permitted methods for fields and resource*
5
+
6
+ For building APIs (and not only) I have been using [Pundit](https://github.com/elabs/pundit) gem for years.
7
+ It's an awesome gem.
8
+ However there is a tiny issue: Pundit has a black and white policy whereas in
9
+ APIs usually you need a grayscale. The user might have access to a specific
10
+ resource/action, but only in certain attributes of that resource.
11
+
12
+ An explanation can be found in some parts of
13
+ [this](http://slides.com/vasilakisfil/apis-on-ruby-and-rails#) presentation, [a pundig issue](https://github.com/elabs/pundit/issues/212#issuecomment-64049328)
14
+ and [this blog post](http://slides.com/vasilakisfil/apis-on-ruby-and-rails#/).
15
+
16
+ ## So what this gem does?
17
+ This gem allows you to specify in an easy way the following properties of a resource
18
+ based on the user role:
19
+
20
+ * default attributes of a resource
21
+ * permitted attributes of a resource (superset of default attributes)
22
+ * default associations of resource
23
+ * permitted associations of resource
24
+
25
+ You filter the associations based on the name of the association found.
26
+ However the gem provides you an easy way to map any attributes/associations to
27
+ the ones you have defined in your API/serializer.
28
+
29
+ Note that this gem works perfectly well with [Pundit](https://github.com/elabs/pundit)
30
+ but [Pundit](https://github.com/elabs/pundit) is not a requirement to use `flexible_permissions`
31
+
32
+ ## Installation
33
+
34
+ Add this line to your application's Gemfile:
35
+
36
+ ```ruby
37
+ gem 'flexible_permissions'
38
+ ```
39
+
40
+ And then execute:
41
+
42
+ $ bundle
43
+
44
+ Or install it yourself as:
45
+
46
+ $ gem install flexible_permissions
47
+
48
+ ## Usage
49
+
50
+ So let's say that we have a `User` resource in our API that we want to allow
51
+ different representations based on the current user role: Guest user,
52
+ Regular user and Admin user.
53
+
54
+ Here is how a pundit policy looks like:
55
+
56
+ ```ruby
57
+ class UserPolicy < ApplicationPolicy
58
+ #allows only Admin and Regular roles, returns only Regular permissions
59
+ (given that the endpoint to create a user does not require authentication)
60
+ def create?
61
+ return Regular.new(record)
62
+ end
63
+
64
+ #allows all roles but with different permissions
65
+ def show?
66
+ return Guest.new(record) unless user
67
+ return Admin.new(record) if user.admin?
68
+ return Regular.new(record)
69
+ end
70
+
71
+ #allows only Admin and Regular roles, each with different permissions
72
+ def update?
73
+ raise Pundit::NotAuthorizedError unless user
74
+ return Admin.new(record) if user.admin?
75
+ return Regular.new(record)
76
+ end
77
+
78
+ #allows only Admin and Regular roles, each with different permissions
79
+ def destroy?
80
+ raise Pundit::NotAuthorizedError unless user
81
+ return Admin.new(record) if user.admin?
82
+ return Regular.new(record)
83
+ end
84
+
85
+ class Scope < Scope
86
+ def resolve
87
+ return Guest.new(record, User) unless user
88
+ return Admin.new(scope, User) if user.admin?
89
+ return Regular.new(scope, User)
90
+ end
91
+ end
92
+
93
+ #admin has access to everything, plus, some extra fields
94
+ class Admin < FlexiblePermissions::Base
95
+ class Fields < self::Fields
96
+ def permitted
97
+ super + [
98
+ :links, :following_state, :follower_state
99
+ ]
100
+ end
101
+ end
102
+
103
+ class Includes < self::Includes
104
+ #our API has `following` but our API exposes `followings`
105
+ def transformations
106
+ {following: :followings}
107
+ end
108
+ end
109
+ end
110
+
111
+ #we chop fields for regular user (but we still keep admins extra fields)
112
+ class Regular < Admin
113
+ class Fields < self::Fields
114
+ def permitted
115
+ super - [
116
+ :activated, :activated_at, :activation_digest, :admin,
117
+ :password_digest, :remember_digest, :reset_digest, :reset_sent_at,
118
+ :token, :updated_at,
119
+ ]
120
+ end
121
+ end
122
+ end
123
+
124
+ #and we chop even more for a guest
125
+ class Guest < Regular
126
+ class Fields < self::Fields
127
+ def permitted
128
+ super - [:following_state, :follower_state]
129
+ end
130
+ end
131
+ end
132
+ end
133
+ ```
134
+
135
+ For each role class you have 2 embedded classes:
136
+ * `Fields` that sets up what fields (attributes) are allowed for this specific role
137
+ * `Includes` that sets up what related resources (associations) are allowed for this specific role
138
+
139
+ For each of those 2 classes, you can setup the final allowed attributes using the following methods:
140
+ * `#permitted` speciffies the permitted attributes
141
+ * `#defaults` specifies the defaults attributes (a subset of permitted attributes)
142
+ * `#transformations` specifies any transformations from the db level to the API level
143
+
144
+ If you have pundit, you can get the allowed attributes in your controller using the
145
+ `authorize_with_permissions` method which uses underhood pundit's authorize method
146
+
147
+ After that you get an object back that has the following methods:
148
+ * `fields` returns the underrelying record
149
+ * `includes` returns the underrelying record
150
+ * `record` returns the underrelying record that you passed in to authorize
151
+ * `collection` returns the underlying collection that you passed in to authorize
152
+
153
+ Protip: `collection` is aliased to `record`.
154
+
155
+ ```ruby
156
+ def show
157
+ auth_user = authorize_with_permissions(@user)
158
+
159
+ render jsonapi: auth_user.record, serializer: Api::V1::UserSerializer,
160
+ fields: {user: auth_user.fields.concat(params[:fields])}
161
+ end
162
+ ```
163
+
164
+ ## Development
165
+
166
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
167
+
168
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
169
+
170
+ ## Contributing
171
+
172
+ Bug reports and pull requests are welcome on GitHub at https://github.com/vasilakisfil/flexible_permissions. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
173
+
174
+
175
+ ## License
176
+
177
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "flexible_permissions"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,26 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'flexible_permissions/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "flexible_permissions"
8
+ spec.version = FlexiblePermissions::VERSION
9
+ spec.authors = ["Filippos Vasilakis"]
10
+ spec.email = ["vasilakisfil@gmail.com"]
11
+
12
+ spec.summary = %q{Removes black and white pundit policy and adds flexible permissions for attributes/associations per role class. Perfect for modern APIs.}
13
+ spec.description = %q{Removes black and white pundit policy and adds flexible permissions for attributes/associations per role class. Perfect for modern APIs.}
14
+ spec.homepage = "https://github.com/vasilakisfil/flexible-permissions"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.13"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ end
@@ -0,0 +1,7 @@
1
+ require "flexible_permissions/version"
2
+ require "flexible_permissions/modules"
3
+ require "flexible_permissions/base"
4
+
5
+ if defined?(Pundit)
6
+ require "flexible_permissions/pundit"
7
+ end
@@ -0,0 +1,19 @@
1
+ module FlexiblePermissions
2
+ class Base
3
+ include RoleMethods
4
+
5
+ class Fields
6
+ include SparsedFieldMethods
7
+ end
8
+
9
+ class Includes
10
+ include SparsedIncludeMethods
11
+ end
12
+
13
+ #for AMS basically...
14
+ def expects_include_fields_in_fields
15
+ true
16
+ end
17
+ end
18
+ end
19
+
@@ -0,0 +1,96 @@
1
+ module FlexiblePermissions
2
+ module RoleMethods
3
+ attr_reader :record, :model
4
+
5
+ def initialize(record, model = nil)
6
+ @record = record
7
+ @model = model || record.class
8
+ end
9
+
10
+ def fields(asked = nil)
11
+ self.class::Fields.new(asked, record, model).resolve.concat(
12
+ expects_include_fields_in_fields ? includes : []
13
+ )
14
+ end
15
+
16
+ def includes(asked = nil)
17
+ self.class::Includes.new(asked, record, model).resolve
18
+ end
19
+
20
+ def collection
21
+ record
22
+ end
23
+
24
+ def expects_include_fields_in_fields
25
+ false
26
+ end
27
+ end
28
+
29
+ module SparsedMethods
30
+ attr_reader :resolve, :model, :record, :asked
31
+ def initialize(asked, record, model)
32
+ @model = model
33
+ @asked = asked
34
+ @record = record
35
+ end
36
+
37
+ def resolve
38
+ return with_transformations(defaults) if asked.blank?
39
+
40
+ with_transformations(union(permitted, asked))
41
+ end
42
+
43
+ private
44
+ def with_transformations(attributes)
45
+ return attributes if transformations.blank?
46
+
47
+ attributes.map{|x|
48
+ transformations[x] ? transformations[x] : x
49
+ }.flatten
50
+ end
51
+
52
+ def transformations
53
+ {}
54
+ end
55
+
56
+ def permitted
57
+ []
58
+ end
59
+
60
+ def defaults
61
+ permitted
62
+ end
63
+
64
+ def union(permitted, asked = nil)
65
+ return permitted unless asked.is_a?(Array)
66
+
67
+ permitted.map(&:to_sym) & asked.map(&:to_sym)
68
+ end
69
+
70
+ def collection?
71
+ record.kind_of? ActiveRecord::Relation
72
+ end
73
+
74
+ def resource?
75
+ !collection?
76
+ end
77
+ end
78
+
79
+ module SparsedFieldMethods
80
+ include SparsedMethods
81
+
82
+ private
83
+ def permitted
84
+ model.attribute_names.map(&:to_sym)
85
+ end
86
+ end
87
+
88
+ module SparsedIncludeMethods
89
+ include SparsedMethods
90
+
91
+ private
92
+ def permitted
93
+ model.reflect_on_all_associations.map(&:name).map(&:to_sym)
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,18 @@
1
+ module AuthorizeWithReturn
2
+ def authorize_with_permissions(record, query=nil)
3
+ query ||= params[:action].to_s + '?'
4
+ @_pundit_policy_authorized = true
5
+
6
+ policy = policy(record)
7
+ policy.public_send(query)
8
+ end
9
+
10
+ def included
11
+ super
12
+ hide_action :authorize
13
+ end
14
+ end
15
+
16
+ module Pundit
17
+ prepend AuthorizeWithReturn
18
+ end
@@ -0,0 +1,3 @@
1
+ module FlexiblePermissions
2
+ VERSION = "1.0.0"
3
+ end
metadata ADDED
@@ -0,0 +1,88 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: flexible_permissions
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Filippos Vasilakis
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-12-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.13'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.13'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ description: Removes black and white pundit policy and adds flexible permissions for
42
+ attributes/associations per role class. Perfect for modern APIs.
43
+ email:
44
+ - vasilakisfil@gmail.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".gitignore"
50
+ - CODE_OF_CONDUCT.md
51
+ - Gemfile
52
+ - LICENSE.txt
53
+ - README.md
54
+ - Rakefile
55
+ - bin/console
56
+ - bin/setup
57
+ - flexible_permissions.gemspec
58
+ - lib/flexible_permissions.rb
59
+ - lib/flexible_permissions/base.rb
60
+ - lib/flexible_permissions/modules.rb
61
+ - lib/flexible_permissions/pundit.rb
62
+ - lib/flexible_permissions/version.rb
63
+ homepage: https://github.com/vasilakisfil/flexible-permissions
64
+ licenses:
65
+ - MIT
66
+ metadata: {}
67
+ post_install_message:
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubyforge_project:
83
+ rubygems_version: 2.5.1
84
+ signing_key:
85
+ specification_version: 4
86
+ summary: Removes black and white pundit policy and adds flexible permissions for attributes/associations
87
+ per role class. Perfect for modern APIs.
88
+ test_files: []