simple_auth 3.1.3 โ†’ 3.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b1d2a68a9455a5f601c57c8f98d70af46795e492f084815a9f2f1f929591d3b0
4
- data.tar.gz: 0f0cb2fec8e43e8d2c00970618bb120b9914d4c2ffe113b93038bacec2d8c4d4
3
+ metadata.gz: 767e5c4765e914fc1e310fe57f9ad0491ccfc7f3eff8b22c0002877bb4ddb262
4
+ data.tar.gz: f2ffea82bbf55a41c705bddb67b638f7df1cfb1f4abc1918c4d89d7b46bde019
5
5
  SHA512:
6
- metadata.gz: 38930354c31b9b9b43970e0efc9d7ae0a71b643702fd8f37b46527a811e30174f32a31e339225d56f3c08175b7e96d24dc9baa764622bc2ad1b6bd27538d0e3d
7
- data.tar.gz: 80715edb98f53b659ca8a95cdda946863da7eb25e4310398621f0fffc24e4becbe0d78e2c9c412a06972a765bbc448a2ecfbf064abac0a10da7fe0b41bd607c1
6
+ metadata.gz: b1489bc14e6f5b787902ad3540e7236e1112a71939f192cdf2e100af5ce0ca302794200e307c517334ef8fe42ec87ade787cfb609f96c6cee91093431741a103
7
+ data.tar.gz: fe1ee4d957ac0a892cedd74efbc7a0f671f1d9adeb6a11f268fc9d4cba7e8a45aac9d8b9a1c68798dde41dd17fb7c3f6ba71062c63320a12635816855016fa1d
@@ -0,0 +1,4 @@
1
+ # You can read more about CODEOWNERS at
2
+ # https://help.github.com/github/creating-cloning-and-archiving-repositories/about-code-owners
3
+
4
+ * @fnando
@@ -0,0 +1,4 @@
1
+ # These are supported funding model platforms
2
+ ---
3
+ github: [fnando]
4
+ custom: ["https://paypal.me/nandovieira/๐Ÿ•"]
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: "๐Ÿ› Bug Report"
3
+ about: Report a reproducible bug or regression.
4
+ title: 'Bug: '
5
+ labels: 'Status: Unconfirmed'
6
+
7
+ ---
8
+
9
+ <!--
10
+ - Please provide a clear and concise description of what the bug is.
11
+ - If possible, add an example reproducing your issue.
12
+ - Please test using the latest version of simple_auth
13
+ to make sure your issue has not already been fixed.
14
+ -->
15
+
16
+ ## Description
17
+
18
+ [Add bug description here]
19
+
20
+ ## How to reproduce
21
+
22
+ [Add steps on how to reproduce this issue]
23
+
24
+ ## What do you expect
25
+
26
+ [Describe what do you expect to happen]
27
+
28
+ ## What happened instead
29
+
30
+ [Describe the actual results]
31
+
32
+ ## Software:
33
+
34
+ - Gem version: [Add gem version here]
35
+ - Ruby version: [Add version here]
36
+
37
+ ## Full backtrace
38
+
39
+ ```text
40
+ [Paste full backtrace here]
41
+ ```
@@ -0,0 +1,5 @@
1
+ ---
2
+ contact_links:
3
+ - name: "๐Ÿคจ Q&A"
4
+ url: https://github.com/fnando/simple_auth/discussions/new?category=q-a
5
+ about: Have a question? Ask it away here!
@@ -0,0 +1,23 @@
1
+ ---
2
+ name: "๐Ÿ’ก Feature request"
3
+ about: Have an idea that may be useful? Make a suggestion!
4
+ title: 'Feature Request: '
5
+ labels: 'Feature request'
6
+
7
+ ---
8
+
9
+ ## Description
10
+
11
+ _A clear and concise description of what the problem is._
12
+
13
+ ## Describe the solution
14
+
15
+ _A clear and concise description of what you want to happen._
16
+
17
+ ## Alternatives you considered
18
+
19
+ _A clear and concise description of any alternative solutions or features you've considered._
20
+
21
+ ## Additional context
22
+
23
+ _Add any other context, screenshots, links, etc about the feature request here._
@@ -0,0 +1,38 @@
1
+ <!--
2
+ If you're making a doc PR or something tiny where the below is irrelevant,
3
+ delete this template and use a short description, but in your description aim to
4
+ include both what the change is, and why it is being made, with enough context
5
+ for anyone to understand.
6
+ -->
7
+
8
+ <details>
9
+ <summary>PR Checklist</summary>
10
+
11
+ ### PR Structure
12
+
13
+ - [ ] This PR has reasonably narrow scope (if not, break it down into smaller
14
+ PRs).
15
+ - [ ] This PR avoids mixing refactoring changes with feature changes (split into
16
+ two PRs otherwise).
17
+ - [ ] This PR's title starts is concise and descriptive.
18
+
19
+ ### Thoroughness
20
+
21
+ - [ ] This PR adds tests for the most critical parts of the new functionality or
22
+ fixes.
23
+ - [ ] I've updated any docs, `.md` files, etcโ€ฆ affected by this change.
24
+
25
+ </details>
26
+
27
+ ### What
28
+
29
+ [TODO: Short statement about what is changing.]
30
+
31
+ ### Why
32
+
33
+ [TODO: Why this change is being made. Include any context required to understand
34
+ the why.]
35
+
36
+ ### Known limitations
37
+
38
+ [TODO or N/A]
@@ -0,0 +1,15 @@
1
+ ---
2
+ # Documentation:
3
+ # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
4
+
5
+ version: 2
6
+ updates:
7
+ - package-ecosystem: "github-actions"
8
+ directory: "/"
9
+ schedule:
10
+ interval: "daily"
11
+
12
+ - package-ecosystem: bundler
13
+ directory: "/"
14
+ schedule:
15
+ interval: "daily"
@@ -0,0 +1,69 @@
1
+ ---
2
+ name: ruby-tests
3
+
4
+ on:
5
+ pull_request_target:
6
+ push:
7
+ branches:
8
+ - main
9
+ workflow_dispatch:
10
+ inputs: {}
11
+
12
+ jobs:
13
+ build:
14
+ name: Tests with Ruby ${{ matrix.ruby }} and ${{ matrix.gemfile }}
15
+ runs-on: "ubuntu-latest"
16
+ if: |
17
+ github.actor == 'dependabot[bot]' && github.event_name == 'pull_request_target' ||
18
+ github.actor != 'dependabot[bot]'
19
+ strategy:
20
+ fail-fast: false
21
+ matrix:
22
+ ruby: ["3.3", "3.4", "4.0"]
23
+ gemfile:
24
+ - Gemfile
25
+ - gemfiles/rails_8_0.gemfile
26
+ - gemfiles/rails_8_1.gemfile
27
+
28
+ services:
29
+ postgres:
30
+ image: postgres:11.5
31
+ ports: ["5432:5432"]
32
+ options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
33
+
34
+ steps:
35
+ - uses: actions/checkout@v4
36
+
37
+ - uses: actions/cache@v3
38
+ with:
39
+ path: vendor/bundle
40
+ key: >
41
+ ${{ runner.os }}-${{ matrix.ruby }}-gems-${{ hashFiles(matrix.gemfile) }} #magic___^_^___line
42
+ - name: Set up Ruby
43
+ uses: ruby/setup-ruby@v1
44
+ with:
45
+ ruby-version: ${{ matrix.ruby }}
46
+
47
+ - name: Install PostgreSQL client
48
+ env:
49
+ PGHOST: localhost
50
+ PGUSER: postgres
51
+ run: |
52
+ sudo apt-get -yqq install libpq-dev
53
+ psql -U postgres -c "create database test"
54
+
55
+ - name: Install gem dependencies
56
+ env:
57
+ BUNDLE_GEMFILE: ${{ matrix.gemfile }}
58
+ run: |
59
+ gem install bundler
60
+ bundle config path vendor/bundle
61
+ bundle update --jobs 4 --retry 3
62
+
63
+ - name: Run Tests
64
+ env:
65
+ BUNDLE_GEMFILE: ${{ matrix.gemfile }}
66
+ PGHOST: localhost
67
+ PGUSER: postgres
68
+ run: |
69
+ bundle exec rake
data/.rubocop.yml CHANGED
@@ -3,7 +3,11 @@ inherit_gem:
3
3
  rubocop-fnando: .rubocop.yml
4
4
 
5
5
  AllCops:
6
- TargetRubyVersion: 2.6
6
+ TargetRubyVersion: 3.3
7
+ NewCops: enable
8
+ Exclude:
9
+ - gemfiles/**/*
10
+ - vendor/**/*
7
11
 
8
- Metrics/AbcSize:
12
+ Minitest/EmptyLineBeforeAssertionMethods:
9
13
  Enabled: false
data/CHANGELOG.md CHANGED
@@ -1,45 +1,56 @@
1
- # v3.1.3
1
+ # Changelog
2
+
3
+ ## v3.2.0
4
+
5
+ - Bump up ruby requirement to 3.3.
6
+ - Add support for ActionController::API
7
+
8
+ ## v3.1.4
9
+
10
+ - Add `authenticate(scope, condition, &block)`, so you can restrict routes
11
+ directly from the routes definition.
12
+
13
+ ## v3.1.3
2
14
 
3
15
  - Remove session[:return_to] after using it.
4
16
 
5
- # v3.1.2
17
+ ## v3.1.2
6
18
 
7
19
  - Make flash message key configurable via
8
20
  `SimpleAuth::Config#flash_message_key`.
9
21
 
10
- # v3.1.1
22
+ ## v3.1.1
11
23
 
12
24
  - Catch exceptions related to record not found when session tries to load a
13
25
  record from session. You can customize the recognized exceptions by adding the
14
26
  error class to `SimpleAuth::Session.record_not_found_exceptions`.
15
27
 
16
- # v3.1.0
28
+ ## v3.1.0
17
29
 
18
30
  - SimpleAuth now uses [GlobalID](https://github.com/rails/globalid) as the
19
31
  identification that's saved on the session. This should be a seamless
20
32
  migration (users will only have to re-login). This allows using any objects
21
33
  that respond to `#to_gid`, including namespaced models and POROs.
22
34
 
23
- # v3.0.0
35
+ ## v3.0.0
24
36
 
25
37
  - Reimplemented library.
26
38
  - Add support for scoped authentication (e.g. user and admin).
27
39
 
28
- # v2.0.3
40
+ ## v2.0.3
29
41
 
30
42
  - Assign the raw password/confirmation, so we can apply validations on the raw
31
43
  value.
32
44
 
33
- # v2.0.2
45
+ ## v2.0.2
34
46
 
35
47
  - The compat wasn't validating fields correctly.
36
48
 
37
- # v2.0.1
49
+ ## v2.0.1
38
50
 
39
51
  - The compat mode wasn't generating the `password_digest`.
40
52
 
41
- # v2.0.0
53
+ ## v2.0.0
42
54
 
43
- - Released version 2.0.0. This version removes support for MongoDB
44
- and switches to `has_secure_password` encryption method. This
45
- change requires Rails 3.1.0+.
55
+ - Released version 2.0.0. This version removes support for MongoDB and switches
56
+ to `has_secure_password` encryption method. This change requires Rails 3.1.0+.
@@ -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 me@fnando.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 [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ (The MIT License)
2
+
3
+ Copyright (c) 2010 Nando Vieira
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the 'Software'), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ 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, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md CHANGED
@@ -1,10 +1,9 @@
1
1
  # Simple Auth
2
2
 
3
- [![Travis-CI](https://travis-ci.org/fnando/simple_auth.svg)](https://travis-ci.org/fnando/simple_auth)
4
- [![Code Climate](https://codeclimate.com/github/fnando/simple_auth/badges/gpa.svg)](https://codeclimate.com/github/fnando/simple_auth)
5
- [![Test Coverage](https://codeclimate.com/github/fnando/simple_auth/badges/coverage.svg)](https://codeclimate.com/github/fnando/simple_auth/coverage)
3
+ [![Tests](https://github.com/fnando/simple_auth/workflows/ruby-tests/badge.svg)](https://github.com/fnando/simple_auth)
6
4
  [![Gem](https://img.shields.io/gem/v/simple_auth.svg)](https://rubygems.org/gems/simple_auth)
7
5
  [![Gem](https://img.shields.io/gem/dt/simple_auth.svg)](https://rubygems.org/gems/simple_auth)
6
+ [![MIT License](https://img.shields.io/:License-MIT-blue.svg)](https://tldrlegal.com/license/mit-license)
8
7
 
9
8
  SimpleAuth is an authentication library to be used when everything else is just
10
9
  too complicated.
@@ -136,16 +135,80 @@ current_#{scope} # e.g. current_user (available in controller & views)
136
135
  #{scope}_session # e.g. user_session (available in controller & views)
137
136
  ```
138
137
 
138
+ #### From your routes file
139
+
140
+ You can also restrict routes directly from your routes:
141
+
142
+ ```ruby
143
+ Rails.application.routes.draw do
144
+ authenticate :admin, ->(user) { user.admin? } do
145
+ mount Sidekiq::Web, at: "sidekiq"
146
+ end
147
+ end
148
+ ```
149
+
150
+ In this case, `:admin` is the scope and the lambda will only be called whenever
151
+ there's a valid record associated with that record.
152
+
153
+ ### API Controllers
154
+
155
+ simple_auth supports `ActionController::API`-based controllers. Include the
156
+ `SimpleAuth::ActionController::API` module in your API controller:
157
+
158
+ ```ruby
159
+ class ApiController < ActionController::API
160
+ include SimpleAuth::ActionController::API
161
+
162
+ before_action :authenticate_via_token
163
+ before_action :require_logged_user
164
+
165
+ def index
166
+ render json: {message: "hello there"}
167
+ end
168
+
169
+ private def authenticate_via_token
170
+ user = User.find_by_api_token(id: request.headers["Authorization"])
171
+
172
+ return render(plain: "401 Unauthorized", status: :unauthorized) unless user
173
+
174
+ SimpleAuth::Session.create(scope: "user", session:, record: user)
175
+ end
176
+ end
177
+ ```
178
+
179
+ By default, unauthorized requests receive a `401 Unauthorized` plain text
180
+ response. You can override `render_unauthorized_access(authorization)` to
181
+ customize this behavior. The `authorization` object gives you access to
182
+ `authorization.error_message`, which contains the translated error message for
183
+ the failed authorization:
184
+
185
+ ```ruby
186
+ class ApiController < ActionController::API
187
+ include SimpleAuth::ActionController::API
188
+
189
+ private def render_unauthorized_access(authorization)
190
+ render json: {error: authorization.error_message}, status: :unauthorized
191
+ end
192
+ end
193
+ ```
194
+
195
+ > [!NOTE]
196
+ >
197
+ > `SimpleAuth::ActionController::API` defines a stub session object that's just
198
+ > a hash, so the user record can be resolved across multiple calls within the
199
+ > same request.
200
+
139
201
  ### Translations
140
202
 
141
203
  These are the translations you'll need:
142
204
 
143
205
  ```yaml
206
+ ---
144
207
  en:
145
208
  simple_auth:
146
209
  user:
147
- need_to_be_logged_in: "You need to be logged in"
148
- not_authorized: "You don't have permission to access this page"
210
+ unlogged_in: "You need to be logged in"
211
+ unauthorized: "You don't have permission to access this page"
149
212
  ```
150
213
 
151
214
  If you don't set these translations, a default message will be used.
@@ -154,6 +217,7 @@ To display the error message, use something like `<%= flash[:alert] %>`. If you
154
217
  want to use a custom key, say `:error`, use the configuration file
155
218
  `config/initializers/simple_auth.rb` to define the new key:
156
219
 
220
+ ```ruby
157
221
  # config/initializers/simple_auth.rb
158
222
  SimpleAuth.setup do |config|
159
223
  # ...
@@ -166,27 +230,25 @@ end
166
230
 
167
231
  ## Maintainer
168
232
 
169
- * Nando Vieira (<http://nandovieira.com>)
233
+ - [Nando Vieira](https://github.com/fnando)
234
+
235
+ ## Contributors
236
+
237
+ - https://github.com/fnando/simple_auth/contributors
238
+
239
+ ## Contributing
170
240
 
171
- ## License:
241
+ For more details about how to contribute, please read
242
+ https://github.com/fnando/simple_auth/blob/main/CONTRIBUTING.md.
172
243
 
173
- (The MIT License)
244
+ ## License
174
245
 
175
- Permission is hereby granted, free of charge, to any person obtaining
176
- a copy of this software and associated documentation files (the
177
- 'Software'), to deal in the Software without restriction, including
178
- without limitation the rights to use, copy, modify, merge, publish,
179
- distribute, sublicense, and/or sell copies of the Software, and to
180
- permit persons to whom the Software is furnished to do so, subject to
181
- the following conditions:
246
+ The gem is available as open source under the terms of the
247
+ [MIT License](https://opensource.org/licenses/MIT). A copy of the license can be
248
+ found at https://github.com/fnando/simple_auth/blob/main/LICENSE.md.
182
249
 
183
- The above copyright notice and this permission notice shall be
184
- included in all copies or substantial portions of the Software.
250
+ ## Code of Conduct
185
251
 
186
- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
187
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
188
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
189
- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
190
- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
191
- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
192
- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
252
+ Everyone interacting in the simple_auth project's codebases, issue trackers,
253
+ chat rooms and mailing lists is expected to follow the
254
+ [code of conduct](https://github.com/fnando/simple_auth/blob/main/CODE_OF_CONDUCT.md).
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+ gemspec path: ".."
5
+
6
+ gem "rails", "~> 6.1.0"
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+ gemspec path: ".."
5
+
6
+ gem "rails", "~> 7.0.0"
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+ gemspec path: ".."
5
+
6
+ gem "rails", "~> 8.0.0"
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+ gemspec path: ".."
5
+
6
+ gem "rails", "~> 8.1.0"
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleAuth
4
+ module ActionController
5
+ module API
6
+ extend ActiveSupport::Concern
7
+ include SimpleAuth::ActionController
8
+
9
+ included do
10
+ undef_method :simple_auth_redirect_logged_scope
11
+ undef_method :return_to
12
+
13
+ SimpleAuth.config.scopes.each do |scope|
14
+ undef_method :"redirect_logged_#{scope}"
15
+ end
16
+ end
17
+
18
+ # A stub session so we can persist the record id between different calls
19
+ # to fetch the record.
20
+ private def session
21
+ @session ||= {}
22
+ end
23
+
24
+ private def render_unauthorized_access(*)
25
+ render plain: "401 Unauthorized", status: :unauthorized
26
+ end
27
+ end
28
+ end
29
+ end
@@ -18,7 +18,7 @@ module SimpleAuth
18
18
  valid_session? && authorized?
19
19
  end
20
20
 
21
- def message
21
+ def error_message
22
22
  return if valid?
23
23
  return unauthorized_message unless authorized?
24
24
 
@@ -26,11 +26,11 @@ module SimpleAuth
26
26
  end
27
27
 
28
28
  private def valid_session?
29
- controller.send("#{scope}_session").valid?
29
+ controller.send(:"#{scope}_session").valid?
30
30
  end
31
31
 
32
32
  private def authorized?
33
- controller.send("authorized_#{scope}?")
33
+ controller.send(:"authorized_#{scope}?")
34
34
  end
35
35
 
36
36
  private def unauthorized_message
@@ -12,34 +12,46 @@ module SimpleAuth
12
12
  def install_simple_auth_scopes
13
13
  SimpleAuth.config.scopes.each do |scope|
14
14
  install_simple_auth_scope(scope)
15
- helper_method "current_#{scope}", "#{scope}_logged_in?"
15
+
16
+ if respond_to?(:helper_method)
17
+ helper_method("current_#{scope}", "#{scope}_logged_in?")
18
+ end
16
19
  end
17
20
  end
18
21
 
19
- def install_simple_auth_scope(scope) # rubocop:disable Metrics/MethodLength
22
+ def install_simple_auth_scope(scope)
20
23
  class_eval <<-RUBY, __FILE__, __LINE__ + 1
24
+ # def user_session
25
+ # @user_session ||= Session.create(scope: :user, session: session)
26
+ # end
21
27
  def #{scope}_session
22
28
  @#{scope}_session ||= Session.create(scope: :#{scope}, session: session)
23
29
  end
24
30
 
31
+ # def current_user
32
+ # user_session.record
33
+ # end
25
34
  def current_#{scope}
26
35
  #{scope}_session.record
27
36
  end
28
37
 
38
+ # def user_logged_in?
39
+ # current_user.present?
40
+ # end
29
41
  def #{scope}_logged_in?
30
42
  current_#{scope}.present?
31
43
  end
32
44
  RUBY
33
45
 
34
- define_method "authorized_#{scope}?" do
46
+ define_method :"authorized_#{scope}?" do
35
47
  true
36
48
  end
37
49
 
38
- define_method "require_logged_#{scope}" do
50
+ define_method :"require_logged_#{scope}" do
39
51
  simple_auth_require_logged_scope(scope)
40
52
  end
41
53
 
42
- define_method "redirect_logged_#{scope}" do
54
+ define_method :"redirect_logged_#{scope}" do
43
55
  simple_auth_redirect_logged_scope(scope)
44
56
  end
45
57
  end
@@ -54,21 +66,25 @@ module SimpleAuth
54
66
  end
55
67
 
56
68
  private def simple_auth_require_logged_scope(scope)
57
- action = RequireLoginAction.new(self, scope)
69
+ authorization = RequireLoginAction.new(self, scope)
58
70
 
59
- return if action.valid?
71
+ return if authorization.valid?
60
72
 
61
- reset_session
62
- flash[simple_auth.flash_message_key] = action.message
63
- session[:return_to] = request.fullpath if request.get?
64
- redirect_to instance_eval(&simple_auth.login_url)
73
+ render_unauthorized_access(authorization)
65
74
  end
66
75
 
67
76
  private def simple_auth_redirect_logged_scope(scope)
68
- scope_session = send("#{scope}_session")
77
+ scope_session = send(:"#{scope}_session")
69
78
  return unless scope_session.valid?
70
79
 
71
80
  redirect_to instance_eval(&simple_auth.logged_url)
72
81
  end
82
+
83
+ private def render_unauthorized_access(authorization)
84
+ reset_session
85
+ flash[simple_auth.flash_message_key] = authorization.error_message
86
+ session[:return_to] = request.fullpath if request.get?
87
+ redirect_to instance_eval(&simple_auth.login_url)
88
+ end
73
89
  end
74
90
  end
@@ -22,6 +22,7 @@ module SimpleAuth
22
22
 
23
23
  def install_helpers!
24
24
  ::ActionController::Base.include SimpleAuth::ActionController
25
+ ::ActionController::API.include SimpleAuth::ActionController::API
25
26
  end
26
27
  end
27
28
  end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleAuth
4
+ module RoutingMapper
5
+ class Matcher
6
+ attr_reader :scope, :condition
7
+
8
+ def initialize(scope:, condition:)
9
+ @scope = scope
10
+ @condition = condition
11
+ end
12
+
13
+ def call(request)
14
+ session = Session.create(scope: scope, session: request.session)
15
+ record = session.record
16
+
17
+ record && condition.call(record)
18
+ end
19
+ end
20
+
21
+ def authenticate(scope, condition, &block)
22
+ with_options(
23
+ constraints: Matcher.new(scope: scope, condition: condition)
24
+ ) do
25
+ instance_eval(&block)
26
+ end
27
+ end
28
+ end
29
+ end
@@ -6,8 +6,8 @@ module SimpleAuth
6
6
  @record_not_found_exceptions ||= []
7
7
  end
8
8
 
9
- def self.create(**kwargs)
10
- new(**kwargs)
9
+ def self.create(**)
10
+ new(**)
11
11
  end
12
12
 
13
13
  def initialize(scope:, session:, record: nil)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SimpleAuth
4
- VERSION = "3.1.3"
4
+ VERSION = "3.2.0"
5
5
  end
data/lib/simple_auth.rb CHANGED
@@ -4,15 +4,20 @@ module SimpleAuth
4
4
  require "rails/railtie"
5
5
  require "global_id/railtie"
6
6
  require "active_support/concern"
7
+ require "action_dispatch/routing/mapper"
7
8
 
8
9
  require "simple_auth/version"
9
10
  require "simple_auth/config"
10
11
  require "simple_auth/railtie"
11
12
  require "simple_auth/action_controller"
13
+ require "simple_auth/action_controller/api"
14
+ require "simple_auth/routing_mapper"
12
15
  require "simple_auth/action_controller/require_login_action"
13
16
  require "simple_auth/session"
14
17
  require "simple_auth/generator"
15
18
 
19
+ ::ActionDispatch::Routing::Mapper.prepend SimpleAuth::RoutingMapper
20
+
16
21
  def self.setup
17
22
  yield config
18
23
  end
data/simple_auth.gemspec CHANGED
@@ -11,9 +11,20 @@ Gem::Specification.new do |s|
11
11
  s.homepage = "http://rubygems.org/gems/simple_auth"
12
12
  s.summary = "A simple authentication system for Rails apps"
13
13
  s.description = s.summary
14
+ s.required_ruby_version = Gem::Requirement.new(">= 3.3.0")
15
+
16
+ github_url = "https://github.com/fnando/simple_auth"
17
+ github_tree_url = "#{github_url}/tree/v#{s.version}"
18
+
19
+ s.metadata["homepage_uri"] = s.homepage
20
+ s.metadata["bug_tracker_uri"] = "#{github_url}/issues"
21
+ s.metadata["source_code_uri"] = github_tree_url
22
+ s.metadata["changelog_uri"] = "#{github_tree_url}/CHANGELOG.md"
23
+ s.metadata["documentation_uri"] = "#{github_tree_url}/README.md"
24
+ s.metadata["license_uri"] = "#{github_tree_url}/LICENSE.md"
25
+ s.metadata["rubygems_mfa_required"] = "true"
14
26
 
15
27
  s.files = `git ls-files`.split("\n")
16
- s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
17
28
  s.executables = `git ls-files -- bin/*`
18
29
  .split("\n")
19
30
  .map {|f| File.basename(f) }
@@ -22,7 +33,7 @@ Gem::Specification.new do |s|
22
33
  s.add_dependency "globalid"
23
34
  s.add_dependency "rails"
24
35
  s.add_development_dependency "activerecord"
25
- s.add_development_dependency "bcrypt", "~> 3.1.7"
36
+ s.add_development_dependency "bcrypt"
26
37
  s.add_development_dependency "minitest"
27
38
  s.add_development_dependency "minitest-utils"
28
39
  s.add_development_dependency "pry-meta"
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "test_helper"
4
+
5
+ class ApiControllerTest < ActionController::TestCase
6
+ setup do
7
+ @routes = Rails.application.routes
8
+ User.delete_all
9
+ end
10
+
11
+ def create_records
12
+ admin = User.create!(
13
+ password: "test",
14
+ email: "admin@example.com",
15
+ admin: true
16
+ )
17
+ user = User.create!(
18
+ password: "test",
19
+ email: "john@example.com",
20
+ admin: false
21
+ )
22
+
23
+ [admin, user]
24
+ end
25
+
26
+ test "renders unauthorized for invalid api keys" do
27
+ get :index
28
+
29
+ assert_equal 401, response.status
30
+ assert_equal "401 Unauthorized", response.body
31
+ end
32
+
33
+ test "renders unauthorized for unauthorized users" do
34
+ _, user = *create_records
35
+ @request.headers["Authorization"] = user.id.to_s
36
+ get :index
37
+
38
+ assert_equal 401, response.status
39
+ assert_equal "401 Unauthorized", response.body
40
+ end
41
+
42
+ test "renders page for authorized users" do
43
+ admin, _ = *create_records
44
+ @request.headers["Authorization"] = admin.id.to_s
45
+ get :index
46
+
47
+ assert_equal 200, response.status
48
+ assert_equal %[{"message":"hello there"}], response.body
49
+ end
50
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "test_helper"
4
+
5
+ class AdminTest < ActionDispatch::IntegrationTest
6
+ setup do
7
+ User.delete_all
8
+ end
9
+
10
+ def create_records
11
+ admin = User.create!(
12
+ password: "test",
13
+ email: "admin@example.com",
14
+ admin: true
15
+ )
16
+ user = User.create!(
17
+ password: "test",
18
+ email: "john@example.com",
19
+ admin: false
20
+ )
21
+
22
+ [admin, user]
23
+ end
24
+
25
+ test "allows users with admin flag to access page" do
26
+ admin, _ = *create_records
27
+
28
+ get "/only/admins"
29
+ assert_equal 404, response.status
30
+
31
+ get "/only/admins-by-email"
32
+ assert_equal 404, response.status
33
+
34
+ post "/start-session", params: {scope: "admin", id: admin.id}
35
+ assert_equal 200, response.status
36
+
37
+ get "/only/admins"
38
+ assert_equal 200, response.status
39
+
40
+ get "/only/admins-by-email"
41
+ assert_equal 404, response.status
42
+ end
43
+
44
+ test "allows users with admin email to access page" do
45
+ admin, _ = *create_records
46
+
47
+ get "/only/admins"
48
+ assert_equal 404, response.status
49
+
50
+ get "/only/admins-by-email"
51
+ assert_equal 404, response.status
52
+
53
+ post "/start-session", params: {scope: "user", id: admin.id}
54
+ assert_equal 200, response.status
55
+
56
+ get "/only/admins"
57
+ assert_equal 404, response.status
58
+
59
+ get "/only/admins-by-email"
60
+ assert_equal 200, response.status
61
+ end
62
+
63
+ test "rejects users with non admin email" do
64
+ _, user = *create_records
65
+
66
+ get "/only/admins"
67
+ assert_equal 404, response.status
68
+
69
+ get "/only/admins-by-email"
70
+ assert_equal 404, response.status
71
+
72
+ post "/start-session", params: {scope: "user", id: user.id}
73
+ assert_equal 200, response.status
74
+
75
+ get "/only/admins"
76
+ assert_equal 404, response.status
77
+
78
+ get "/only/admins-by-email"
79
+ assert_equal 404, response.status
80
+ end
81
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ class ApiController < ActionController::API
4
+ include SimpleAuth::ActionController::API
5
+
6
+ before_action :validate_api_key
7
+ before_action :require_logged_user
8
+
9
+ def index
10
+ render json: {message: "hello there"}
11
+ end
12
+
13
+ private def authorized_user?
14
+ current_user&.admin?
15
+ end
16
+
17
+ private def validate_api_key
18
+ id = request.headers["Authorization"]
19
+ user = User.find_by(id:)
20
+
21
+ return render(plain: "401 Unauthorized", status: :unauthorized) unless user
22
+
23
+ SimpleAuth::Session.create(
24
+ scope: "user",
25
+ session:,
26
+ record: User.find_by(id:)
27
+ )
28
+ end
29
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ class SessionsController < ApplicationController
4
+ def create_session
5
+ session["#{params[:scope]}_id"] = User.find(params[:id]).to_gid.to_s
6
+ render plain: "", status: 200
7
+ end
8
+
9
+ def terminate_session
10
+ reset_session
11
+ render plain: "", status: 200
12
+ end
13
+ end
@@ -5,6 +5,17 @@ Rails.application.routes.draw do
5
5
  get "/admin/dashboard", to: "admin/dashboard#index"
6
6
  get "/login", to: "sessions#new"
7
7
 
8
+ post "/start-session", to: "sessions#create_session"
9
+ post "/terminate-session", to: "sessions#terminate_session"
10
+
11
+ authenticate :admin, lambda(&:admin?) do
12
+ get "/only/admins", to: ->(_env) { [200, {}, ["OK"]] }
13
+ end
14
+
15
+ authenticate :user, ->(u) { u.email == "admin@example.com" } do
16
+ get "only/admins-by-email", to: ->(_env) { [200, {}, ["OK"]] }
17
+ end
18
+
8
19
  controller :dashboard do
9
20
  get :log_in
10
21
  get :not_logged
@@ -24,4 +35,6 @@ Rails.application.routes.draw do
24
35
  get :log_in_with_admin_flag
25
36
  end
26
37
  end
38
+
39
+ get "api", to: "api#index"
27
40
  end
data/test/test_helper.rb CHANGED
@@ -18,4 +18,4 @@ require "active_record"
18
18
  ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"
19
19
  require "./test/support/schema"
20
20
 
21
- Dir["./test/support/**/*.rb"].sort.each {|file| require file }
21
+ Dir["./test/support/**/*.rb"].each {|file| require file }
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: simple_auth
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.1.3
4
+ version: 3.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nando Vieira
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2020-02-21 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: globalid
@@ -56,16 +55,16 @@ dependencies:
56
55
  name: bcrypt
57
56
  requirement: !ruby/object:Gem::Requirement
58
57
  requirements:
59
- - - "~>"
58
+ - - ">="
60
59
  - !ruby/object:Gem::Version
61
- version: 3.1.7
60
+ version: '0'
62
61
  type: :development
63
62
  prerelease: false
64
63
  version_requirements: !ruby/object:Gem::Requirement
65
64
  requirements:
66
- - - "~>"
65
+ - - ">="
67
66
  - !ruby/object:Gem::Version
68
- version: 3.1.7
67
+ version: '0'
69
68
  - !ruby/object:Gem::Dependency
70
69
  name: minitest
71
70
  requirement: !ruby/object:Gem::Requirement
@@ -172,35 +171,54 @@ executables:
172
171
  extensions: []
173
172
  extra_rdoc_files: []
174
173
  files:
174
+ - ".github/CODEOWNERS"
175
+ - ".github/FUNDING.yml"
176
+ - ".github/ISSUE_TEMPLATE/bug_report.md"
177
+ - ".github/ISSUE_TEMPLATE/config.yml"
178
+ - ".github/ISSUE_TEMPLATE/feature_request.md"
179
+ - ".github/PULL_REQUEST_TEMPLATE.md"
180
+ - ".github/dependabot.yml"
181
+ - ".github/workflows/ruby-tests.yml"
175
182
  - ".gitignore"
176
183
  - ".rubocop.yml"
177
- - ".travis.yml"
178
184
  - CHANGELOG.md
185
+ - CODE_OF_CONDUCT.md
179
186
  - Gemfile
187
+ - LICENSE.md
180
188
  - MIGRATE.md
181
189
  - README.md
182
190
  - Rakefile
183
191
  - bin/console
184
192
  - gemfiles/rails_5_2.gemfile
185
193
  - gemfiles/rails_6_0.gemfile
194
+ - gemfiles/rails_6_1.gemfile
195
+ - gemfiles/rails_7_0.gemfile
196
+ - gemfiles/rails_8_0.gemfile
197
+ - gemfiles/rails_8_1.gemfile
186
198
  - lib/simple_auth.rb
187
199
  - lib/simple_auth/action_controller.rb
200
+ - lib/simple_auth/action_controller/api.rb
188
201
  - lib/simple_auth/action_controller/require_login_action.rb
189
202
  - lib/simple_auth/config.rb
190
203
  - lib/simple_auth/generator.rb
191
204
  - lib/simple_auth/railtie.rb
205
+ - lib/simple_auth/routing_mapper.rb
192
206
  - lib/simple_auth/session.rb
193
207
  - lib/simple_auth/templates/install/initializer.rb
194
208
  - lib/simple_auth/version.rb
195
209
  - simple_auth.gemspec
196
210
  - test/controllers/admin/dashboard_controller_test.rb
211
+ - test/controllers/api_controller_test.rb
197
212
  - test/controllers/dashboard_controller_test.rb
198
213
  - test/controllers/pages_controller_test.rb
199
214
  - test/generators/install_test.rb
215
+ - test/requests/admin_test.rb
200
216
  - test/support/dummy/app/controllers/admin/dashboard_controller.rb
217
+ - test/support/dummy/app/controllers/api_controller.rb
201
218
  - test/support/dummy/app/controllers/application_controller.rb
202
219
  - test/support/dummy/app/controllers/dashboard_controller.rb
203
220
  - test/support/dummy/app/controllers/pages_controller.rb
221
+ - test/support/dummy/app/controllers/sessions_controller.rb
204
222
  - test/support/dummy/app/models/user.rb
205
223
  - test/support/dummy/config/application.rb
206
224
  - test/support/dummy/config/initializers/simple_auth.rb
@@ -210,8 +228,14 @@ files:
210
228
  - test/unit/session_test.rb
211
229
  homepage: http://rubygems.org/gems/simple_auth
212
230
  licenses: []
213
- metadata: {}
214
- post_install_message:
231
+ metadata:
232
+ homepage_uri: http://rubygems.org/gems/simple_auth
233
+ bug_tracker_uri: https://github.com/fnando/simple_auth/issues
234
+ source_code_uri: https://github.com/fnando/simple_auth/tree/v3.2.0
235
+ changelog_uri: https://github.com/fnando/simple_auth/tree/v3.2.0/CHANGELOG.md
236
+ documentation_uri: https://github.com/fnando/simple_auth/tree/v3.2.0/README.md
237
+ license_uri: https://github.com/fnando/simple_auth/tree/v3.2.0/LICENSE.md
238
+ rubygems_mfa_required: 'true'
215
239
  rdoc_options: []
216
240
  require_paths:
217
241
  - lib
@@ -219,30 +243,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
219
243
  requirements:
220
244
  - - ">="
221
245
  - !ruby/object:Gem::Version
222
- version: '0'
246
+ version: 3.3.0
223
247
  required_rubygems_version: !ruby/object:Gem::Requirement
224
248
  requirements:
225
249
  - - ">="
226
250
  - !ruby/object:Gem::Version
227
251
  version: '0'
228
252
  requirements: []
229
- rubygems_version: 3.1.2
230
- signing_key:
253
+ rubygems_version: 4.0.3
231
254
  specification_version: 4
232
255
  summary: A simple authentication system for Rails apps
233
- test_files:
234
- - test/controllers/admin/dashboard_controller_test.rb
235
- - test/controllers/dashboard_controller_test.rb
236
- - test/controllers/pages_controller_test.rb
237
- - test/generators/install_test.rb
238
- - test/support/dummy/app/controllers/admin/dashboard_controller.rb
239
- - test/support/dummy/app/controllers/application_controller.rb
240
- - test/support/dummy/app/controllers/dashboard_controller.rb
241
- - test/support/dummy/app/controllers/pages_controller.rb
242
- - test/support/dummy/app/models/user.rb
243
- - test/support/dummy/config/application.rb
244
- - test/support/dummy/config/initializers/simple_auth.rb
245
- - test/support/dummy/config/routes.rb
246
- - test/support/schema.rb
247
- - test/test_helper.rb
248
- - test/unit/session_test.rb
256
+ test_files: []
data/.travis.yml DELETED
@@ -1,22 +0,0 @@
1
- ---
2
- sudo: false
3
- cache: bundler
4
- rvm:
5
- - 2.7.0
6
- - 2.6.5
7
- - 2.5.7
8
- script: bundle exec rake
9
- before_script:
10
- - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
11
- - chmod +x ./cc-test-reporter
12
- - "./cc-test-reporter before-build"
13
- after_script:
14
- - "./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT"
15
- notifications:
16
- email: false
17
- gemfile:
18
- - gemfiles/rails_6_0.gemfile
19
- - gemfiles/rails_5_2.gemfile
20
- env:
21
- global:
22
- secure: LglasZ2QJLCE2tSKyZ9wIZNNwDNQ/gi+QNSHlpK2olgBOYMKV1idJPZjUlSTAac7+QHTYRRGCoUVMYHWxJgLfcuo7YpXVAgqPwjVl5nbHKfh/oP/FLriELKZbqMo0TtuqZNdnqPdO8RE7zK0om37jYNoUPJ4j2mUVLC8PMZpbiM=