u-authorization 2.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -1,136 +1,523 @@
1
- [![Gem](https://img.shields.io/gem/v/u-authorization.svg?style=flat-square)](https://rubygems.org/gems/u-authorization)
2
- [![Build Status](https://travis-ci.com/serradura/u-authorization.svg?branch=master)](https://travis-ci.com/serradura/u-authorization)
3
- [![Maintainability](https://api.codeclimate.com/v1/badges/19251112cf39afdf8bf6/maintainability)](https://codeclimate.com/github/serradura/u-authorization/maintainability)
4
- [![Test Coverage](https://api.codeclimate.com/v1/badges/19251112cf39afdf8bf6/test_coverage)](https://codeclimate.com/github/serradura/u-authorization/test_coverage)
1
+ <p align="center">
2
+ <h1 align="center">🔐 µ-authorization</h1>
3
+ <p align="center"><i>Authorization and role management for Ruby, with no runtime dependencies.</i></p>
4
+ </p>
5
+
6
+ <p align="center">
7
+ <a href="https://rubygems.org/gems/u-authorization">
8
+ <img alt="Gem" src="https://img.shields.io/gem/v/u-authorization.svg?style=flat-square">
9
+ </a>
10
+ <a href="https://github.com/u-gems/u-authorization/actions/workflows/ci.yml">
11
+ <img alt="Build Status" src="https://github.com/u-gems/u-authorization/actions/workflows/ci.yml/badge.svg">
12
+ </a>
13
+ <br/>
14
+ <a href="https://qlty.sh/gh/u-gems/projects/u-authorization"><img src="https://qlty.sh/gh/u-gems/projects/u-authorization/maintainability.svg" alt="Maintainability" /></a>
15
+ <a href="https://qlty.sh/gh/u-gems/projects/u-authorization"><img src="https://qlty.sh/gh/u-gems/projects/u-authorization/coverage.svg" alt="Code Coverage" /></a>
16
+ <br/>
17
+ <img src="https://img.shields.io/badge/Ruby%20%3E%3D%202.7%2C%20%3C%3D%20Head-ruby.svg?colorA=444&colorB=333" alt="Ruby">
18
+ <img src="https://img.shields.io/badge/Rails%20%3E%3D%206.0%2C%20%3C%3D%20Edge-rails.svg?colorA=444&colorB=333" alt="Rails">
19
+ </p>
20
+
21
+ > [!IMPORTANT]
22
+ > **Stable and feature-complete.** `u-authorization` has no new features planned. Its public API is frozen and backward compatible, and ongoing work is limited to keeping it running on current and future Ruby versions. You can depend on it without expecting breaking changes.
23
+ >
24
+ > A major version bump signals only that an old Ruby version was dropped from the supported matrix, which is a dependency-floor change under SemVer. Your code keeps working.
25
+
26
+ `u-authorization` splits authorization into two layers that you can use together or on their own:
27
+
28
+ 1. **Permissions** answer "is this role allowed to use this feature, in this context?". A role is plain data (a Hash, or JSON loaded from a database), so you can change who can do what without redeploying.
29
+ 2. **Policies** answer "is this user allowed to act on this specific record?". A policy is a small Ruby class, similar to [Pundit](https://github.com/varvet/pundit), that returns `true` or `false` and defaults to denying anything it doesn't recognize.
30
+
31
+ The two layers are independent, and you pick the right one for each check. Use permissions to gate a feature by role and context, which fits a controller `before_action`. Use a policy to decide access to a single record. An authorization object carries the current user, the request context, the role's permissions, and the policies for one request, so both checks are available from the same place.
32
+
33
+ ## Table of contents
34
+
35
+ - [Table of contents](#table-of-contents)
36
+ - [Installation](#installation)
37
+ - [Supported versions](#supported-versions)
38
+ - [Quick start](#quick-start)
39
+ - [Permissions](#permissions)
40
+ - [Roles are plain data](#roles-are-plain-data)
41
+ - [Permission rules](#permission-rules)
42
+ - [Context matching and dot notation](#context-matching-and-dot-notation)
43
+ - [Checking permissions](#checking-permissions)
44
+ - [Multiple roles](#multiple-roles)
45
+ - [Policies](#policies)
46
+ - [Defining a policy](#defining-a-policy)
47
+ - [The subject](#the-subject)
48
+ - [Reading permissions inside a policy](#reading-permissions-inside-a-policy)
49
+ - [The authorization object](#the-authorization-object)
50
+ - [Building it](#building-it)
51
+ - [Asking about permissions](#asking-about-permissions)
52
+ - [Fetching policies](#fetching-policies)
53
+ - [Registering policies](#registering-policies)
54
+ - [Cloning with map](#cloning-with-map)
55
+ - [Using it with Rails](#using-it-with-rails)
56
+ - [Comparison with Pundit and CanCanCan](#comparison-with-pundit-and-cancancan)
57
+ - [Development](#development)
58
+ - [Contributing](#contributing)
59
+ - [License](#license)
60
+ - [Code of conduct](#code-of-conduct)
5
61
 
6
- # µ-authorization
62
+ ## Installation
7
63
 
8
- Simple authorization library and role managment for Ruby.
64
+ Add the gem to your `Gemfile`:
9
65
 
10
- ## Prerequisites
66
+ ```ruby
67
+ gem 'u-authorization'
68
+ ```
11
69
 
12
- > Ruby >= 2.2.0
70
+ Then run `bundle install`. Or install it directly:
13
71
 
14
- ## Installation
72
+ ```bash
73
+ gem install u-authorization
74
+ ```
75
+
76
+ Require it (or let Bundler do it for you):
15
77
 
16
- Add this line to your application's Gemfile:
78
+ ```ruby
79
+ require 'u-authorization'
17
80
  ```
18
- gem 'u-authorization'
81
+
82
+ ## Supported versions
83
+
84
+ The gem requires Ruby `>= 2.7` and is tested on CI against Ruby 2.7 through the current development build. It has no runtime dependencies and works inside any Rails `>= 6.0` application, but it does not depend on Rails or ActiveModel, so you can use it in plain Ruby, Hanami, Sinatra, or a script.
85
+
86
+ ## Quick start
87
+
88
+ Here is a full example using `OpenStruct` to stand in for a user and a database record. It defines a role, a policy, builds an authorization object, and asks it questions.
89
+
90
+ ```ruby
91
+ require 'ostruct'
92
+ require 'u-authorization'
93
+
94
+ # 1. Roles are data. Map each feature to a rule.
95
+ module Permissions
96
+ ADMIN = {
97
+ 'visit' => { 'any' => true },
98
+ 'export' => { 'any' => true }
99
+ }
100
+
101
+ USER = {
102
+ 'visit' => { 'except' => ['billings'] },
103
+ 'export' => { 'except' => ['sales'] }
104
+ }
105
+
106
+ ALL = { 'admin' => ADMIN, 'user' => USER }
107
+
108
+ def self.to(role)
109
+ ALL.fetch(role, USER)
110
+ end
111
+ end
112
+
113
+ # 2. Policies are classes. Predicate methods return true or false.
114
+ class SalesPolicy < Micro::Authorization::Policy
115
+ def edit?(record)
116
+ user.id == record.user_id
117
+ end
118
+ end
119
+
120
+ user = OpenStruct.new(id: 1, role: 'user')
121
+
122
+ # 3. Build the authorization object for this request.
123
+ authorization = Micro::Authorization::Model.build(
124
+ permissions: Permissions.to(user.role),
125
+ policies: { default: :sales, sales: SalesPolicy },
126
+ context: {
127
+ user: user,
128
+ to_permit: ['dashboard', 'controllers', 'sales', 'index']
129
+ }
130
+ )
131
+
132
+ # 4a. Ask about feature permissions for the current context.
133
+ authorization.permissions.to?('visit') # => true
134
+ authorization.permissions.to?('export') # => false
135
+
136
+ # 4b. Ask the same feature about a different context.
137
+ can_export = authorization.permissions.to('export')
138
+ can_export.context?('billings') # => true
139
+ can_export.context?('sales') # => false
140
+
141
+ # 4c. Ask a policy about a record.
142
+ charge = OpenStruct.new(id: 2, user_id: user.id)
143
+
144
+ authorization.to(:sales).edit?(charge) # => true
145
+ authorization.policy.edit?(charge) # => true (uses the default policy)
146
+ ```
147
+
148
+ ## Permissions
149
+
150
+ A permission check answers one question: given a role and the context the request is happening in, is a feature allowed?
151
+
152
+ ### Roles are plain data
153
+
154
+ A role is a Hash whose keys are feature names and whose values are rules:
155
+
156
+ ```ruby
157
+ role = {
158
+ 'visit' => { 'only' => ['users'] },
159
+ 'export' => { 'only' => ['users.reports'] },
160
+ 'manage' => { 'any' => false }
161
+ }
162
+ ```
163
+
164
+ Because a role is plain data, it serializes cleanly. You can store roles as JSON in a database, edit them through an admin screen, and load them at runtime without touching code:
165
+
166
+ ```ruby
167
+ require 'json'
168
+
169
+ roles = JSON.parse(current_account.roles_json)
170
+ permissions = Micro::Authorization::Permissions.new(roles['user'], context: [])
171
+ ```
172
+
173
+ ### Permission rules
174
+
175
+ Each feature maps to one of these rules:
176
+
177
+ | Rule | Meaning |
178
+ | ----------------------- | ---------------------------------------------- |
179
+ | `true` | Allowed in every context. |
180
+ | `false` | Denied in every context. |
181
+ | missing key or `nil` | Denied. |
182
+ | `{ 'any' => true }` | Allowed in every context. |
183
+ | `{ 'any' => false }` | Denied in every context. |
184
+ | `{ 'only' => [...] }` | Allowed only in the listed contexts. |
185
+ | `{ 'except' => [...] }` | Allowed everywhere except the listed contexts. |
186
+
187
+ `{ 'any' => nil }` and any unrecognized key (for example `{ 'sometimes' => [...] }`) raise `NotImplementedError`, so a malformed role fails loudly instead of silently granting or denying access.
188
+
189
+ ### Context matching and dot notation
190
+
191
+ The context is an array of strings that describes where the request is happening. In a Rails controller that is usually `[controller_name, action_name]`, but it can be any list of identifiers. Matching is case insensitive; both the context and the rule values are downcased before comparison.
192
+
193
+ A single string in `only` or `except` matches when the context includes it:
194
+
195
+ ```ruby
196
+ role = { 'visit' => { 'only' => ['users'] } }
197
+ permissions = Micro::Authorization::Permissions.new(role, context: [])
198
+
199
+ permissions.to('visit').context?(['users']) # => true
200
+ permissions.to('visit').context?(['sales']) # => false
19
201
  ```
20
202
 
21
- And then execute:
203
+ A string with dots, such as `'users.reports'`, splits on the dot and requires every segment to be present in the context. Entries in the array are still combined with OR, so the rule means "users and reports, or any other listed entry":
204
+
205
+ ```ruby
206
+ role = { 'export' => { 'only' => ['users.reports'] } }
207
+ permissions = Micro::Authorization::Permissions.new(role, context: [])
208
+
209
+ permissions.to('export').context?(['users', 'reports']) # => true
210
+ permissions.to('export').context?(['users']) # => false
22
211
  ```
23
- $ bundle
212
+
213
+ ### Checking permissions
214
+
215
+ `Micro::Authorization::Permissions.new(role, context:)` returns a permissions model bound to a context. From there you have two ways to ask questions.
216
+
217
+ Use `to?` and `to_not?` to check a feature against the context the model was built with. Pass a single feature or an array, in which case every feature must be allowed:
218
+
219
+ ```ruby
220
+ role = { 'visit' => true, 'comment' => false }
221
+ permissions = Micro::Authorization::Permissions.new(role, context: ['sales', 'index'])
222
+
223
+ permissions.to?('visit') # => true
224
+ permissions.to?('comment') # => false
225
+ permissions.to?(['visit', 'comment']) # => false (comment is denied)
226
+ permissions.to_not?('comment') # => true
24
227
  ```
25
228
 
26
- Or install it yourself as:
229
+ Use `to(feature)` to get a checker you can test against any context with `context?`, regardless of the model's own context:
230
+
231
+ ```ruby
232
+ role = {
233
+ 'visit' => { 'any' => true },
234
+ 'comment' => { 'except' => ['sales'] }
235
+ }
236
+ permissions = Micro::Authorization::Permissions.new(role, context: ['sales', 'index'])
237
+
238
+ can_comment = permissions.to('comment')
239
+ can_comment.context?('invoices') # => true
240
+ can_comment.context?('sales') # => false
241
+
242
+ can_comment.features # => ['comment'] (the features this checker verifies)
243
+ ```
244
+
245
+ The model caches each `to?` result per feature, so repeated checks in the same request are cheap.
246
+
247
+ ### Multiple roles
248
+
249
+ Pass an array of roles to grant a user the union of their permissions. A feature is allowed when at least one role allows it:
250
+
251
+ ```ruby
252
+ analytics = { 'export' => { 'only' => ['reports'] } }
253
+ support = { 'export' => { 'only' => ['users.reports'] } }
254
+
255
+ permissions = Micro::Authorization::Permissions.new([analytics, support], context: [])
256
+
257
+ permissions.to('export').context?(['sales', 'reports']) # => true (granted by analytics)
258
+ permissions.to('export').context?(['users', 'reports']) # => true (granted by support)
259
+ ```
260
+
261
+ ## Policies
262
+
263
+ Permissions decide what a role can do in a place. Policies decide what a user can do to a record. A policy is a class with predicate methods, in the style of Pundit.
264
+
265
+ ### Defining a policy
266
+
267
+ Subclass `Micro::Authorization::Policy` and define methods that end in `?`. Inside a policy you can read `user` (an alias of `current_user`), `subject`, `context`, and `permissions`:
268
+
269
+ ```ruby
270
+ class CommentPolicy < Micro::Authorization::Policy
271
+ def edit?(comment)
272
+ user.id == comment.author_id
273
+ end
274
+ end
275
+
276
+ policy = CommentPolicy.new({ user: current_user })
277
+ policy.edit?(comment) # => true or false
278
+ ```
279
+
280
+ Any predicate method you have not defined returns `false`. Deny by default is the standard behavior, so a feature you forget to handle stays forbidden.
281
+
282
+ ```ruby
283
+ policy = Micro::Authorization::Policy.new({})
284
+
285
+ policy.index? # => false
286
+ policy.show?(record) # => false
27
287
  ```
28
- $ gem install u-authorization
288
+
289
+ Calling a method that does not end in `?` raises `NoMethodError`, so typos in real method names still surface.
290
+
291
+ Inside a policy, `current_user` reads `context[:user]` first, then falls back to `context[:current_user]`.
292
+
293
+ ### The subject
294
+
295
+ A policy can receive the record it is about in two ways. You can pass it as the second argument when constructing the policy, and read it through `subject`:
296
+
297
+ ```ruby
298
+ class RecordPolicy < Micro::Authorization::Policy
299
+ def show?
300
+ user.id == subject.user_id
301
+ end
302
+ end
303
+
304
+ RecordPolicy.new({ user: current_user }, record).show?
29
305
  ```
30
306
 
31
- ## Usage
307
+ Or you can pass it as an argument to the predicate method, which is handy when one policy instance answers questions about several records:
32
308
 
33
309
  ```ruby
34
- require 'ostruct'
35
- require 'u-authorization'
310
+ class RecordPolicy < Micro::Authorization::Policy
311
+ def show?(record)
312
+ user.id == record.user_id
313
+ end
314
+ end
36
315
 
37
- module Permissions
38
- ADMIN = {
39
- 'visit' => { 'any' => true },
40
- 'export' => { 'any' => true }
41
- }
316
+ policy = RecordPolicy.new({ user: current_user })
317
+ policy.show?(record_a) # => true
318
+ policy.show?(record_b) # => false
319
+ ```
42
320
 
43
- USER = {
44
- 'visit' => { 'except' => ['billings'] },
45
- 'export' => { 'except' => ['sales'] }
46
- }
321
+ ### Reading permissions inside a policy
47
322
 
48
- ALL = {
49
- 'admin' => ADMIN,
50
- 'user' => USER
51
- }
323
+ A policy can combine record-level checks with feature permissions. When the authorization object builds a policy it passes the permissions in, so `permissions` is available inside:
52
324
 
53
- def self.to(role)
54
- ALL.fetch(role, 'user')
55
- end
325
+ ```ruby
326
+ class ReportPolicy < Micro::Authorization::Policy
327
+ def show?(report)
328
+ permissions.to?('visit') && current_user.id == report.owner_id
56
329
  end
330
+ end
331
+ ```
332
+
333
+ ## The authorization object
334
+
335
+ `Micro::Authorization::Model` ties a user, a context, a role's permissions, and a set of policies into a single object for the current request.
336
+
337
+ ### Building it
338
+
339
+ Use `Model.build` with three keyword arguments. `policies` is optional:
340
+
341
+ ```ruby
342
+ authorization = Micro::Authorization::Model.build(
343
+ permissions: Permissions.to(user.role),
344
+ policies: { default: SalesPolicy, sales: SalesPolicy },
345
+ context: {
346
+ user: user,
347
+ to_permit: ['sales', 'index']
348
+ }
349
+ )
350
+ ```
351
+
352
+ The `context` Hash is read like this:
353
+
354
+ - `:to_permit` (or its alias `:permissions`) is the context used for permission checks. One of them is required if you want to check permissions.
355
+ - `:user` is the current user. It becomes `user` / `current_user` inside policies.
356
+ - Every other key stays in the context and is handed to policies, so a policy can read anything else you put there.
357
+
358
+ ### Asking about permissions
359
+
360
+ `authorization.permissions` returns the permissions model described above, so the full `to?`, `to_not?`, and `to(...).context?` interface is available:
361
+
362
+ ```ruby
363
+ authorization.permissions.to?('visit') # => true
364
+ authorization.permissions.to('export').context?('sales') # => false
365
+ ```
366
+
367
+ ### Fetching policies
368
+
369
+ `to(key, subject: nil)` looks up a registered policy by name, builds it with the current context and permissions, and returns the instance:
370
+
371
+ ```ruby
372
+ authorization.to(:sales).edit?(charge)
373
+ ```
374
+
375
+ `policy(key = :default, subject: nil)` does the same but defaults to the `:default` policy, which reads well when you have one main policy per request:
376
+
377
+ ```ruby
378
+ authorization.policy.edit?(charge) # uses :default
379
+ authorization.policy(:sales).edit?(charge) # same as to(:sales)
380
+ ```
381
+
382
+ If you ask for a key that was never registered, you get the base `Micro::Authorization::Policy`, which denies every predicate. Unknown features are forbidden rather than raising.
383
+
384
+ Policy instances are cached per key, so calling `to(:sales)` repeatedly returns the same object within a request. Passing a `subject:` builds a fresh instance bound to that subject:
57
385
 
58
- user = OpenStruct.new(id: 1, role: 'user')
386
+ ```ruby
387
+ authorization.to(:report, subject: report).show?
388
+ ```
389
+
390
+ ### Registering policies
391
+
392
+ You can register policies when building the object through the `policies:` keyword, or afterward with `add_policy` and `add_policies`:
393
+
394
+ ```ruby
395
+ authorization.add_policy(:sales, SalesPolicy)
396
+ authorization.add_policies(sales: SalesPolicy, report: ReportPolicy)
397
+ ```
398
+
399
+ `add_policies` expects a Hash and raises `ArgumentError` otherwise.
400
+
401
+ The `:default` key is special. It can hold a policy class, or a Symbol that points at another registered policy, so you can name one of your policies as the default:
402
+
403
+ ```ruby
404
+ Micro::Authorization::Model.build(
405
+ permissions: role,
406
+ policies: { default: :sales, sales: SalesPolicy },
407
+ context: { user: user }
408
+ )
409
+ ```
410
+
411
+ ### Cloning with map
412
+
413
+ `map` returns a new authorization object, replacing the context, the policies, or both. Whatever you leave out is carried over from the original, and the original is left untouched, which helps when one request needs to check several contexts:
414
+
415
+ ```ruby
416
+ on_releases = authorization.map(context: ['dashboard', 'releases', 'index'])
417
+
418
+ on_releases.permissions.to?('visit') # checked against the new context
419
+ authorization.equal?(on_releases) # => false
420
+
421
+ with_admin_policy = authorization.map(policies: { default: AdminPolicy })
422
+ ```
423
+
424
+ Calling `map` without `context:` or `policies:` raises `ArgumentError`, since there would be nothing to change.
59
425
 
60
- class SalesPolicy < Micro::Authorization::Policy
61
- def edit?(record)
62
- user.id == record.user_id
63
- end
426
+ ## Using it with Rails
427
+
428
+ The context maps naturally onto a Rails controller. Using `controller_path.split('/') + [action_name]` keeps namespaced controllers distinct, so `Admin::UsersController#index` becomes `['admin', 'users', 'index']`. A common setup builds the authorization object once per request and exposes a helper:
429
+
430
+ ```ruby
431
+ class ApplicationController < ActionController::Base
432
+ before_action :authenticate_user!
433
+
434
+ private
435
+
436
+ def authorization
437
+ @authorization ||= Micro::Authorization::Model.build(
438
+ permissions: current_user.role_permissions, # a Hash, maybe loaded from the DB
439
+ policies: { default: :record, record: RecordPolicy },
440
+ context: {
441
+ user: current_user,
442
+ to_permit: controller_path.split('/') + [action_name]
443
+ }
444
+ )
64
445
  end
65
446
 
66
- authorization = Micro::Authorization::Model.build(
67
- permissions: Permissions.to(user.role),
68
- policies: { default: :sales, sales: SalesPolicy },
69
- context: {
70
- user: user,
71
- to_permit: ['dashboard', 'controllers', 'sales', 'index']
72
- }
73
- )
447
+ def authorize_visit!
448
+ redirect_to root_path unless authorization.permissions.to?('visit')
449
+ end
450
+ end
451
+ ```
74
452
 
75
- # Info about the `context` data:
76
- # 1. :to_permit is a required key
77
- # 1.1. :permissions is an alternative of :to_permit key.
78
- # 2. :user is an optional key
79
- # 3. Any key different of :permissions, will be passed as a policy context.
453
+ ```ruby
454
+ class ReportsController < ApplicationController
455
+ before_action :authorize_visit!
80
456
 
81
- # Verifying the permissions for the given context
82
- authorization.permissions.to?('visit') #=> true
83
- authorization.permissions.to?('export') #=> false
457
+ def show
458
+ @report = Report.find(params[:id])
459
+ redirect_to reports_path unless authorization.policy.show?(@report)
460
+ end
461
+ end
462
+ ```
84
463
 
85
- # Verifying permission for a given feature in different contexts
86
- has_permission_to = authorization.permissions.to('export')
87
- has_permission_to.context?('billings') #=> true
88
- has_permission_to.context?('sales') #=> false
464
+ Because roles are data, `current_user.role_permissions` can come straight from a column or an associated table, which lets non-developers manage roles through your own admin tools.
89
465
 
90
- charge = OpenStruct.new(id: 2, user_id: user.id)
466
+ ## Comparison with Pundit and CanCanCan
91
467
 
92
- # The #to() method fetch and build a policy.
93
- authorization.to(:sales).edit?(charge) #=> true
468
+ All three gems solve authorization, with different shapes.
94
469
 
95
- # :default is the only permitted key to receive
96
- # another symbol as a value (a policy reference).
97
- authorization.to(:default).edit?(charge) #=> true
470
+ - [Pundit](https://github.com/varvet/pundit) is built around policy classes, one per resource. `u-authorization` has the same idea in its `Policy` layer, and adds a separate permissions layer for role and context checks. Pundit leaves roles to you.
471
+ - [CanCanCan](https://github.com/CanCanCommunity/cancancan) centralizes rules in one `Ability` class written in Ruby. `u-authorization` keeps role rules as data instead of code, so they can be stored and edited outside the codebase, and keeps record-level logic in policy classes.
98
472
 
99
- # #policy() method has a similar behavior of #to(),
100
- # but if there is a policy defined as ":default", it will be fetched and instantiated by default.
101
- authorization.policy.edit?(charge) #=> true
102
- authorization.policy(:sales).edit?(charge) #=> true
473
+ Reasons you might reach for `u-authorization`:
103
474
 
104
- # Cloning the authorization changing only its context.
105
- new_authorization = authorization.map(context: [
106
- 'dashboard', 'controllers', 'billings', 'index'
107
- ])
475
+ - You want roles defined as data (Hash or JSON) so they can live in a database and change without a deploy.
476
+ - You want permission checks that are aware of the controller and action, not only the model.
477
+ - You want a small library with no runtime dependencies.
478
+ - You want role and context checks and record-level checks to stay separate instead of merging into one concept.
108
479
 
109
- new_authorization.permissions.to?('visit') #=> false
480
+ If you only need record-level policies, Pundit is a fine and popular choice. If you prefer one central Ruby file of abilities, CanCanCan fits well.
110
481
 
111
- authorization.equal?(new_authorization) #=> false
482
+ ## Development
112
483
 
113
- #========================#
114
- # Multi role permissions #
115
- #========================#
484
+ After cloning the repository, install dependencies and set up the project:
116
485
 
117
- authorization = Micro::Authorization::Model.build(
118
- permissions: [Permissions::USER, Permissions::ADMIN], # An array of permissions
119
- policies: { default: :sales, sales: SalesPolicy },
120
- context: {
121
- user: user,
122
- to_permit: ['dashboard', 'controllers', 'sales', 'index']
123
- }
124
- )
486
+ ```bash
487
+ bin/setup
488
+ ```
125
489
 
126
- authorization.permissions.to?('visit') #=> true
127
- authorization.permissions.to?('export') #=> true
490
+ Run the test suite, which is the default Rake task:
128
491
 
129
- has_permission_to = authorization.permissions.to('export')
130
- has_permission_to.context?('billings') #=> true
131
- has_permission_to.context?('sales') #=> true
492
+ ```bash
493
+ bundle exec rake test
494
+ # or simply
495
+ bundle exec rake
132
496
  ```
133
497
 
134
- ## Original implementation
498
+ Open a console with the gem loaded to experiment:
499
+
500
+ ```bash
501
+ bin/console
502
+ ```
503
+
504
+ To run the suite across Ruby versions locally, use [mise](https://mise.jdx.dev). The `.tool-versions` file pins the project's default Ruby; add the versions you want to cover and run the suite under each. CI runs the full matrix, from Ruby 2.7 through the current development build, defined in `.github/workflows/ci.yml`.
505
+
506
+ ## Contributing
507
+
508
+ Bug reports and pull requests are welcome on GitHub at https://github.com/u-gems/u-authorization. Please add or update tests for any behavior you change; the test suite is the contract for the public API.
509
+
510
+ 1. Fork the repository.
511
+ 2. Create your feature branch (`git checkout -b my-new-feature`).
512
+ 3. Add tests and make them pass with `bundle exec rake test`.
513
+ 4. Commit your changes and open a pull request.
514
+
515
+ Everyone interacting in the project's codebases and issue trackers is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).
516
+
517
+ ## License
518
+
519
+ The gem is available as open source under the terms of the [MIT License](LICENSE.txt).
520
+
521
+ ## Code of conduct
135
522
 
136
- https://gist.github.com/serradura/7d51b979b90609d8601d0f416a9aa373
523
+ Everyone interacting in the µ-authorization project is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "u-authorization"
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(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ rm -f Gemfile.lock
7
+
8
+ bundle install
9
+
10
+ # Do any other automated setup that you need to do here
@@ -50,10 +50,10 @@ module Micro
50
50
 
51
51
  def add_policies(new_policies)
52
52
  unless new_policies.is_a?(Hash)
53
- raise ArgumentError, "policies must be a Hash (key => #{Policy.name})"
53
+ raise ArgumentError, "policies must be a Hash. e.g: `{policy_name: #{Policy.name}}`"
54
54
  end
55
55
 
56
- new_policies.each(&method(:add_policy))
56
+ new_policies.each { |key, policy_klass| add_policy(key, policy_klass) }
57
57
 
58
58
  self
59
59
  end