rottweiler 0.1.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
+ SHA256:
3
+ metadata.gz: 85bed1ab72dd8951ec40afe16afa8563f9cecd62e8eb858b6a5257546f4e0119
4
+ data.tar.gz: 5a7db89fb990b531ce4bb3da83ade63e314bbdb208740efa2d6dd86cff0643a3
5
+ SHA512:
6
+ metadata.gz: d310bc733fd05dbc6f03440f3be7cab4a50e7f70d79d7f17477da217893ed6a773e46f22f28a26d7c53d20afe26723f3fa79e4fd8fc722b5ad72addf983d3207
7
+ data.tar.gz: 5599b8cf15ace519f006b74294ca324ccc2a65306a4f1221d1c7aeb0ca8f93c52ba34297c4e653e0d8ba957c60da0c3690e4a3471b0ee6f1501ab124c7e63eca
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,10 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ TargetRubyVersion: 2.7
4
+
5
+ Style/StringLiteralsInInterpolation:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Layout/LineLength:
10
+ Max: 120
@@ -0,0 +1,22 @@
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "type": "rdbg",
9
+ "name": "RSpec",
10
+ "request": "launch",
11
+ "command": "bundle exec rspec",
12
+ "script": "${file}:${lineNumber}",
13
+ "args": [],
14
+ "askParameters": false
15
+ },
16
+ {
17
+ "type": "rdbg",
18
+ "name": "Attach with rdbg",
19
+ "request": "attach"
20
+ }
21
+ ]
22
+ }
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-02-22
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at groza@opinioni.net. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in rottweiler.gemspec
6
+ gemspec
7
+
8
+ gem 'rubocop', '~> 1.21'
9
+
10
+ group :test do
11
+ gem 'rake', '~> 13.0.6'
12
+ gem 'rspec-rails', '~> 6.0.1'
13
+ gem 'shoulda-matchers', '~> 5.3.0'
14
+ gem 'simplecov', '~> 0.22.0'
15
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,211 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rottweiler (0.1.0)
5
+ jwt (>= 2.0)
6
+ rails (>= 5.0)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ actioncable (7.0.4)
12
+ actionpack (= 7.0.4)
13
+ activesupport (= 7.0.4)
14
+ nio4r (~> 2.0)
15
+ websocket-driver (>= 0.6.1)
16
+ actionmailbox (7.0.4)
17
+ actionpack (= 7.0.4)
18
+ activejob (= 7.0.4)
19
+ activerecord (= 7.0.4)
20
+ activestorage (= 7.0.4)
21
+ activesupport (= 7.0.4)
22
+ mail (>= 2.7.1)
23
+ net-imap
24
+ net-pop
25
+ net-smtp
26
+ actionmailer (7.0.4)
27
+ actionpack (= 7.0.4)
28
+ actionview (= 7.0.4)
29
+ activejob (= 7.0.4)
30
+ activesupport (= 7.0.4)
31
+ mail (~> 2.5, >= 2.5.4)
32
+ net-imap
33
+ net-pop
34
+ net-smtp
35
+ rails-dom-testing (~> 2.0)
36
+ actionpack (7.0.4)
37
+ actionview (= 7.0.4)
38
+ activesupport (= 7.0.4)
39
+ rack (~> 2.0, >= 2.2.0)
40
+ rack-test (>= 0.6.3)
41
+ rails-dom-testing (~> 2.0)
42
+ rails-html-sanitizer (~> 1.0, >= 1.2.0)
43
+ actiontext (7.0.4)
44
+ actionpack (= 7.0.4)
45
+ activerecord (= 7.0.4)
46
+ activestorage (= 7.0.4)
47
+ activesupport (= 7.0.4)
48
+ globalid (>= 0.6.0)
49
+ nokogiri (>= 1.8.5)
50
+ actionview (7.0.4)
51
+ activesupport (= 7.0.4)
52
+ builder (~> 3.1)
53
+ erubi (~> 1.4)
54
+ rails-dom-testing (~> 2.0)
55
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
56
+ activejob (7.0.4)
57
+ activesupport (= 7.0.4)
58
+ globalid (>= 0.3.6)
59
+ activemodel (7.0.4)
60
+ activesupport (= 7.0.4)
61
+ activerecord (7.0.4)
62
+ activemodel (= 7.0.4)
63
+ activesupport (= 7.0.4)
64
+ activestorage (7.0.4)
65
+ actionpack (= 7.0.4)
66
+ activejob (= 7.0.4)
67
+ activerecord (= 7.0.4)
68
+ activesupport (= 7.0.4)
69
+ marcel (~> 1.0)
70
+ mini_mime (>= 1.1.0)
71
+ activesupport (7.0.4)
72
+ concurrent-ruby (~> 1.0, >= 1.0.2)
73
+ i18n (>= 1.6, < 2)
74
+ minitest (>= 5.1)
75
+ tzinfo (~> 2.0)
76
+ ast (2.4.2)
77
+ builder (3.2.4)
78
+ concurrent-ruby (1.1.10)
79
+ crass (1.0.6)
80
+ date (3.3.2)
81
+ diff-lcs (1.5.0)
82
+ docile (1.4.0)
83
+ erubi (1.11.0)
84
+ globalid (1.0.0)
85
+ activesupport (>= 5.0)
86
+ i18n (1.12.0)
87
+ concurrent-ruby (~> 1.0)
88
+ json (2.6.3)
89
+ jwt (2.6.0)
90
+ loofah (2.19.1)
91
+ crass (~> 1.0.2)
92
+ nokogiri (>= 1.5.9)
93
+ mail (2.8.0)
94
+ mini_mime (>= 0.1.1)
95
+ net-imap
96
+ net-pop
97
+ net-smtp
98
+ marcel (1.0.2)
99
+ method_source (1.0.0)
100
+ mini_mime (1.1.2)
101
+ minitest (5.17.0)
102
+ net-imap (0.3.2)
103
+ date
104
+ net-protocol
105
+ net-pop (0.1.2)
106
+ net-protocol
107
+ net-protocol (0.2.1)
108
+ timeout
109
+ net-smtp (0.3.3)
110
+ net-protocol
111
+ nio4r (2.5.8)
112
+ nokogiri (1.13.10-x86_64-linux)
113
+ racc (~> 1.4)
114
+ parallel (1.22.1)
115
+ parser (3.1.3.0)
116
+ ast (~> 2.4.1)
117
+ racc (1.6.1)
118
+ rack (2.2.4)
119
+ rack-test (2.0.2)
120
+ rack (>= 1.3)
121
+ rails (7.0.4)
122
+ actioncable (= 7.0.4)
123
+ actionmailbox (= 7.0.4)
124
+ actionmailer (= 7.0.4)
125
+ actionpack (= 7.0.4)
126
+ actiontext (= 7.0.4)
127
+ actionview (= 7.0.4)
128
+ activejob (= 7.0.4)
129
+ activemodel (= 7.0.4)
130
+ activerecord (= 7.0.4)
131
+ activestorage (= 7.0.4)
132
+ activesupport (= 7.0.4)
133
+ bundler (>= 1.15.0)
134
+ railties (= 7.0.4)
135
+ rails-dom-testing (2.0.3)
136
+ activesupport (>= 4.2.0)
137
+ nokogiri (>= 1.6)
138
+ rails-html-sanitizer (1.4.4)
139
+ loofah (~> 2.19, >= 2.19.1)
140
+ railties (7.0.4)
141
+ actionpack (= 7.0.4)
142
+ activesupport (= 7.0.4)
143
+ method_source
144
+ rake (>= 12.2)
145
+ thor (~> 1.0)
146
+ zeitwerk (~> 2.5)
147
+ rainbow (3.0.0)
148
+ rake (13.0.6)
149
+ regexp_parser (2.6.1)
150
+ rexml (3.2.5)
151
+ rspec-core (3.12.0)
152
+ rspec-support (~> 3.12.0)
153
+ rspec-expectations (3.12.2)
154
+ diff-lcs (>= 1.2.0, < 2.0)
155
+ rspec-support (~> 3.12.0)
156
+ rspec-mocks (3.12.3)
157
+ diff-lcs (>= 1.2.0, < 2.0)
158
+ rspec-support (~> 3.12.0)
159
+ rspec-rails (6.0.1)
160
+ actionpack (>= 6.1)
161
+ activesupport (>= 6.1)
162
+ railties (>= 6.1)
163
+ rspec-core (~> 3.11)
164
+ rspec-expectations (~> 3.11)
165
+ rspec-mocks (~> 3.11)
166
+ rspec-support (~> 3.11)
167
+ rspec-support (3.12.0)
168
+ rubocop (1.40.0)
169
+ json (~> 2.3)
170
+ parallel (~> 1.10)
171
+ parser (>= 3.1.2.1)
172
+ rainbow (>= 2.2.2, < 4.0)
173
+ regexp_parser (>= 1.8, < 3.0)
174
+ rexml (>= 3.2.5, < 4.0)
175
+ rubocop-ast (>= 1.23.0, < 2.0)
176
+ ruby-progressbar (~> 1.7)
177
+ unicode-display_width (>= 1.4.0, < 3.0)
178
+ rubocop-ast (1.24.0)
179
+ parser (>= 3.1.1.0)
180
+ ruby-progressbar (1.11.0)
181
+ shoulda-matchers (5.3.0)
182
+ activesupport (>= 5.2.0)
183
+ simplecov (0.22.0)
184
+ docile (~> 1.1)
185
+ simplecov-html (~> 0.11)
186
+ simplecov_json_formatter (~> 0.1)
187
+ simplecov-html (0.12.3)
188
+ simplecov_json_formatter (0.1.4)
189
+ thor (1.2.1)
190
+ timeout (0.3.1)
191
+ tzinfo (2.0.5)
192
+ concurrent-ruby (~> 1.0)
193
+ unicode-display_width (2.3.0)
194
+ websocket-driver (0.7.5)
195
+ websocket-extensions (>= 0.1.0)
196
+ websocket-extensions (0.1.5)
197
+ zeitwerk (2.6.6)
198
+
199
+ PLATFORMS
200
+ x86_64-linux
201
+
202
+ DEPENDENCIES
203
+ rake (~> 13.0.6)
204
+ rottweiler!
205
+ rspec-rails (~> 6.0.1)
206
+ rubocop (~> 1.21)
207
+ shoulda-matchers (~> 5.3.0)
208
+ simplecov (~> 0.22.0)
209
+
210
+ BUNDLED WITH
211
+ 2.3.24
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Groza Sergiu
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,161 @@
1
+ # Rottweiler
2
+
3
+ [![Maintainability](https://api.codeclimate.com/v1/badges/abc07c78d5a9ece0340a/maintainability)](https://codeclimate.com/github/demetra-it/rottweiler/maintainability)
4
+ [![Test Coverage](https://api.codeclimate.com/v1/badges/abc07c78d5a9ece0340a/test_coverage)](https://codeclimate.com/github/demetra-it/rottweiler/test_coverage)
5
+
6
+ Rottweiler is a Ruby gem that provides functionality for verifying JSON Web Tokens (JWTs).
7
+ It allows you to easily verify the authenticity and integrity of JWTs, making it an essential tool for applications
8
+ that rely on JWT-based authentication and authorization.
9
+ Rottweiler's intuitive interface and comprehensive documentation make it easy to use and integrate into new or existing Rails projects.
10
+
11
+ ## Requirements
12
+
13
+ - Ruby >= 2.7
14
+ - Rails >= 5.x
15
+
16
+ ## Installation
17
+
18
+ Install the gem and add to the application's Gemfile by executing:
19
+
20
+ $ bundle add rottweiler
21
+
22
+ If bundler is not being used to manage dependencies, install the gem by executing:
23
+
24
+ $ gem install rottweiler
25
+
26
+ ## Configuration
27
+
28
+ Before start using Rottweiler gem you might need to configure it to fit your application. First of all you need to choose the appropriate
29
+ cryptographic algorithm which is used for JWT generation and verification. The most common are HMAC and RSA, but there're also other available
30
+ algorithms. You can find more about available algorithms in the documentation of [JWT gem](https://github.com/jwt/ruby-jwt).
31
+
32
+ To configure Rottwiler gem you should add a new initializer file to `config/initializers/rottweiler.rb` and set `Rottweiler.config` to configure it for your application.
33
+
34
+ Below you can find an example of how to configure Rottweiler for verification of JWTs using the RSA algorithm:
35
+
36
+ ```ruby
37
+ # frozen_string_literal: true
38
+
39
+ require 'rottweiler'
40
+
41
+ Rottweiler.config do |config|
42
+ # Here an example of configuration for JWT generated with RSA algorithm (RSA 256)
43
+ config.jwt.algorithm = 'RS256'
44
+ # Decode key must be a OpenSSL::PKey::RSA when RSA algorithm is used
45
+ config.jwt.decode_key = OpenSSL::PKey::RSA.new(ENV['JWT_PUBLIC_KEY'])
46
+ end
47
+ ```
48
+
49
+ ### JWT header and param
50
+
51
+ By default Rottweiler will look for JWT token in `headers['Authorization']` header and `params[:token]`, but if you need to use a different header or param, you can specify which header and parameter to use for JWT lookup:
52
+
53
+ ```ruby
54
+ Rottweiler.config do |config|
55
+ config.token_header = 'X-JWT-Token'
56
+
57
+ # To search for JWT token in `params[:_jwt]`
58
+ config.token_param = [:_jwt]
59
+
60
+ # To search for JWT token in `params[:secrets][:jwt]`
61
+ config.token_param = [:secrets, :jwt]
62
+ end
63
+ ```
64
+
65
+ ### Unauthorized status code
66
+
67
+ If for some reason you don't want Rottweiler to respond with `401 Unauthorized` on authentication failure, you can customize the status code by setting:
68
+
69
+ ```ruby
70
+ Rottweiler.config.unauthorized_status = :bad_request
71
+
72
+ # or
73
+
74
+ Rottweiler.config do |config|
75
+ config.unauthorized_status = 403
76
+ end
77
+ ```
78
+
79
+ ## Usage
80
+
81
+ To start using Rottweiler in your controllers you just need to include `Rottweiler::Authentication` module in your controllers:
82
+
83
+ ```ruby
84
+ class ApplicationController < ActionController::API
85
+ include Rottweiler::Authentication
86
+
87
+ # If you want to run some specific code on authentication failure, you can do it
88
+ # by setting on_authentication_failed callback
89
+ on_authentication_failed do |errors|
90
+ # your code here
91
+ end
92
+
93
+ # If you need to run some specific code on authentication success, you can do it
94
+ # by setting on_authentication_success callback
95
+ on_authentication_success do |data|
96
+ # your code here
97
+ end
98
+ end
99
+ ```
100
+
101
+ ### Skip authentication
102
+
103
+ Sometimes you might want to skip authentication for specific controllers or actions. For doing so you can use `skip_authentication!` helper inside your controller:
104
+
105
+ ```ruby
106
+ class PublicController < ApplicationController
107
+ # Skip authentication for all the actions in this controller (make it public).
108
+ skip_authentication!
109
+ end
110
+ ```
111
+
112
+ If you want to skip authentication only for specific actions, you can pass the name of the actions for which you want to skip authentication with `:only` option:
113
+
114
+ ```ruby
115
+ class CustomController < ApplicationController
116
+ skip_authentication! only: %i[status public_action]
117
+
118
+ # Authentication required
119
+ def index; end
120
+
121
+ # Skip authentication
122
+ def status; end
123
+
124
+ # Skip authentication
125
+ def public_action; end
126
+ end
127
+ ```
128
+
129
+ You can also proceed in an opposite direction, by skipping authentication for all the actions except the actions specified with `:except` option:
130
+
131
+ ```ruby
132
+ class StrangeController < ApplicationController
133
+ skip_authentication! except: %i[private_action]
134
+
135
+ # Skip authentication
136
+ def index; end
137
+
138
+ # Authentication required
139
+ def private_action; end
140
+ end
141
+ ```
142
+
143
+ **NOTE**: `Rottweiler::Authentication` have to be included before other authorization modules, in order to perform authentication checks before authorization.
144
+
145
+ ## Development
146
+
147
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
148
+
149
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
150
+
151
+ ## Contributing
152
+
153
+ Bug reports and pull requests are welcome on GitHub at https://github.com/demetra-it/rottweiler. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/rottweiler/blob/master/CODE_OF_CONDUCT.md).
154
+
155
+ ## License
156
+
157
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
158
+
159
+ ## Code of Conduct
160
+
161
+ Everyone interacting in the Rottweiler project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/rottweiler/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'jwt'
4
+
5
+ module Rottweiler
6
+ module Auth
7
+ # Implements the logic for JWT token parsing
8
+ class Result
9
+ attr_reader :request, :data, :errors
10
+
11
+ def initialize(request)
12
+ @request = request
13
+ @data = nil
14
+ @errors = []
15
+
16
+ check_decode_key!
17
+ verify! if errors.empty?
18
+ end
19
+
20
+ def valid?
21
+ @errors.empty?
22
+ end
23
+
24
+ private
25
+
26
+ def algorithm
27
+ @algorithm ||= Rottweiler.config.jwt.algorithm
28
+ end
29
+
30
+ def decode_key
31
+ @decode_key ||= Rottweiler.config.jwt.decode_key
32
+ end
33
+
34
+ def check_decode_key!
35
+ return true unless decode_key.nil?
36
+
37
+ add_error(:decode_key, 'JWT decode key is not configured')
38
+ false
39
+ end
40
+
41
+ def verify!
42
+ if token.nil?
43
+ add_error(:token_missing, 'No JWT token found')
44
+ return
45
+ end
46
+
47
+ body = JWT.decode(token, decode_key, true, { algorithm: algorithm })[0]
48
+ @data = HashWithIndifferentAccess.new body
49
+ rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::IncorrectAlgorithm, JWT::DecodeError => e
50
+ handle_jwt_error(e)
51
+ rescue StandardError => e
52
+ handle_generic_error(e)
53
+ end
54
+
55
+ def token
56
+ return @token if defined?(@token)
57
+
58
+ @token = request.headers[Rottweiler.config.token_header] || request.params.dig(*Rottweiler.config.token_param)
59
+ @token = @token&.split(' ')&.last
60
+ @token
61
+ end
62
+
63
+ def add_error(key, message)
64
+ errors << { key => message }
65
+ end
66
+
67
+ def handle_jwt_error(error)
68
+ case error
69
+ when JWT::ExpiredSignature
70
+ add_error(:token_expired, 'JWT token is expired')
71
+ when JWT::VerificationError
72
+ add_error(:invalid_token_signature, 'JWT token has invalid signature')
73
+ when JWT::IncorrectAlgorithm
74
+ add_error(:invalid_token_algorithm, 'JWT token has invalid algorithm')
75
+ when JWT::DecodeError
76
+ add_error(:invalid_token_format, 'JWT token has invalid format')
77
+ end
78
+ end
79
+
80
+ def handle_generic_error(error)
81
+ Rails.logger.error "#{error.message}\n#{error.backtrace.join("\n")}"
82
+ add_error(:jwt_verification_error, "Failed to verify JWT token: #{error.class}")
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'result'
4
+
5
+ module Rottweiler
6
+ module Auth
7
+ # Implements the logic for requests authentication in Rails controllers.
8
+ class Settings
9
+ def initialize(superklass)
10
+ @super_params = superklass.rottweiler if superklass.respond_to?(:rottweiler)
11
+ reset!
12
+ end
13
+
14
+ def reset!
15
+ @auth_failed_cbk = nil
16
+ @auth_success_cbk = nil
17
+ reset_skip!
18
+ end
19
+
20
+ def reset_skip!
21
+ @skip = { only: [], except: [], all: false }
22
+ end
23
+
24
+ def skip_authentication!(only: nil, except: nil)
25
+ raise Rottweiler::InvalidParamsError, 'You can only use `only` or `except`, not both' if only && except
26
+
27
+ reset_skip!
28
+
29
+ @skip[:only] = sanitize_action_names(only)
30
+ @skip[:except] = sanitize_action_names(except)
31
+ @skip[:all] = true if only.nil?
32
+ end
33
+
34
+ def skip_authentication?(action_name)
35
+ action_name = action_name.to_sym
36
+
37
+ # Use the most local value if it's set, otherwise use the value from the superclass
38
+ return true if @skip[:only].include?(action_name)
39
+ return true if @skip[:all] && !@skip[:except].include?(action_name)
40
+
41
+ # If there's no superclass, return false, otherwise return the value from the superclass
42
+ return @super_params.skip_authentication?(action_name) unless @super_params.nil?
43
+
44
+ false
45
+ end
46
+
47
+ def auth_failed_cbk=(callback)
48
+ validate_callback!(callback)
49
+
50
+ @auth_failed_cbk = callback
51
+ end
52
+
53
+ def auth_failed_cbk
54
+ @auth_failed_cbk || @super_params&.auth_failed_cbk
55
+ end
56
+
57
+ def auth_success_cbk=(callback)
58
+ validate_callback!(callback)
59
+
60
+ @auth_success_cbk = callback
61
+ end
62
+
63
+ def auth_success_cbk
64
+ @auth_success_cbk || @super_params&.auth_success_cbk
65
+ end
66
+
67
+ def authenticate(request)
68
+ Result.new(request)
69
+ end
70
+
71
+ private
72
+
73
+ def sanitize_action_names(action_names)
74
+ return [] if action_names.nil?
75
+
76
+ [action_names].flatten.map do |action_name|
77
+ unless [Symbol, String].include?(action_name.class)
78
+ raise Rottweiler::InvalidParamsError, 'Action name must be a Symbol or a String'
79
+ end
80
+
81
+ action_name.to_sym
82
+ end
83
+ end
84
+
85
+ def validate_callback!(callback)
86
+ return if [Symbol, String, Proc].include?(callback.class)
87
+
88
+ raise Rottweiler::InvalidParamsError, 'Expected a callback block or a method name'
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/concern'
4
+ require_relative 'auth/settings'
5
+
6
+ module Rottweiler
7
+ # Implements the logic for requests authentication in Rails controllers.
8
+ module Authentication
9
+ extend ActiveSupport::Concern
10
+
11
+ included do
12
+ before_action do
13
+ next if rottweiler.skip_authentication?(action_name)
14
+
15
+ authentication = rottweiler.authenticate(request)
16
+ if authentication.valid?
17
+ rottweiler_on_authentication_success!(authentication.data)
18
+ else
19
+ rottweiler_on_authentication_failed!(authentication.errors)
20
+ force_rottweiler_auth_failure_status!
21
+ end
22
+ end
23
+ end
24
+
25
+ # Implement Rottweiler::Authentication class methods
26
+ module ClassMethods
27
+ attr_accessor :_rottweiler
28
+
29
+ def rottweiler
30
+ self._rottweiler ||= Rottweiler::Auth::Settings.new(superclass)
31
+ end
32
+
33
+ def skip_authentication!(**options)
34
+ rottweiler.skip_authentication!(**options)
35
+ end
36
+
37
+ def on_authentication_success(method_name = nil, &callback)
38
+ rottweiler.auth_success_cbk = callback || method_name
39
+ end
40
+
41
+ def on_authentication_failed(method_name = nil, &callback)
42
+ rottweiler.auth_failed_cbk = callback || method_name
43
+ end
44
+ end
45
+
46
+ protected
47
+
48
+ def rottweiler
49
+ self.class.rottweiler
50
+ end
51
+
52
+ def rottweiler_on_authentication_success!(data)
53
+ return if rottweiler.auth_success_cbk.nil?
54
+
55
+ if rottweiler.auth_success_cbk.is_a?(Proc)
56
+ instance_exec(data, &rottweiler.auth_success_cbk)
57
+ else
58
+ send(rottweiler.auth_success_cbk, data)
59
+ end
60
+ end
61
+
62
+ def rottweiler_on_authentication_failed!(errors)
63
+ if rottweiler.auth_failed_cbk.is_a?(Proc)
64
+ instance_exec(errors, &rottweiler.auth_failed_cbk)
65
+ elsif rottweiler.auth_failed_cbk
66
+ send(rottweiler.auth_failed_cbk, errors)
67
+ else
68
+ render json: { errors: errors }
69
+ end
70
+ end
71
+
72
+ def force_rottweiler_auth_failure_status!
73
+ response.status = Rottweiler.config.unauthorized_status
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal true
2
+
3
+ module Rottweiler
4
+ module Configs
5
+ # Implements JWT configuration for Rottweiler
6
+ class JWT
7
+ ACCEPTED_ALGORITHMS = %w[RS256 RS384 RS512 HS256 HS384 HS512].freeze
8
+
9
+ attr_reader :algorithm
10
+ attr_accessor :decode_key
11
+
12
+ def initialize
13
+ @algorithm = 'RS256'
14
+ @decode_key = nil
15
+ end
16
+
17
+ def algorithm=(algorithm)
18
+ raise Rottweiler::InvalidJwtAlgorithmError, 'JWT Algorithm must be a string' unless algorithm.is_a?(String)
19
+
20
+ unless ACCEPTED_ALGORITHMS.include?(algorithm.upcase)
21
+ error = "Invalid JWT algorithm: #{algorithm}. Valid values are: #{ACCEPTED_ALGORITHMS}"
22
+ raise Rottweiler::InvalidJwtAlgorithmError, error
23
+ end
24
+
25
+ @algorithm = algorithm
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'configs/jwt'
4
+
5
+ module Rottweiler
6
+ # `Configuration` class allows to store and retrieve current Rottweiler configuration.
7
+ class Configuration
8
+ def self.instance
9
+ @instance ||= Configuration.new
10
+ end
11
+
12
+ def self.reset!
13
+ @instance = Configuration.new
14
+ end
15
+
16
+ attr_accessor :token_header, :token_param, :unauthorized_status
17
+
18
+ attr_reader :jwt
19
+
20
+ def initialize
21
+ @token_header = 'Authorization'
22
+ @token_param = [:token]
23
+ @unauthorized_status = :unauthorized
24
+ @jwt = Configs::JWT.new
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rottweiler
4
+ VERSION = '0.1.0'
5
+ end
data/lib/rottweiler.rb ADDED
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'rottweiler/version'
4
+ require_relative 'rottweiler/configuration'
5
+ require_relative 'rottweiler/authentication'
6
+
7
+ # Rottweiler is a Ruby gem for easy verification of JSON Web Tokens (JWTs) in Rails applications.
8
+ module Rottweiler
9
+ class Error < StandardError; end
10
+ class InvalidParamsError < StandardError; end
11
+ class InvalidJwtAlgorithmError < StandardError; end
12
+
13
+ class << self
14
+ # Allows to configure Rottweiler gem:
15
+ #
16
+ # Rottweiler.config do |config|
17
+ # config.token_header = 'Authorization'
18
+ # config.token_param = [:token]
19
+ #
20
+ # config.jwt.algorithm = 'RS256'
21
+ # config.jwt.decode_key = '--- RSA PUBLIC KEY ---'
22
+ # end
23
+ #
24
+ def config(&block)
25
+ config_instance = Configuration.instance
26
+
27
+ if block_given?
28
+ block.call(config_instance)
29
+ else
30
+ config_instance
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/rottweiler/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'rottweiler'
7
+ spec.version = Rottweiler::VERSION
8
+ spec.authors = ['Demetra Opinioni.net S.r.l.']
9
+ spec.email = ['developers@opinioni.net']
10
+
11
+ spec.summary = 'Rottweiler is a Ruby gem for easy verification of JSON Web Tokens (JWTs) in Rails applications.'
12
+ spec.description = <<~DESC
13
+ Rottweiler is a Ruby gem that provides functionality for verifying JSON Web Tokens (JWTs).
14
+ It allows you to easily verify the authenticity and integrity of JWTs, making it an essential tool for applications
15
+ that rely on JWT-based authentication and authorization.
16
+ Rottweiler's intuitive interface and comprehensive documentation make it easy to use and integrate into new or existing Rails projects.
17
+ DESC
18
+
19
+ spec.homepage = 'https://github.com/demetra-it/rottweiler'
20
+ spec.license = 'MIT'
21
+ spec.required_ruby_version = '>= 2.7.0'
22
+
23
+ spec.metadata['homepage_uri'] = spec.homepage
24
+ spec.metadata['source_code_uri'] = spec.homepage
25
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/main/CHANGELOG.md"
26
+
27
+ spec.metadata['rubygems_mfa_required'] = 'true'
28
+
29
+ # Specify which files should be added to the gem when it is released.
30
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
31
+ spec.files = Dir.chdir(__dir__) do
32
+ `git ls-files -z`.split("\x0").reject do |f|
33
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
34
+ end
35
+ end
36
+ spec.bindir = 'exe'
37
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
38
+ spec.require_paths = ['lib']
39
+
40
+ # Uncomment to register a new dependency of your gem
41
+ # spec.add_dependency "example-gem", "~> 1.0"
42
+ spec.add_runtime_dependency 'jwt', '>= 2.0'
43
+ spec.add_runtime_dependency 'rails', '>= 5.0'
44
+
45
+ # For more information and examples about making a new gem, check out our
46
+ # guide at: https://bundler.io/guides/creating_gem.html
47
+ end
@@ -0,0 +1,30 @@
1
+ module Rottweiler
2
+ module Auth
3
+ # Implements the logic for requests authentication in Rails controllers.
4
+ class Settings
5
+ attr_writer auth_failed_cbk: Proc?
6
+
7
+ attr_writer auth_success_cbk: Proc?
8
+
9
+ def initialize: (Rottweiler::Auth::Settings superklass) -> void
10
+
11
+ def reset!: () -> void
12
+
13
+ def reset_skip!: () -> void
14
+
15
+ def skip_authentication!: (?only: Symbol | String | Array[Symbol] | Array[String], ?except: Symbol | String | Array[Symbol] | Array[String]) -> void
16
+
17
+ def skip_authentication?: (Symbol | String action_name) -> (true | false)
18
+
19
+ def auth_failed_cbk: () -> Proc?
20
+
21
+ def auth_success_cbk: () -> Proc?
22
+
23
+ def authenticate: (untyped request) -> Hash?
24
+
25
+ private
26
+
27
+ def sanitize_action_names: (Symbol action_names) -> (::Array[Symbol])
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,24 @@
1
+ module Rottweiler
2
+ module Auth
3
+ # Implements the logic for JWT token parsing
4
+ class TokenParser
5
+ attr_reader request: untyped
6
+
7
+ attr_reader result: Hash?
8
+
9
+ def initialize: (untyped request) -> void
10
+
11
+ def valid?: () -> bool
12
+
13
+ private
14
+
15
+ def algorithm: () -> String
16
+
17
+ def decode_key: () -> String?
18
+
19
+ def verify!: () -> void
20
+
21
+ def token: () -> String?
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,23 @@
1
+ module Rottweiler
2
+ # Implements the logic for requests authentication in Rails controllers.
3
+ module Authentication
4
+ extend ActiveSupport::Concern
5
+
6
+ # Implement Rottweiler::Authentication class methods
7
+ module ClassMethods
8
+ attr_accessor _rottweiler: Rottweiler::Auth::Settings
9
+
10
+ def rottweiler: () -> Rottweiler::Auth::Settings
11
+
12
+ def skip_authentication!: (?only: Symbol | String | Array[Symbol] | Array[String], ?except: Symbol | String | Array[Symbol] | Array[String]) -> void
13
+
14
+ def on_authentication_success: () ?{ () -> void } -> void
15
+
16
+ def on_authentication_failed: () ?{ () -> void } -> void
17
+ end
18
+
19
+ def rottweiler: () -> Rottweiler::Auth::Settings
20
+
21
+ def jwt_data: () -> Hash
22
+ end
23
+ end
@@ -0,0 +1,16 @@
1
+ module Rottweiler
2
+ module Configs
3
+ # Implements JWT configuration for Rottweiler
4
+ class JWT
5
+ ACCEPTED_ALGORITHMS: ::Array["RS256" | "RS384" | "RS512" | "HS256" | "HS384" | "HS512"]
6
+
7
+ attr_reader algorithm: String
8
+
9
+ attr_accessor decode_key: String?
10
+
11
+ def initialize: () -> void
12
+
13
+ def algorithm=: (String algorithm) -> void
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,16 @@
1
+ module Rottweiler
2
+ # `Configuration` class allows to store and retrieve current Rottweiler configuration.
3
+ class Configuration
4
+ def self.instance: () -> Rottweiler::Configuration
5
+
6
+ attr_accessor token_header: String | Symbol
7
+
8
+ attr_accessor token_param: Array[String] | Array[Symbol]
9
+
10
+ attr_accessor unauthorized_status: Integer | Symbol | String
11
+
12
+ attr_reader jwt: Rottweiler::Configs::JWT
13
+
14
+ def initialize: () -> void
15
+ end
16
+ end
@@ -0,0 +1,20 @@
1
+ # Rottweiler is a Ruby gem for easy verification of JSON Web Tokens (JWTs) in Rails applications.
2
+ module Rottweiler
3
+ class Error < StandardError
4
+ end
5
+
6
+ class InvalidParamsError < StandardError
7
+ end
8
+
9
+ # Allows to configure Rottweiler gem:
10
+ #
11
+ # Rottweiler.config do |config|
12
+ # config.token_header = 'Authorization'
13
+ # config.token_param = [:token]
14
+ #
15
+ # config.jwt.algorithm = 'RS256'
16
+ # config.jwt.decode_key = '--- RSA PUBLIC KEY ---'
17
+ # end
18
+ #
19
+ def self.config: () ?{ (Rottweiler::Configuration) -> void } -> Rottweiler::Configuration
20
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rottweiler
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Demetra Opinioni.net S.r.l.
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-02-22 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: jwt
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rails
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '5.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '5.0'
41
+ description: |
42
+ Rottweiler is a Ruby gem that provides functionality for verifying JSON Web Tokens (JWTs).
43
+ It allows you to easily verify the authenticity and integrity of JWTs, making it an essential tool for applications
44
+ that rely on JWT-based authentication and authorization.
45
+ Rottweiler's intuitive interface and comprehensive documentation make it easy to use and integrate into new or existing Rails projects.
46
+ email:
47
+ - developers@opinioni.net
48
+ executables: []
49
+ extensions: []
50
+ extra_rdoc_files: []
51
+ files:
52
+ - ".rspec"
53
+ - ".rubocop.yml"
54
+ - ".vscode/launch.json"
55
+ - CHANGELOG.md
56
+ - CODE_OF_CONDUCT.md
57
+ - Gemfile
58
+ - Gemfile.lock
59
+ - LICENSE.txt
60
+ - README.md
61
+ - Rakefile
62
+ - lib/rottweiler.rb
63
+ - lib/rottweiler/auth/result.rb
64
+ - lib/rottweiler/auth/settings.rb
65
+ - lib/rottweiler/authentication.rb
66
+ - lib/rottweiler/configs/jwt.rb
67
+ - lib/rottweiler/configuration.rb
68
+ - lib/rottweiler/version.rb
69
+ - rottweiler.gemspec
70
+ - sig/rottweiler.rbs
71
+ - sig/rottweiler/auth/settings.rbs
72
+ - sig/rottweiler/auth/token_parser.rbs
73
+ - sig/rottweiler/authentication.rbs
74
+ - sig/rottweiler/configs/jwt.rbs
75
+ - sig/rottweiler/configuration.rbs
76
+ homepage: https://github.com/demetra-it/rottweiler
77
+ licenses:
78
+ - MIT
79
+ metadata:
80
+ homepage_uri: https://github.com/demetra-it/rottweiler
81
+ source_code_uri: https://github.com/demetra-it/rottweiler
82
+ changelog_uri: https://github.com/demetra-it/rottweiler/blob/main/CHANGELOG.md
83
+ rubygems_mfa_required: 'true'
84
+ post_install_message:
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: 2.7.0
93
+ required_rubygems_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: '0'
98
+ requirements: []
99
+ rubygems_version: 3.3.7
100
+ signing_key:
101
+ specification_version: 4
102
+ summary: Rottweiler is a Ruby gem for easy verification of JSON Web Tokens (JWTs)
103
+ in Rails applications.
104
+ test_files: []