aid-common 0.1.4

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: dd2be344bd175b9b8bb072fd36b68850414824de3bc49f3275270877e794dc28
4
+ data.tar.gz: fb00f825b0e7015820cb0c00fd406d041fbb8f6c3f47d3d8397c7dfb1cfda4a5
5
+ SHA512:
6
+ metadata.gz: dcaa49b38c8a13beb2aee7798595ebf0eee95f8100fa6255fddf73e467c1624f160d0242a13d4e75c531ccfdd53129fc48ade8c2804fef43a4ce95518e164413
7
+ data.tar.gz: 418ead5d8a2b6618c035b487f6e5aea957f40270b59e49abe1ed70349895d2cae35db487e9536f12ea62a64ec3965384f3ee9bcc816540a6ecc27db0284c4b1a
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -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 yuivannikov@phoenixit.ru. 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,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in aid-common.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
data/Gemfile.lock ADDED
@@ -0,0 +1,50 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ aid-common (0.1.4)
5
+ jwt (>= 2.1.1, < 3)
6
+ ory-kratos-client (~> 0.10.1)
7
+ redis (>= 4.2.5)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ connection_pool (2.2.5)
13
+ diff-lcs (1.5.0)
14
+ ethon (0.15.0)
15
+ ffi (>= 1.15.0)
16
+ ffi (1.15.5)
17
+ jwt (2.5.0)
18
+ ory-kratos-client (0.10.1)
19
+ typhoeus (~> 1.0, >= 1.0.1)
20
+ rake (13.0.6)
21
+ redis (5.0.4)
22
+ redis-client (>= 0.7.4)
23
+ redis-client (0.8.0)
24
+ connection_pool
25
+ rspec (3.11.0)
26
+ rspec-core (~> 3.11.0)
27
+ rspec-expectations (~> 3.11.0)
28
+ rspec-mocks (~> 3.11.0)
29
+ rspec-core (3.11.0)
30
+ rspec-support (~> 3.11.0)
31
+ rspec-expectations (3.11.0)
32
+ diff-lcs (>= 1.2.0, < 2.0)
33
+ rspec-support (~> 3.11.0)
34
+ rspec-mocks (3.11.1)
35
+ diff-lcs (>= 1.2.0, < 2.0)
36
+ rspec-support (~> 3.11.0)
37
+ rspec-support (3.11.0)
38
+ typhoeus (1.4.0)
39
+ ethon (>= 0.9.0)
40
+
41
+ PLATFORMS
42
+ arm64-darwin-21
43
+
44
+ DEPENDENCIES
45
+ aid-common!
46
+ rake (~> 13.0)
47
+ rspec (~> 3.0)
48
+
49
+ BUNDLED WITH
50
+ 2.3.6
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Yury Ivannikov
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,45 @@
1
+ # Aid::Common
2
+
3
+ Gem for shared functionality of A.ID backend services:
4
+ - Authentication
5
+ - Inter-service communications - TBD
6
+ - DTOs and schemas - TBD
7
+ - RabbitMQ Connection - TBD
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'aid-common'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle install
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install aid-common
24
+
25
+ ## Usage
26
+
27
+ TODO: Write usage instructions here
28
+
29
+ ## Development
30
+
31
+ 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.
32
+
33
+ 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).
34
+
35
+ ## Contributing
36
+
37
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/aid-common. 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]/aid-common/blob/master/CODE_OF_CONDUCT.md).
38
+
39
+ ## License
40
+
41
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
42
+
43
+ ## Code of Conduct
44
+
45
+ Everyone interacting in the Aid::Common project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/aid-common/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
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
+ task default: :spec
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/aid/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "aid-common"
7
+ spec.version = AidCommon::VERSION
8
+ spec.authors = ["Yury Ivannikov"]
9
+ spec.email = ["yi@ariv.al"]
10
+
11
+ spec.summary = "A.ID Shared Functionality Gem"
12
+ spec.description = "A.ID Shared Functionality Gem"
13
+ # spec.homepage = "TODO: Put your gem's website or public repo URL here."
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.6.0"
16
+
17
+ # spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'"
18
+
19
+ # spec.metadata["homepage_uri"] = spec.homepage
20
+ # spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here."
21
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
28
+ end
29
+ end
30
+ spec.bindir = "exe"
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+
33
+ spec.add_runtime_dependency "ory-kratos-client", ["~> 0.10.1"]
34
+ spec.add_runtime_dependency "jwt", [">= 2.1.1", "< 3"]
35
+ spec.add_runtime_dependency "redis", [">= 4.2.5"]
36
+
37
+ spec.require_paths = ["lib"]
38
+
39
+ # Uncomment to register a new dependency of your gem
40
+ # spec.add_dependency "example-gem", "~> 1.0"
41
+
42
+ # For more information and examples about making a new gem, check out our
43
+ # guide at: https://bundler.io/guides/creating_gem.html
44
+ end
@@ -0,0 +1,13 @@
1
+ module Aid
2
+ module Auth
3
+ class Context
4
+ attr_accessor :session, :cookies, :env
5
+
6
+ def initialize(**options)
7
+ @session = options[:session]
8
+ @cookies = options[:cookies]
9
+ @env = options[:env]
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,11 @@
1
+ module Aid
2
+ module Auth
3
+ module Errors
4
+ class BaseError < ::Aid::Errors::Base; end
5
+
6
+ class Unauthorized < BaseError; end
7
+
8
+ class InvalidToken < BaseError; end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,36 @@
1
+ module Aid
2
+ module Auth
3
+ class Helper
4
+
5
+ def auth_manager
6
+ raise NotImplementedError
7
+ end
8
+
9
+ def authorized?
10
+ auth_manager.authorized?
11
+ end
12
+
13
+ def current_account_id
14
+ auth_manager.current_account_id
15
+ end
16
+
17
+ def current_account
18
+ @current_account ||= Account.find(current_account_id)
19
+ rescue ActiveRecord::RecordNotFound
20
+ raise ::Aid::Auth::Errors::Unauthorized
21
+ end
22
+
23
+ def current_client
24
+ @current_client ||= if params[:client_id]
25
+ Client.find(params[:client_id])
26
+ elsif request.env['HTTP_X_CLIENT_ID']
27
+ current_account.clients.find(request.env['HTTP_X_CLIENT_ID'])
28
+ else
29
+ nil
30
+ end
31
+ end
32
+ end
33
+
34
+ end
35
+ end
36
+
@@ -0,0 +1,45 @@
1
+ require 'ory-kratos-client'
2
+
3
+ module Aid
4
+ module Auth
5
+ module Kratos
6
+ class Api
7
+
8
+ KRATOS_PARAMS = %w(scheme host base_path server_index server_operation_index server_variables
9
+ server_operation_variables api_key api_key_prefix client_side_validation
10
+ verify_ssl verify_ssl_host params_encoding cert_file key_file timeout
11
+ debugging inject_format force_ending_format logger)
12
+
13
+ attr_accessor :api_config,
14
+ :api_client,
15
+ :v0_api_instance,
16
+ :metadata_api_instance
17
+
18
+ def initialize(**params)
19
+ @api_config = OryKratosClient::Configuration.new do |a|
20
+ params.each do |k, v|
21
+ if KRATOS_PARAMS.include?(k.to_s)
22
+ a.send("#{k}=", v)
23
+ end
24
+ end
25
+ end
26
+ @api_client = OryKratosClient::ApiClient.new(@api_config)
27
+ @metadata_api_instance = OryKratosClient::MetadataApi.new(@api_client)
28
+ @v0_api_instance = OryKratosClient::V0alpha2Api.new(@api_client)
29
+ end
30
+
31
+ def whoami(cookie: nil, token: nil)
32
+ params = {}
33
+ if cookie
34
+ params[:'cookie'] = cookie
35
+ end
36
+ if token
37
+ params[:'x_session_token'] = token
38
+ end
39
+ @v0_api_instance.to_session(**params)
40
+ end
41
+
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,50 @@
1
+ module Aid
2
+ module Auth
3
+ class EnabledStrategy
4
+ attr_accessor :strategy_klass,
5
+ :strategy_config,
6
+ :priority
7
+
8
+ def initialize(strategy_klass, strategy_config, priority = 0)
9
+ @strategy_klass = strategy_klass
10
+ @strategy_config = strategy_config
11
+ @priority = priority
12
+ end
13
+
14
+ def should_use?(ctx)
15
+ @strategy_klass.should_use?(ctx, @strategy_config)
16
+ end
17
+ end
18
+
19
+ class Manager
20
+ class_attribute :enabled_strategies
21
+
22
+ def self.enable_strategy(strategy_klass, strategy_config, priority = 0)
23
+ self.enabled_strategies ||= []
24
+ self.enabled_strategies << EnabledStrategy.new(strategy_klass, strategy_config, priority)
25
+ end
26
+
27
+ attr_accessor :context
28
+
29
+ def initialize(context)
30
+ @context = context
31
+ end
32
+
33
+ def strategy
34
+ strategies = self.class.enabled_strategies.sort{|x, y| y.priority <=> x.priority}
35
+ es = strategies.select{|s| s.should_use?(@context)}.first
36
+ es ||= strategies.first
37
+ (es&.strategy_klass || Strategies::Null).new(es&.strategy_config, @context)
38
+ end
39
+
40
+ def authenticated?
41
+ strategy.authenticated?
42
+ end
43
+
44
+ def current_account_id
45
+ strategy.current_user_id
46
+ end
47
+
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,24 @@
1
+ module Aid
2
+ module Auth
3
+ module Strategies
4
+ # Base Strategy (abstract class)
5
+
6
+ class BaseStrategy
7
+
8
+ def self.should_use?(ctx)
9
+ false
10
+ end
11
+
12
+ def current_user_id
13
+ raise NotImplementedError.new
14
+ end
15
+
16
+ def authenticated?
17
+ raise NotImplementedError.new
18
+ end
19
+
20
+ end
21
+ end
22
+ end
23
+ end
24
+
@@ -0,0 +1,71 @@
1
+ module Aid
2
+ module Auth
3
+ module Strategies
4
+
5
+ # Kratos based strategy with direct request to Kratos API to invalidate session
6
+ class KratosDirectV1Config
7
+ DEFAULT_KRATOS_COOKIE_NAME='ory_kratos_session'
8
+ DEFAULT_KRATOS_TOKEN_HEADER_NAME='HTTP_X_SESSION_TOKEN'
9
+
10
+ attr_accessor :api,
11
+ :kratos_cookie_name,
12
+ :kratos_token_header_name
13
+
14
+ def initialize(**options)
15
+ @api = options[:api]
16
+ @kratos_cookie_name = options[:kratos_cookie_name] ||
17
+ ENV.fetch('KRATOS_COOKIE_NAME', DEFAULT_KRATOS_COOKIE_NAME)
18
+ @kratos_token_header_name = options[:kratos_token_header_name] ||
19
+ ENV.fetch('KRATOS_TOKEN_HEADER_NAME', DEFAULT_KRATOS_TOKEN_HEADER_NAME)
20
+ yield(self) if block_given?
21
+ end
22
+
23
+ end
24
+
25
+ class KratosDirectV1 < BaseStrategy
26
+
27
+ attr_accessor :config, :context
28
+
29
+ def self.should_use?(ctx, config)
30
+ conf = config.is_a?(KratosDirectV1Config) ? config : KratosDirectV1Config.new(**config)
31
+ ctx.cookies[conf.kratos_cookie_name].present? || ctx.env[conf.kratos_token_header_name].present?
32
+ end
33
+
34
+ def initialize(config=KratosDirectV1Config.new, context)
35
+ if config.is_a?(Hash)
36
+ @config = KratosDirectV1Config.new(**config)
37
+ elsif config.is_a?(KratosDirectV1Config)
38
+ @config = config
39
+ end
40
+ @context = context
41
+ end
42
+
43
+ def current_user_id
44
+ session&.identity&.id
45
+ end
46
+
47
+ def authenticated?
48
+ session&.active
49
+ end
50
+
51
+ private
52
+
53
+ def session
54
+ @session ||= @config.api.whoami(cookie: cookie, token: token)
55
+ end
56
+
57
+ def cookie
58
+ val = @context.cookies[@config.kratos_cookie_name]
59
+ return nil unless val
60
+ "#{@config.kratos_cookie_name}=#{val};"
61
+ end
62
+
63
+ def token
64
+ @context.env[@config.kratos_token_header_name]
65
+ end
66
+
67
+ end
68
+ end
69
+ end
70
+ end
71
+
@@ -0,0 +1,26 @@
1
+ module Aid
2
+ module Auth
3
+ module Strategies
4
+ # Null Strategy (always returns unauthorized)
5
+
6
+ class Null < BaseStrategy
7
+
8
+ def initialize(*options); end
9
+
10
+ def self.should_use?
11
+ true
12
+ end
13
+
14
+ def current_user_id
15
+ nil
16
+ end
17
+
18
+ def authenticated?
19
+ false
20
+ end
21
+
22
+ end
23
+ end
24
+ end
25
+ end
26
+
@@ -0,0 +1,73 @@
1
+ require 'jwt'
2
+
3
+ module Aid
4
+ module Auth
5
+ module Strategies
6
+ # Old strategy based on OAuth2 tokens
7
+ # Requires envs:
8
+ # - SSO_JWT_SECRET
9
+ # - SSO_CLIENT_ID
10
+ # - SSO_CLIENT_SECRET
11
+ # - SSO_HOST
12
+ # - SESSION_EXP_TIME
13
+
14
+ class TokenAuthV1Config
15
+ attr_accessor :sso_jwt_secret,
16
+ :sso_client_id,
17
+ :sso_client_secret,
18
+ :sso_host,
19
+ :session_exp_time
20
+
21
+ def initialize(**options)
22
+ @sso_jwt_secret = options[:sso_jwt_secret] || ENV['SSO_JWT_SECRET']
23
+ @sso_client_id = options[:sso_client_id] || ENV['SSO_CLIENT_ID']
24
+ @sso_client_secret = options[:sso_client_secret] || ENV['SSO_CLIENT_SECRET']
25
+ @sso_host = options[:sso_host] || ENV['SSO_HOST']
26
+ @session_exp_time = options[:session_exp_time] || ENV['SESSION_EXP_TIME']
27
+ yield(self) if block_given?
28
+ end
29
+ end
30
+
31
+ class TokenOauthV1 < BaseStrategy
32
+
33
+ attr_accessor :config, :context
34
+
35
+ def self.should_use?(ctx, config)
36
+ conf = config.is_a?(TokenAuthV1Config) ? config : TokenAuthV1Config.new(**config)
37
+ conf.sso_host.present? || ctx.env['HTTP_AUTHORIZATION'].present?
38
+ end
39
+
40
+ def initialize(config=TokenAuthV1Config.new, context)
41
+ if config.is_a?(Hash)
42
+ @config = TokenAuthV1Config.new(**config)
43
+ elsif config.is_a?(TokenAuthV1Config)
44
+ @config = config
45
+ end
46
+ @context = context
47
+ header = @context.env['HTTP_AUTHORIZATION']
48
+ raise ::Aid::Auth::Errors::Unauthorized unless header
49
+ @token = header.split(' ').last
50
+ raise ::Aid::Auth::InvalidToken unless @token
51
+ end
52
+
53
+ def current_user_id
54
+ @user_id ||= decode_jwt_token(@token)[0].dig('sub')
55
+ end
56
+
57
+ def authenticated?
58
+ !!current_user_id
59
+ end
60
+
61
+ private
62
+
63
+ def decode_jwt_token(token)
64
+ JWT.decode token, @config.sso_jwt_secret, true, { algorithm: 'HS512' }
65
+ rescue StandardError
66
+ [{}, {}]
67
+ end
68
+
69
+ end
70
+ end
71
+ end
72
+ end
73
+
@@ -0,0 +1,13 @@
1
+ require_relative 'strategies/base_strategy'
2
+ require_relative 'strategies/kratos_direct_v1'
3
+ require_relative 'strategies/token_oauth_v1'
4
+ require_relative 'strategies/null'
5
+
6
+ module Aid
7
+ module Auth
8
+ module Strategies
9
+ ## Just for keep
10
+ end
11
+ end
12
+ end
13
+
data/lib/aid/auth.rb ADDED
@@ -0,0 +1,13 @@
1
+ require 'jwt'
2
+ require_relative 'auth/kratos/api'
3
+ require_relative 'auth/manager'
4
+ require_relative 'auth/helper'
5
+ require_relative 'auth/context'
6
+ require_relative 'auth/strategies'
7
+ require_relative 'auth/errors'
8
+
9
+ module Aid
10
+ module Auth
11
+
12
+ end
13
+ end
data/lib/aid/errors.rb ADDED
@@ -0,0 +1,7 @@
1
+ module Aid
2
+ module Errors
3
+ class Base < StandardError
4
+
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,39 @@
1
+ module Aid
2
+ module Redis
3
+ class Instance
4
+
5
+ DEFAULT_REDIS_HOST = ENV.fetch('REDIS_URL', 'redis://localhost:6379/1').freeze
6
+
7
+ cattr_accessor :redis
8
+
9
+ # Example
10
+ #
11
+ # 1) With config
12
+ # Aid::Redis::Instance.configure do |config|
13
+ # config.redis = Redis.new(url: ENV['REDIS_URL'])
14
+ # end
15
+ # $redis = Aid::Redis::Instance.get
16
+ #
17
+ # 2) Default
18
+ # $redis = Aid::Redis::Instance.get #!!! Needs REDIS_URL ENV.
19
+
20
+ class << self
21
+
22
+ def configure
23
+ yield(self)
24
+ end
25
+
26
+ def default
27
+ self.redis = ::Redis.new(url: DEFAULT_REDIS_HOST)
28
+ end
29
+
30
+ def get
31
+ self.redis || default
32
+ end
33
+
34
+ end
35
+
36
+ end
37
+ end
38
+ end
39
+
@@ -0,0 +1,41 @@
1
+ module Aid
2
+ module Redis
3
+ class Manager
4
+
5
+ DEFAULT_TTL = 2.hour
6
+
7
+ attr_accessor :redis
8
+
9
+ # Example
10
+ #
11
+ # manager = Aid::Redis::Manager.new
12
+ # key = manager.setex_with_key('some data')
13
+ # data = manager.get_by_key('key')
14
+
15
+ def initialize
16
+ @redis = Instance.get
17
+ end
18
+
19
+ def set_with_key(data = {}, key = SecureRandom.uuid)
20
+ redis.set(key, data)
21
+ key
22
+ end
23
+
24
+ def setex_with_key(data = {}, key = SecureRandom.uuid, ttl = DEFAULT_TTL)
25
+ redis.setex(key, ttl, data)
26
+ key
27
+ end
28
+
29
+ def get_by_key(key)
30
+ res = redis.get(key)
31
+ block_given? ? yield(res) : res
32
+ end
33
+
34
+ def del_by_key(key)
35
+ redis.del(key)
36
+ end
37
+
38
+ end
39
+ end
40
+ end
41
+
data/lib/aid/redis.rb ADDED
@@ -0,0 +1,10 @@
1
+ require 'redis'
2
+ require 'securerandom'
3
+ require_relative 'redis/instance'
4
+ require_relative 'redis/manager'
5
+
6
+ module Aid
7
+ module Redis
8
+
9
+ end
10
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AidCommon
4
+ VERSION = "0.1.4"
5
+ end
data/lib/aid.rb ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "aid/version"
4
+ require_relative 'aid/errors'
5
+ require_relative 'aid/auth'
6
+ require_relative 'aid/redis'
7
+
8
+ module Aid
9
+ # Just for keep
10
+ end
@@ -0,0 +1,6 @@
1
+ module Aid
2
+ module Common
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,117 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: aid-common
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.4
5
+ platform: ruby
6
+ authors:
7
+ - Yury Ivannikov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-09-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ory-kratos-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.10.1
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.10.1
27
+ - !ruby/object:Gem::Dependency
28
+ name: jwt
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: 2.1.1
34
+ - - "<"
35
+ - !ruby/object:Gem::Version
36
+ version: '3'
37
+ type: :runtime
38
+ prerelease: false
39
+ version_requirements: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: 2.1.1
44
+ - - "<"
45
+ - !ruby/object:Gem::Version
46
+ version: '3'
47
+ - !ruby/object:Gem::Dependency
48
+ name: redis
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: 4.2.5
54
+ type: :runtime
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: 4.2.5
61
+ description: A.ID Shared Functionality Gem
62
+ email:
63
+ - yi@ariv.al
64
+ executables: []
65
+ extensions: []
66
+ extra_rdoc_files: []
67
+ files:
68
+ - ".rspec"
69
+ - CODE_OF_CONDUCT.md
70
+ - Gemfile
71
+ - Gemfile.lock
72
+ - LICENSE.txt
73
+ - README.md
74
+ - Rakefile
75
+ - aid-common.gemspec
76
+ - lib/aid.rb
77
+ - lib/aid/auth.rb
78
+ - lib/aid/auth/context.rb
79
+ - lib/aid/auth/errors.rb
80
+ - lib/aid/auth/helper.rb
81
+ - lib/aid/auth/kratos/api.rb
82
+ - lib/aid/auth/manager.rb
83
+ - lib/aid/auth/strategies.rb
84
+ - lib/aid/auth/strategies/base_strategy.rb
85
+ - lib/aid/auth/strategies/kratos_direct_v1.rb
86
+ - lib/aid/auth/strategies/null.rb
87
+ - lib/aid/auth/strategies/token_oauth_v1.rb
88
+ - lib/aid/errors.rb
89
+ - lib/aid/redis.rb
90
+ - lib/aid/redis/instance.rb
91
+ - lib/aid/redis/manager.rb
92
+ - lib/aid/version.rb
93
+ - sig/aid/common.rbs
94
+ homepage:
95
+ licenses:
96
+ - MIT
97
+ metadata: {}
98
+ post_install_message:
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: 2.6.0
107
+ required_rubygems_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ requirements: []
113
+ rubygems_version: 3.3.7
114
+ signing_key:
115
+ specification_version: 4
116
+ summary: A.ID Shared Functionality Gem
117
+ test_files: []