eld 0.2.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: 247e36de9e29d9c37af0e18f3539163d374e06f58c1e6083c4bfaac166936822
4
+ data.tar.gz: bc8301c74a5fb74f1f0257fdd1460f6efe366b1946cb108daa5c08dcaa807043
5
+ SHA512:
6
+ metadata.gz: 49d2a5d66cf2a7d23b2bd3ff3c6ed16c261723ec48f9328c76b990826885e70796b36f5b7afeea7fc90110c63c53cde5ac41aabc0e675af0008bfa7033f1889d
7
+ data.tar.gz: cb88f78c43e8ed65b263e98abe991de8ba6614b74576abd99643548d3744e4c05ea08cd416865e9ffb61c876d037fd307bb80a1f6b6bd65675026520acfc4306
data/.codeclimate.yml ADDED
@@ -0,0 +1,12 @@
1
+ plugins:
2
+ rubocop:
3
+ enabled: true
4
+ channel: rubocop-1-48-1
5
+ exclude_patterns:
6
+ - "!spec/"
7
+ - "spec/vcr_cassettes"
8
+ checks:
9
+ similar-code:
10
+ enabled: false
11
+ identical-code:
12
+ enabled: false
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,54 @@
1
+ require: rubocop-rspec
2
+
3
+ AllCops:
4
+ TargetRubyVersion: 2.7
5
+
6
+ Style/StringLiterals:
7
+ Enabled: true
8
+ EnforcedStyle: double_quotes
9
+
10
+ Style/StringLiteralsInInterpolation:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+
14
+ Style/TrivialAccessors:
15
+ Enabled: false
16
+
17
+ Style/Documentation:
18
+ Enabled: false
19
+
20
+ Style/HashSyntax:
21
+ Enabled: false
22
+
23
+ Layout/LineLength:
24
+ Enabled: false
25
+
26
+ Layout/MultilineOperationIndentation:
27
+ Enabled: false
28
+
29
+ Layout/MultilineMethodCallIndentation:
30
+ Enabled: false
31
+
32
+ Gemspec/OrderedDependencies:
33
+ Enabled: false
34
+
35
+ Metrics/AbcSize:
36
+ Enabled: false
37
+
38
+ RSpec/MultipleMemoizedHelpers:
39
+ Enabled: false
40
+
41
+ RSpec/MultipleExpectations:
42
+ Enabled: false
43
+
44
+ RSpec/NestedGroups:
45
+ Enabled: false
46
+
47
+ RSpec/ExampleLength:
48
+ Enabled: false
49
+
50
+ RSpec/ContextWording:
51
+ Enabled: false
52
+
53
+ RSpec/MessageSpies:
54
+ Enabled: false
@@ -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 rickardsunden@gmail.com. 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,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in eld.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,106 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ eld (0.2.0)
5
+ httparty (~> 0.21)
6
+ jwt (~> 2.7)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ addressable (2.8.3)
12
+ public_suffix (>= 2.0.2, < 6.0)
13
+ ast (2.4.2)
14
+ coderay (1.1.3)
15
+ connection_pool (2.4.0)
16
+ crack (0.4.5)
17
+ rexml
18
+ diff-lcs (1.5.0)
19
+ docile (1.4.0)
20
+ hashdiff (1.0.1)
21
+ httparty (0.21.0)
22
+ mini_mime (>= 1.0.0)
23
+ multi_xml (>= 0.5.2)
24
+ json (2.6.3)
25
+ jwt (2.7.0)
26
+ method_source (1.0.0)
27
+ mini_mime (1.1.2)
28
+ multi_xml (0.6.0)
29
+ parallel (1.22.1)
30
+ parser (3.2.2.0)
31
+ ast (~> 2.4.1)
32
+ pry (0.14.2)
33
+ coderay (~> 1.1)
34
+ method_source (~> 1.0)
35
+ public_suffix (5.0.1)
36
+ rainbow (3.1.1)
37
+ rake (13.0.6)
38
+ redis (5.0.6)
39
+ redis-client (>= 0.9.0)
40
+ redis-client (0.14.1)
41
+ connection_pool
42
+ regexp_parser (2.7.0)
43
+ rexml (3.2.5)
44
+ rspec (3.12.0)
45
+ rspec-core (~> 3.12.0)
46
+ rspec-expectations (~> 3.12.0)
47
+ rspec-mocks (~> 3.12.0)
48
+ rspec-core (3.12.1)
49
+ rspec-support (~> 3.12.0)
50
+ rspec-expectations (3.12.2)
51
+ diff-lcs (>= 1.2.0, < 2.0)
52
+ rspec-support (~> 3.12.0)
53
+ rspec-mocks (3.12.5)
54
+ diff-lcs (>= 1.2.0, < 2.0)
55
+ rspec-support (~> 3.12.0)
56
+ rspec-support (3.12.0)
57
+ rubocop (1.49.0)
58
+ json (~> 2.3)
59
+ parallel (~> 1.10)
60
+ parser (>= 3.2.0.0)
61
+ rainbow (>= 2.2.2, < 4.0)
62
+ regexp_parser (>= 1.8, < 3.0)
63
+ rexml (>= 3.2.5, < 4.0)
64
+ rubocop-ast (>= 1.28.0, < 2.0)
65
+ ruby-progressbar (~> 1.7)
66
+ unicode-display_width (>= 2.4.0, < 3.0)
67
+ rubocop-ast (1.28.0)
68
+ parser (>= 3.2.1.0)
69
+ rubocop-capybara (2.17.1)
70
+ rubocop (~> 1.41)
71
+ rubocop-rspec (2.19.0)
72
+ rubocop (~> 1.33)
73
+ rubocop-capybara (~> 2.17)
74
+ ruby-progressbar (1.13.0)
75
+ simplecov (0.22.0)
76
+ docile (~> 1.1)
77
+ simplecov-html (~> 0.11)
78
+ simplecov_json_formatter (~> 0.1)
79
+ simplecov-html (0.12.3)
80
+ simplecov_json_formatter (0.1.4)
81
+ timecop (0.9.6)
82
+ unicode-display_width (2.4.2)
83
+ vcr (6.1.0)
84
+ webmock (3.18.1)
85
+ addressable (>= 2.8.0)
86
+ crack (>= 0.3.2)
87
+ hashdiff (>= 0.4.0, < 2.0.0)
88
+
89
+ PLATFORMS
90
+ arm64-darwin-20
91
+
92
+ DEPENDENCIES
93
+ eld!
94
+ pry
95
+ rake (~> 13.0)
96
+ redis
97
+ rspec (~> 3.0)
98
+ rubocop (~> 1.49)
99
+ rubocop-rspec (~> 2.19)
100
+ simplecov
101
+ timecop (~> 0.9)
102
+ vcr (~> 6.1)
103
+ webmock (~> 3.18)
104
+
105
+ BUNDLED WITH
106
+ 2.3.7
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 TODO: Write your name
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,169 @@
1
+ # Eld
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/eld.svg)](https://rubygems.org/gems/eld)
4
+ ![Build](https://github.com/sunrick/eld/workflows/CI/badge.svg)
5
+ <a href="https://codeclimate.com/github/sunrick/eld/maintainability"><img src="https://api.codeclimate.com/v1/badges/5e8eadb4762ad371641c/maintainability" /></a>
6
+ <a href="https://codeclimate.com/github/sunrick/eld/test_coverage"><img src="https://api.codeclimate.com/v1/badges/5e8eadb4762ad371641c/test_coverage" /></a>
7
+ [![Known Vulnerabilities](https://snyk.io/test/github/sunrick/eld/badge.svg)](https://snyk.io/test/github/{username}/{repo})
8
+
9
+ [Firebase Authentication](https://firebase.google.com/docs/auth) for Ruby applications.
10
+
11
+ ## Installation
12
+
13
+ Add this line to your application's Gemfile:
14
+
15
+ ```ruby
16
+ gem "eld"
17
+ ```
18
+
19
+ And then execute:
20
+
21
+ $ bundle install
22
+
23
+ Or install it yourself as:
24
+
25
+ $ gem install eld
26
+
27
+ ## Usage
28
+
29
+ Eld takes a Firebase access token and decodes it. Once you've decoded the token, the rest is up to you!
30
+
31
+ See [Firebase Authentication](https://firebase.google.com/docs/auth) for example client implementations.
32
+
33
+ ### Basic Usage
34
+ ```rb
35
+ Eld.configure do |c|
36
+ c.firebase_id = "FIREBASE_PROJECT_ID"
37
+ end
38
+
39
+ decoded_token = Eld.authenticate("FIREBASE_ACCESS_TOKEN")
40
+ # =>
41
+ {
42
+ "iss" => "https://securetoken.google.com/fire-auth-67d5f",
43
+ "aud" => "fire-auth-67d5f",
44
+ "auth_time" => 1679606435,
45
+ "user_id" => "Z02vuFq6RAU1NqVrWrdLAjyiqJ83",
46
+ "sub" => "Z02vuFq6RAU1NqVrWrdLAjyiqJ83",
47
+ "iat" => 1679606435,
48
+ "exp" => 1679610035,
49
+ "email" => "test@test.com",
50
+ "email_verified" => false,
51
+ "firebase" => {
52
+ "identities" => {
53
+ "email" => ["test@test.com"]
54
+ },
55
+ "sign_in_provider"=>"password"
56
+ }
57
+ }
58
+
59
+ user = User.new(decoded_token)
60
+ ```
61
+
62
+ ### Advanced Setup
63
+
64
+ ```rb
65
+ Eld.configure do |c|
66
+ # Use one or more Firebase projects
67
+ c.firebase_id = "FIREBASE_PROJECT_ID"
68
+ # c.firebase_id = ["FIREBASE_PROJECT_ID_1", "FIREBASE_PROJECT_ID_2"]
69
+
70
+ # Use Redis to cache (recommended)
71
+ # By default we use Eld::Cache::Memory
72
+ # You can also create your own cache implementation.
73
+ c.cache = Eld::Cache::Redis.new(
74
+ client: Redis.new, # Your redis client
75
+ cache_key "eld/certificates" # Optional: This is the default key
76
+ )
77
+
78
+ # Use your own authenticator
79
+ # See Eld::Authenticator for an example implementation.
80
+ c.authenticator = CustomAuthenticator
81
+ end
82
+ ```
83
+
84
+ ### Certificates
85
+
86
+ The default behavior of Eld is to lazily handle caching and fetching certificates from Google when authenticating tokens. This means you don't have to worry about refreshing certificates at any particular interval. However, you can refresh the cache and fetch new certificates whenever you want should you need to.
87
+
88
+ ```rb
89
+ Eld::Certificate.refresh
90
+ ```
91
+
92
+ ### Custom Authenticators
93
+
94
+ You can create your own authenticator and use it as a new default or build it anywhere.
95
+
96
+ Custom authenticators will still use Eld defaults for caching.
97
+
98
+ ```rb
99
+ class CustomAuthenticator < Eld::Authenticator
100
+ # The default behavior is to return the decoded token
101
+ # You could add additional behavior like finding or instantiating
102
+ # a user.
103
+ def respond(decoded_token)
104
+ User.find_by(uid: decoded_token['user_id'])
105
+ end
106
+
107
+ # The default authenticator swallows JWT errors
108
+ # You might want to handle them on your own.
109
+ def handle_error(error)
110
+ ReportError.call(error)
111
+ false
112
+ end
113
+ end
114
+
115
+ # Set a new default authenticator
116
+ Eld.authenticator = CustomAuthenticator
117
+ Eld.authenticate(token)
118
+ # => User(uid: "1231231")
119
+
120
+ # Instantiate your own authenticator
121
+ authenticator = CustomAuthenticator.new(firebase_id: "FIREBASE_PROJECT_ID")
122
+ authenticator.authenticate(token)
123
+ # => User(uid: "1231231")
124
+ ```
125
+
126
+ ### Rails Example
127
+
128
+ ```rb
129
+ class ApplicationController < ActionController::Base
130
+ before_action :authenticate_user!
131
+ helper_method :current_user
132
+
133
+ def authenticate_user!
134
+ @current_user = nil
135
+
136
+ token = request.headers["X-Access-Token"]
137
+ decoded_token = Eld.authenticate(token)
138
+
139
+ if payload
140
+ # Find a User from DB?
141
+ # Find or create a User?
142
+ @current_user = User.find_by(uid: decoded_token['user_id'])
143
+
144
+ # Wrap data in a User object?
145
+ @current_user = User.new(decoded_token)
146
+ end
147
+
148
+ head :unauthorized unless @current_user
149
+ end
150
+
151
+ def current_user
152
+ @current_user
153
+ end
154
+ end
155
+ ```
156
+
157
+ ## Development
158
+
159
+ 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.
160
+
161
+ 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).
162
+
163
+ ## Contributing
164
+
165
+ Bug reports and pull requests are welcome on GitHub at https://github.com/sunrick/eld. Please check the [code of conduct](https://github.com/sunrick/eld/blob/main/CODE_OF_CONDUCT.md) before contributing.
166
+
167
+ ## License
168
+
169
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
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]
data/eld.gemspec ADDED
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/eld/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "eld"
7
+ spec.version = Eld::VERSION
8
+ spec.authors = ["Rickard Sundén"]
9
+ spec.email = ["rickardsunden@gmail.com"]
10
+
11
+ spec.summary = "Firebase Authentication for Ruby applications."
12
+ spec.homepage = "https://github.com/sunrick/eld"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = ">= 2.7"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = "https://github.com/sunrick/eld"
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files =
22
+ Dir.chdir(File.expand_path(__dir__)) do
23
+ `git ls-files -z`.split("\x0")
24
+ .reject do |f|
25
+ (f == __FILE__) ||
26
+ f.match(
27
+ %r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)}
28
+ )
29
+ end
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_dependency "jwt", "~> 2.7"
36
+ spec.add_dependency "httparty", "~> 0.21"
37
+
38
+ spec.add_development_dependency "rake", "~> 13.0"
39
+ spec.add_development_dependency "rspec", "~> 3.0"
40
+ spec.add_development_dependency "rubocop", "~> 1.49"
41
+ spec.add_development_dependency "rubocop-rspec", "~> 2.19"
42
+ spec.add_development_dependency "vcr", "~> 6.1"
43
+ spec.add_development_dependency "webmock", "~> 3.18"
44
+ spec.add_development_dependency "pry"
45
+ spec.add_development_dependency "timecop", "~> 0.9"
46
+ spec.add_development_dependency "redis"
47
+ spec.add_development_dependency "simplecov"
48
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "jwt"
4
+ require "httparty"
5
+
6
+ module Eld
7
+ class Authenticator
8
+ GOOGLE_ISS = "https://securetoken.google.com"
9
+
10
+ # See Firebase docs for implemenation details
11
+ # https://firebase.google.com/docs/auth/admin/verify-id-tokens?authuser=0#verify_id_tokens_using_a_third-party_jwt_library
12
+
13
+ #############
14
+ # Glossary: #
15
+ #############
16
+ # exp Expiration time Must be in the future. The time is measured in seconds since the UNIX epoch.
17
+ # iat Issued-at time Must be in the past. The time is measured in seconds since the UNIX epoch.
18
+ # aud Audience Must be your Firebase project ID, the unique identifier for your Firebase project, which can be found in the URL of that project's console.
19
+ # iss Issuer Must be "https://securetoken.google.com/<projectId>", where <projectId> is the same project ID used for aud above.
20
+ # sub Subject Must be a non-empty string and must be the uid of the user or device.
21
+ # auth_time Authentication time Must be in the past. The time when the user authenticated.
22
+
23
+ def initialize(firebase_id:)
24
+ @firebase_id = Array(firebase_id)
25
+ end
26
+
27
+ def authenticate(token)
28
+ return false if token.nil? || token.empty?
29
+
30
+ kid = JWT.decode(token, nil, false).last["kid"]
31
+
32
+ certificate = Eld::Certificate.find(kid)
33
+
34
+ decoded_token = decode_token(token, certificate.public_key)
35
+
36
+ valid_token?(decoded_token) && respond(decoded_token)
37
+ rescue JWT::DecodeError => e
38
+ handle_error(e)
39
+ end
40
+
41
+ def decode_token(token, public_key)
42
+ JWT.decode(
43
+ token,
44
+ public_key,
45
+ true,
46
+ algorithm: "RS256",
47
+ verify_expiration: false # we verify this manually
48
+ ).first
49
+ end
50
+
51
+ def valid_token?(decoded_token)
52
+ current_time = Time.now.utc.to_i
53
+
54
+ !decoded_token.empty? &&
55
+ decoded_token["exp"].to_i > current_time &&
56
+ decoded_token["iat"].to_i < current_time &&
57
+ decoded_token["auth_time"].to_i < current_time &&
58
+ valid_sub?(decoded_token) &&
59
+ valid_firebase_id?(decoded_token)
60
+ end
61
+
62
+ def valid_sub?(decoded_token)
63
+ !decoded_token["sub"].nil? &&
64
+ !decoded_token["sub"].empty? &&
65
+ decoded_token["sub"] == decoded_token["user_id"]
66
+ end
67
+
68
+ def valid_firebase_id?(decoded_token)
69
+ @firebase_id.any? do |id|
70
+ decoded_token["aud"] == id && decoded_token["iss"] == "#{GOOGLE_ISS}/#{id}"
71
+ end
72
+ end
73
+
74
+ def respond(decoded_token)
75
+ decoded_token
76
+ end
77
+
78
+ def handle_error(_error)
79
+ false
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Eld
4
+ module Cache
5
+ class Memory
6
+ def initialize
7
+ @storage = {}
8
+ end
9
+
10
+ def fetch(&block)
11
+ current_time = Time.now.utc.to_i
12
+
13
+ if @storage[:data] && @storage[:expires_at] > current_time
14
+ @storage[:data]
15
+ else
16
+ set(&block)
17
+ end
18
+ end
19
+
20
+ def set(&block)
21
+ response = block.call
22
+
23
+ @storage = response
24
+
25
+ response[:data]
26
+ end
27
+
28
+ def clear
29
+ @storage = {}
30
+
31
+ nil
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Eld
4
+ module Cache
5
+ class Redis
6
+ def initialize(
7
+ client:,
8
+ cache_key: "eld/certificates"
9
+ )
10
+ @client = client
11
+ @cache_key = cache_key
12
+ end
13
+
14
+ def fetch(&block)
15
+ data = @client.get(@cache_key)
16
+
17
+ if data
18
+ JSON.parse(data)
19
+ else
20
+ set(&block)
21
+ end
22
+ end
23
+
24
+ def set(&block)
25
+ response = block.call
26
+
27
+ # We calculate ex in seconds instead of using exat for
28
+ # specs. Not ideal but good enough.
29
+ # Probably should mock redis calls in tests.
30
+ @client.set(
31
+ @cache_key,
32
+ response[:data].to_json,
33
+ ex: response[:expires_at] - Time.now.utc.to_i
34
+ )
35
+
36
+ response[:data]
37
+ end
38
+
39
+ def clear
40
+ @client.del(@cache_key)
41
+
42
+ nil
43
+ end
44
+ end
45
+ end
46
+ end
data/lib/eld/cache.rb ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "cache/memory"
4
+ require_relative "cache/redis"
5
+
6
+ module Eld
7
+ module Cache
8
+ end
9
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Eld
4
+ class Certificate
5
+ GOOGLE_CERTIFICATES_URL =
6
+ "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
7
+
8
+ def self.all
9
+ Eld.cache.fetch do
10
+ response = HTTParty.get(GOOGLE_CERTIFICATES_URL)
11
+
12
+ {
13
+ expires_at: Time.parse(response.headers["expires"]).utc.to_i,
14
+ data: JSON.parse(response.body)
15
+ }
16
+ end
17
+ end
18
+
19
+ def self.find(kid)
20
+ certificate = all[kid]
21
+
22
+ OpenSSL::X509::Certificate.new(certificate)
23
+ end
24
+
25
+ def self.refresh
26
+ Eld.cache.clear
27
+ all
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Eld
4
+ VERSION = "0.2.0"
5
+ end
data/lib/eld.rb ADDED
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "eld/version"
4
+ require_relative "eld/cache"
5
+ require_relative "eld/certificate"
6
+ require_relative "eld/authenticator"
7
+
8
+ module Eld
9
+ class Error < StandardError
10
+ end
11
+
12
+ class << self
13
+ def configure
14
+ yield(self)
15
+ end
16
+
17
+ def firebase_id
18
+ @firebase_id
19
+ end
20
+
21
+ def firebase_id=(value)
22
+ @firebase_id = value
23
+ end
24
+
25
+ def authenticator
26
+ @authenticator ||= Eld::Authenticator.new(
27
+ firebase_id: firebase_id
28
+ )
29
+ end
30
+
31
+ def authenticator=(value)
32
+ @authenticator = value.new(firebase_id: firebase_id)
33
+ end
34
+
35
+ def cache
36
+ @cache ||= Eld::Cache::Memory.new
37
+ end
38
+
39
+ def cache=(value)
40
+ @cache = value
41
+ end
42
+
43
+ def authenticate(token)
44
+ authenticator.authenticate(token)
45
+ end
46
+ end
47
+ end
data/sig/eld.rbs ADDED
@@ -0,0 +1,3 @@
1
+ module Eld
2
+ VERSION: String
3
+ end
metadata ADDED
@@ -0,0 +1,231 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: eld
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Rickard Sundén
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-04-15 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.7'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.7'
27
+ - !ruby/object:Gem::Dependency
28
+ name: httparty
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.21'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.21'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '13.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '13.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '1.49'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '1.49'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop-rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '2.19'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '2.19'
97
+ - !ruby/object:Gem::Dependency
98
+ name: vcr
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '6.1'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '6.1'
111
+ - !ruby/object:Gem::Dependency
112
+ name: webmock
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '3.18'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '3.18'
125
+ - !ruby/object:Gem::Dependency
126
+ name: pry
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: '0'
139
+ - !ruby/object:Gem::Dependency
140
+ name: timecop
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - "~>"
144
+ - !ruby/object:Gem::Version
145
+ version: '0.9'
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - "~>"
151
+ - !ruby/object:Gem::Version
152
+ version: '0.9'
153
+ - !ruby/object:Gem::Dependency
154
+ name: redis
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - ">="
158
+ - !ruby/object:Gem::Version
159
+ version: '0'
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ - !ruby/object:Gem::Dependency
168
+ name: simplecov
169
+ requirement: !ruby/object:Gem::Requirement
170
+ requirements:
171
+ - - ">="
172
+ - !ruby/object:Gem::Version
173
+ version: '0'
174
+ type: :development
175
+ prerelease: false
176
+ version_requirements: !ruby/object:Gem::Requirement
177
+ requirements:
178
+ - - ">="
179
+ - !ruby/object:Gem::Version
180
+ version: '0'
181
+ description:
182
+ email:
183
+ - rickardsunden@gmail.com
184
+ executables: []
185
+ extensions: []
186
+ extra_rdoc_files: []
187
+ files:
188
+ - ".codeclimate.yml"
189
+ - ".rspec"
190
+ - ".rubocop.yml"
191
+ - CODE_OF_CONDUCT.md
192
+ - Gemfile
193
+ - Gemfile.lock
194
+ - LICENSE.txt
195
+ - README.md
196
+ - Rakefile
197
+ - eld.gemspec
198
+ - lib/eld.rb
199
+ - lib/eld/authenticator.rb
200
+ - lib/eld/cache.rb
201
+ - lib/eld/cache/memory.rb
202
+ - lib/eld/cache/redis.rb
203
+ - lib/eld/certificate.rb
204
+ - lib/eld/version.rb
205
+ - sig/eld.rbs
206
+ homepage: https://github.com/sunrick/eld
207
+ licenses:
208
+ - MIT
209
+ metadata:
210
+ homepage_uri: https://github.com/sunrick/eld
211
+ source_code_uri: https://github.com/sunrick/eld
212
+ post_install_message:
213
+ rdoc_options: []
214
+ require_paths:
215
+ - lib
216
+ required_ruby_version: !ruby/object:Gem::Requirement
217
+ requirements:
218
+ - - ">="
219
+ - !ruby/object:Gem::Version
220
+ version: '2.7'
221
+ required_rubygems_version: !ruby/object:Gem::Requirement
222
+ requirements:
223
+ - - ">="
224
+ - !ruby/object:Gem::Version
225
+ version: '0'
226
+ requirements: []
227
+ rubygems_version: 3.3.7
228
+ signing_key:
229
+ specification_version: 4
230
+ summary: Firebase Authentication for Ruby applications.
231
+ test_files: []