api_warden 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
+ SHA1:
3
+ metadata.gz: 0282ed518cd01a9417d7691212753f1fe7508cca
4
+ data.tar.gz: bf85675a76299613094ad4c9651e2ea82dc9524d
5
+ SHA512:
6
+ metadata.gz: c9676158663b2b151b3ba98f631671bea10e91a64c9654a4b977e119fd7c8097ab847a741eaf30100ba4bc6fe03498c52e6a1d0ece499a2e1b61b31ba1219479
7
+ data.tar.gz: 4a01e7bcb7505a6abe4eb573d53ad01e197d55547aa11c5f5acc5a3615543e2b4ae04125363a17d58907fa16afbd5e9beed854be99e01701a5abb2258c258c92
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2.5
5
+ before_install: gem install bundler -v 1.16.0
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at 327110424@163.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ gemspec
6
+
7
+ gem "rails", "4.2.10"
8
+
9
+ group :test do
10
+ gem 'rspec-rails', '~> 3.6'
11
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,148 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ api_warden (0.1.0)
5
+ connection_pool (~> 2.2, >= 2.2.0)
6
+ redis (~> 3.2, >= 3.2.1)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ actionmailer (4.2.10)
12
+ actionpack (= 4.2.10)
13
+ actionview (= 4.2.10)
14
+ activejob (= 4.2.10)
15
+ mail (~> 2.5, >= 2.5.4)
16
+ rails-dom-testing (~> 1.0, >= 1.0.5)
17
+ actionpack (4.2.10)
18
+ actionview (= 4.2.10)
19
+ activesupport (= 4.2.10)
20
+ rack (~> 1.6)
21
+ rack-test (~> 0.6.2)
22
+ rails-dom-testing (~> 1.0, >= 1.0.5)
23
+ rails-html-sanitizer (~> 1.0, >= 1.0.2)
24
+ actionview (4.2.10)
25
+ activesupport (= 4.2.10)
26
+ builder (~> 3.1)
27
+ erubis (~> 2.7.0)
28
+ rails-dom-testing (~> 1.0, >= 1.0.5)
29
+ rails-html-sanitizer (~> 1.0, >= 1.0.3)
30
+ activejob (4.2.10)
31
+ activesupport (= 4.2.10)
32
+ globalid (>= 0.3.0)
33
+ activemodel (4.2.10)
34
+ activesupport (= 4.2.10)
35
+ builder (~> 3.1)
36
+ activerecord (4.2.10)
37
+ activemodel (= 4.2.10)
38
+ activesupport (= 4.2.10)
39
+ arel (~> 6.0)
40
+ activesupport (4.2.10)
41
+ i18n (~> 0.7)
42
+ minitest (~> 5.1)
43
+ thread_safe (~> 0.3, >= 0.3.4)
44
+ tzinfo (~> 1.1)
45
+ arel (6.0.4)
46
+ builder (3.2.3)
47
+ concurrent-ruby (1.0.5)
48
+ connection_pool (2.2.1)
49
+ crass (1.0.3)
50
+ diff-lcs (1.3)
51
+ erubis (2.7.0)
52
+ fakeredis (0.6.0)
53
+ redis (~> 3.2)
54
+ globalid (0.4.1)
55
+ activesupport (>= 4.2.0)
56
+ i18n (0.9.1)
57
+ concurrent-ruby (~> 1.0)
58
+ loofah (2.1.1)
59
+ crass (~> 1.0.2)
60
+ nokogiri (>= 1.5.9)
61
+ mail (2.7.0)
62
+ mini_mime (>= 0.1.1)
63
+ mini_mime (1.0.0)
64
+ mini_portile2 (2.3.0)
65
+ minitest (5.10.3)
66
+ nokogiri (1.8.1)
67
+ mini_portile2 (~> 2.3.0)
68
+ rack (1.6.8)
69
+ rack-test (0.6.3)
70
+ rack (>= 1.0)
71
+ rails (4.2.10)
72
+ actionmailer (= 4.2.10)
73
+ actionpack (= 4.2.10)
74
+ actionview (= 4.2.10)
75
+ activejob (= 4.2.10)
76
+ activemodel (= 4.2.10)
77
+ activerecord (= 4.2.10)
78
+ activesupport (= 4.2.10)
79
+ bundler (>= 1.3.0, < 2.0)
80
+ railties (= 4.2.10)
81
+ sprockets-rails
82
+ rails-deprecated_sanitizer (1.0.3)
83
+ activesupport (>= 4.2.0.alpha)
84
+ rails-dom-testing (1.0.9)
85
+ activesupport (>= 4.2.0, < 5.0)
86
+ nokogiri (~> 1.6)
87
+ rails-deprecated_sanitizer (>= 1.0.1)
88
+ rails-html-sanitizer (1.0.3)
89
+ loofah (~> 2.0)
90
+ railties (4.2.10)
91
+ actionpack (= 4.2.10)
92
+ activesupport (= 4.2.10)
93
+ rake (>= 0.8.7)
94
+ thor (>= 0.18.1, < 2.0)
95
+ rake (10.4.2)
96
+ redis (3.3.5)
97
+ redis-namespace (1.6.0)
98
+ redis (>= 3.0.4)
99
+ rspec (3.6.0)
100
+ rspec-core (~> 3.6.0)
101
+ rspec-expectations (~> 3.6.0)
102
+ rspec-mocks (~> 3.6.0)
103
+ rspec-core (3.6.0)
104
+ rspec-support (~> 3.6.0)
105
+ rspec-expectations (3.6.0)
106
+ diff-lcs (>= 1.2.0, < 2.0)
107
+ rspec-support (~> 3.6.0)
108
+ rspec-json_expectations (2.1.0)
109
+ rspec-mocks (3.6.0)
110
+ diff-lcs (>= 1.2.0, < 2.0)
111
+ rspec-support (~> 3.6.0)
112
+ rspec-rails (3.6.1)
113
+ actionpack (>= 3.0)
114
+ activesupport (>= 3.0)
115
+ railties (>= 3.0)
116
+ rspec-core (~> 3.6.0)
117
+ rspec-expectations (~> 3.6.0)
118
+ rspec-mocks (~> 3.6.0)
119
+ rspec-support (~> 3.6.0)
120
+ rspec-support (3.6.0)
121
+ sprockets (3.7.1)
122
+ concurrent-ruby (~> 1.0)
123
+ rack (> 1, < 3)
124
+ sprockets-rails (3.2.1)
125
+ actionpack (>= 4.0)
126
+ activesupport (>= 4.0)
127
+ sprockets (>= 3.0.0)
128
+ thor (0.20.0)
129
+ thread_safe (0.3.6)
130
+ tzinfo (1.2.4)
131
+ thread_safe (~> 0.1)
132
+
133
+ PLATFORMS
134
+ ruby
135
+
136
+ DEPENDENCIES
137
+ api_warden!
138
+ bundler (~> 1.16)
139
+ fakeredis
140
+ rails (= 4.2.10)
141
+ rake (~> 10.0)
142
+ redis-namespace (~> 1.5, >= 1.5.2)
143
+ rspec (~> 3.0)
144
+ rspec-json_expectations
145
+ rspec-rails (~> 3.6)
146
+
147
+ BUNDLED WITH
148
+ 1.16.0
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Mingxiang Xue
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,56 @@
1
+ # ApiWarden
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/api_warden`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'api_warden'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install api_warden
22
+
23
+ ## Usage
24
+
25
+ Create a file config/initializers/api_warden.rb.
26
+
27
+ Add the below codes:
28
+ ```
29
+ ApiWarden.configure do |config|
30
+ config.redis = {
31
+ host: 'localhost',
32
+ port: 8877,
33
+ size: 8
34
+ }
35
+ end
36
+
37
+ ApiWarden.ward_by('users')
38
+ ```
39
+
40
+ ## Development
41
+
42
+ 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.
43
+
44
+ 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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
45
+
46
+ ## Contributing
47
+
48
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/api_warden. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
49
+
50
+ ## License
51
+
52
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
53
+
54
+ ## Code of Conduct
55
+
56
+ Everyone interacting in the ApiWarden project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/api_warden/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,30 @@
1
+ lib = File.expand_path('../lib', __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'api_warden/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'api_warden'
7
+ spec.version = ApiWarden::VERSION
8
+ spec.authors = ['Mingxiang Xue']
9
+ spec.email = ['327110424@163.com']
10
+
11
+ spec.summary = 'Use access token to protect your API in rails.'
12
+ spec.description = 'Use access token to protect your API in rails.'
13
+ spec.homepage = 'https://github.com/UzxMx/api_warden'
14
+ spec.license = 'MIT'
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
17
+ f.match(%r{^(test|spec|features)/})
18
+ end
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_dependency 'redis', '~> 3.2', '>= 3.2.1'
22
+ spec.add_dependency 'connection_pool', '~> 2.2', '>= 2.2.0'
23
+
24
+ spec.add_development_dependency 'redis-namespace', '~> 1.5', '>= 1.5.2'
25
+ spec.add_development_dependency 'fakeredis'
26
+ spec.add_development_dependency 'bundler', '~> 1.16'
27
+ spec.add_development_dependency 'rake', '~> 10.0'
28
+ spec.add_development_dependency 'rspec', '~> 3.0'
29
+ spec.add_development_dependency 'rspec-json_expectations'
30
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "api_warden"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lib/api_warden.rb ADDED
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails'
4
+ require 'connection_pool'
5
+
6
+ module ApiWarden
7
+ autoload :Authentication, 'api_warden/authentication'
8
+ autoload :Helpers, 'api_warden/helpers'
9
+ autoload :RedisConnection, 'api_warden/redis_connection'
10
+ autoload :Scope, 'api_warden/scope'
11
+ autoload :Version, 'api_warden/version'
12
+
13
+ SCOPES = Hash.new
14
+
15
+ # Configuration for ApiWarden, use like:
16
+ #
17
+ # ApiWarden.configure do |config|
18
+ # config.redis = { :namespace => 'myapp', :size => 1, :url => 'redis://myhost:8877/0' }
19
+ # end
20
+ def self.configure
21
+ yield self
22
+ end
23
+
24
+ # Add a scope to ward. Some methods related with the scope will be generated and mixed into
25
+ # ActionController::Base.
26
+ #
27
+ # ==== Examples
28
+ #
29
+ # ApiWarden.ward_by('users')
30
+ # ApiWarden.ward_by('users', expire_time_for_access_token: 2.days.seconds)
31
+ # ApiWarden.ward_by('users', value_for_access_token: proc { |access_token, *args| ... })
32
+ #
33
+ # @param scope [String]
34
+ # @param options [Hash] see Scope#initialize
35
+ def self.ward_by(scope, options = {})
36
+ name = validate_scope_name(scope)
37
+ raise "Scope #{name} already defined" if find_scope(name)
38
+
39
+ scope = Scope.new(name, options)
40
+ SCOPES[name] = scope
41
+ Helpers.define_helpers(scope)
42
+ end
43
+
44
+ # @return [Boolean] true if removed successfully, false otherwise.
45
+ def self.remove_ward_by(scope)
46
+ if scope = find_scope(scope)
47
+ Helpers.remove_helpers(scope)
48
+ SCOPES.delete(scope.name)
49
+ true
50
+ else
51
+ false
52
+ end
53
+ end
54
+
55
+ def self.find_scope(name)
56
+ name = validate_scope_name(name)
57
+ SCOPES[name]
58
+ end
59
+
60
+ def self.redis
61
+ raise ArgumentError, 'requires a block' unless block_given?
62
+ redis_pool.with do |conn|
63
+ retryable = true
64
+ begin
65
+ yield conn
66
+ rescue Redis::CommandError => ex
67
+ # Failover can cause the server to become a slave, need
68
+ # to disconnect and reopen the socket to get back to the master.
69
+ (conn.disconnect!; retryable = false; retry) if retryable && ex.message =~ /READONLY/
70
+ raise
71
+ end
72
+ end
73
+ end
74
+
75
+ def self.redis_pool
76
+ @redis ||= RedisConnection.create
77
+ end
78
+
79
+ def self.redis=(hash)
80
+ @redis = if hash.is_a?(ConnectionPool)
81
+ hash
82
+ elsif hash
83
+ RedisConnection.create(hash)
84
+ end
85
+ end
86
+
87
+ # Generate a friendly string randomly to be used as token.
88
+ # By default, length is 20 characters.
89
+ def self.friendly_token(length = 20)
90
+ # To calculate real characters, we must perform this operation.
91
+ # See SecureRandom.urlsafe_base64
92
+ rlength = (length * 3) / 4
93
+ SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz')
94
+ end
95
+
96
+ private
97
+ def self.validate_scope_name(scope)
98
+ scope.to_s.singularize.downcase
99
+ end
100
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiWarden
4
+ class Authentication
5
+ autoload :Params, 'api_warden/authentication/params'
6
+ autoload :HeaderParams, 'api_warden/authentication/header_params'
7
+
8
+ attr_reader :scope, :request, :params
9
+
10
+ def initialize(scope, request)
11
+ @scope = scope
12
+ @request = request
13
+ @params = scope.params_class.new(self)
14
+ end
15
+
16
+ def authenticated?
17
+ ensure_authenticated
18
+ @authenticated
19
+ end
20
+
21
+ def refreshable?
22
+ ensure_refreshable
23
+ @refreshable
24
+ end
25
+
26
+ def id
27
+ ensure_authenticated_or_refreshable
28
+ @id
29
+ end
30
+
31
+ def value_for_access_token
32
+ ensure_authenticated
33
+ @value_for_access_token
34
+ end
35
+
36
+ def value_for_refresh_token
37
+ ensure_refreshable
38
+ @value_for_refresh_token
39
+ end
40
+
41
+ # @return self
42
+ def authenticate
43
+ authenticate!
44
+ rescue AuthenticationError => e
45
+ self
46
+ end
47
+
48
+ # This method will only authenticate once, and cache the result.
49
+ #
50
+ # @return self
51
+ def authenticate!
52
+ return unless @authenticated.nil?
53
+
54
+ id, access_token = @params.retrieve_id, @params.retrieve_access_token
55
+ key = @scope.key_for_access_token(id, access_token)
56
+
57
+ if access_token && !access_token.empty?
58
+ ApiWarden.redis { |conn| @value_for_access_token = conn.get(key) }
59
+ end
60
+
61
+ unless @value_for_access_token
62
+ @authenticated = false
63
+ raise AuthenticationError
64
+ end
65
+
66
+ @authenticated = true
67
+ @id = id
68
+ @access_token = access_token
69
+ self
70
+ end
71
+
72
+ def validate_refresh_token
73
+ validate_refresh_token!
74
+ rescue AuthenticationError => e
75
+ end
76
+
77
+ def validate_refresh_token!
78
+ return unless @refreshable.nil?
79
+
80
+ id, refresh_token = @params.retrieve_id, @params.retrieve_refresh_token
81
+ key = @scope.key_for_refresh_token(id, refresh_token)
82
+
83
+ if refresh_token && !refresh_token.empty?
84
+ ApiWarden.redis do |conn|
85
+ @value_for_refresh_token = conn.get(key)
86
+ conn.del(key)
87
+ end
88
+ end
89
+
90
+ unless @value_for_refresh_token
91
+ @refreshable = false
92
+ raise AuthenticationError
93
+ end
94
+
95
+ @refreshable = true
96
+ @id = id
97
+ self
98
+ end
99
+
100
+ # TODO remove refresh token as well
101
+ def sign_out
102
+ key = @scope.key_for_access_token(@id, @access_token)
103
+
104
+ ApiWarden.redis { |conn| conn.del(key) }
105
+ end
106
+
107
+ private
108
+ def ensure_authenticated
109
+ return unless @authenticated.nil?
110
+ authenticate
111
+ end
112
+
113
+ def ensure_refreshable
114
+ return unless @refreshable.nil?
115
+ validate_refresh_token
116
+ end
117
+
118
+ def ensure_authenticated_or_refreshable
119
+ ensure_authenticated
120
+ ensure_refreshable unless @authenticated
121
+ end
122
+
123
+ class AuthenticationError < Exception
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiWarden
4
+ class Authentication
5
+ class HeaderParams < Params
6
+
7
+ def headers
8
+ request.headers
9
+ end
10
+
11
+ def retrieve_id
12
+ @id ||= headers["X-#{scope.name.camelize}-Id"]
13
+ end
14
+
15
+ def retrieve_access_token
16
+ @access_token ||= headers["X-#{scope.name.camelize}-Access-Token"]
17
+ end
18
+
19
+ def retrieve_refresh_token
20
+ @refresh_token ||= headers["X-#{scope.name.camelize}-Refresh-Token"]
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiWarden
4
+ class Authentication
5
+ class Params
6
+ attr_reader :authentication
7
+
8
+ def initialize(authentication)
9
+ @authentication = authentication
10
+ end
11
+
12
+ def scope
13
+ authentication.scope
14
+ end
15
+
16
+ def request
17
+ authentication.request
18
+ end
19
+
20
+ def retrieve_id
21
+ raise NotImplementedError
22
+ end
23
+
24
+ def retrieve_access_token
25
+ raise NotImplementedError
26
+ end
27
+
28
+ def retrieve_refresh_token
29
+ raise NotImplementedError
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiWarden
4
+ module Helpers
5
+ autoload :Accessable, 'api_warden/helpers/accessable'
6
+ autoload :Refreshable, 'api_warden/helpers/refreshable'
7
+
8
+ def self.define_helpers(scope)
9
+ name = scope.name
10
+
11
+ class_eval <<-METHODS, __FILE__, __LINE__ + 1
12
+ def ward_by_#{name}
13
+ ward_by("#{name}")
14
+ end
15
+
16
+ def ward_by_#{name}!
17
+ ward_by!("#{name}")
18
+ end
19
+
20
+ def current_#{name}_authentication
21
+ current_authentication_for("#{name}")
22
+ end
23
+
24
+ def current_#{name}_id
25
+ current_#{name}_authentication.id
26
+ end
27
+
28
+ def current_#{name}_value_for_access_token
29
+ current_#{name}_authentication.value_for_access_token
30
+ end
31
+
32
+ def #{name}_signed_in?
33
+ current_#{name}_authentication.authenticated?
34
+ end
35
+
36
+ def generate_access_token_for_#{name}(id, *args)
37
+ generate_access_token_for("#{name}", id, *args)
38
+ end
39
+ METHODS
40
+
41
+ if scope.load_owner.respond_to?(:call)
42
+ class_eval <<-METHODS, __FILE__, __LINE__ + 1
43
+ def current_#{name}
44
+ unless @current_#{name}
45
+ scope = ApiWarden.find_scope("#{name}")
46
+ @current_#{name} = scope.load_owner.call(
47
+ current_#{name}_id,
48
+ current_#{name}_value_for_access_token,
49
+ current_#{name}_authentication
50
+ )
51
+ end
52
+ @current_#{name}
53
+ end
54
+ METHODS
55
+ end
56
+
57
+ unless scope.disable_refresh_token?
58
+ class_eval <<-METHODS, __FILE__, __LINE__ + 1
59
+ def generate_refresh_token_for_#{name}(id, *args)
60
+ generate_refresh_token_for("#{name}", id, *args)
61
+ end
62
+
63
+ def generate_tokens_for_#{name}(id, *args)
64
+ [generate_access_token_for_#{name}(id, *args), generate_refresh_token_for_#{name}(id, *args)]
65
+ end
66
+
67
+ def validate_refresh_token_for_#{name}!
68
+ validate_refresh_token_for!("#{name}")
69
+ end
70
+ METHODS
71
+ end
72
+
73
+ ActiveSupport.on_load(:action_controller) do
74
+ include ApiWarden::Helpers, Accessable
75
+ include Refreshable unless scope.disable_refresh_token?
76
+
77
+ if respond_to?(:helper_method)
78
+ helper_method "current_#{name}_authentication", "current_#{name}_id", "current_#{name}_value_for_access_token", "#{name}_signed_in?"
79
+
80
+ if scope.load_owner.respond_to?(:call)
81
+ helper_method "current_#{name}"
82
+ end
83
+ end
84
+ end
85
+ end
86
+
87
+ def self.remove_helpers(scope)
88
+ name = scope.name
89
+
90
+ ["ward_by_#{name}",
91
+ "ward_by_#{name}!",
92
+ "current_#{name}_authentication",
93
+ "current_#{name}_id",
94
+ "current_#{name}_value_for_access_token",
95
+ "#{name}_signed_in?",
96
+ "generate_access_token_for_#{name}"].each { |s| undef_method s }
97
+
98
+ unless scope.disable_refresh_token?
99
+ ["generate_refresh_token_for_#{name}",
100
+ "generate_tokens_for_#{name}",
101
+ "validate_refresh_token_for_#{name}!"].each { |s| undef_method s }
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiWarden
4
+ module Helpers
5
+ module Accessable
6
+ # @return [Boolean] whether or not authenticated
7
+ def ward_by(scope)
8
+ current_authentication_for(scope).authenticated?
9
+ end
10
+
11
+ # If not authenticated, an unauthorized response is rendered.
12
+ #
13
+ # @return [Boolean] whether or not authenticated
14
+ def ward_by!(scope)
15
+ scope = validate_scope(scope)
16
+
17
+ authentication = current_authentication_for(scope)
18
+ unless authentication.authenticated?
19
+ if (block = scope.on_authenticate_failed) && block.respond_to?(:call)
20
+ instance_exec(authentication, &block)
21
+ else
22
+ render json: { err_msg: 'Unauthorized' }, status: 401
23
+ end
24
+ false
25
+ else
26
+ true
27
+ end
28
+ end
29
+
30
+ def current_authentication_for(scope)
31
+ scope = validate_scope(scope)
32
+
33
+ ivar_authentication = "@current_#{scope.name}_authentication"
34
+ unless authentication = instance_variable_get(ivar_authentication)
35
+ authentication = Authentication.new(scope, request)
36
+ instance_variable_set(ivar_authentication, authentication)
37
+ else
38
+ authentication
39
+ end
40
+ end
41
+
42
+ def generate_access_token_for(scope, id, *args)
43
+ scope = validate_scope(scope)
44
+
45
+ access_token = ApiWarden.friendly_token(20)
46
+
47
+ ApiWarden.redis do |conn|
48
+ conn.set(scope.key_for_access_token(id, access_token),
49
+ scope.value_for_access_token(access_token, *args),
50
+ ex: scope.expire_time_for_access_token
51
+ )
52
+ end
53
+
54
+ access_token
55
+ end
56
+
57
+ private
58
+ def validate_scope(scope)
59
+ scope.is_a?(String) ? ApiWarden.find_scope(scope) : scope
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiWarden
4
+ module Helpers
5
+ module Refreshable
6
+ def generate_refresh_token_for(scope, id, *args)
7
+ scope = validate_scope(scope)
8
+
9
+ refresh_token = ApiWarden.friendly_token(30)
10
+
11
+ ApiWarden.redis do |conn|
12
+ conn.set(scope.key_for_refresh_token(id, refresh_token),
13
+ scope.value_for_refresh_token(refresh_token, *args),
14
+ ex: scope.expire_time_for_refresh_token
15
+ )
16
+ end
17
+
18
+ refresh_token
19
+ end
20
+
21
+ # If not refreshable, a forbidden response is rendered.
22
+ #
23
+ # @return [Boolean] whether or not refreshable
24
+ def validate_refresh_token_for!(scope)
25
+ scope = validate_scope(scope)
26
+
27
+ authentication = current_authentication_for(scope)
28
+ unless authentication.refreshable?
29
+ if (block = scope.on_refresh_failed) && block.respond_to?(:call)
30
+ instance_exec(authentication, &block)
31
+ else
32
+ render json: { err_msg: 'Forbidden' }, status: 403
33
+ end
34
+ false
35
+ else
36
+ true
37
+ end
38
+ end
39
+
40
+ private
41
+ def validate_scope(scope)
42
+ scope.is_a?(String) ? ApiWarden.find_scope(scope) : scope
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'connection_pool'
4
+ require 'redis'
5
+
6
+ module ApiWarden
7
+ class RedisConnection
8
+ class << self
9
+
10
+ def create(options = {})
11
+ options[:url] ||= determine_redis_provider
12
+ size = options[:size] || 5
13
+ pool_timeout = options[:pool_timeout] || 1
14
+ ConnectionPool.new(:timeout => pool_timeout, :size => size) do
15
+ build_client(options)
16
+ end
17
+ end
18
+
19
+ private
20
+
21
+ def build_client(options)
22
+ namespace = options[:namespace]
23
+
24
+ client = Redis.new client_opts(options)
25
+ if namespace
26
+ begin
27
+ require 'redis/namespace'
28
+ Redis::Namespace.new(namespace, :redis => client)
29
+ rescue LoadError
30
+ puts "Your Redis configuration uses the namespace '#{namespace}' but the redis-namespace gem is not included in the Gemfile." \
31
+ "Add the gem to your Gemfile to continue using a namespace. Otherwise, remove the namespace parameter."
32
+ exit(-127)
33
+ end
34
+ else
35
+ client
36
+ end
37
+ end
38
+
39
+ def client_opts(options)
40
+ opts = options.dup
41
+ if opts[:namespace]
42
+ opts.delete(:namespace)
43
+ end
44
+
45
+ if opts[:network_timeout]
46
+ opts[:timeout] = opts[:network_timeout]
47
+ opts.delete(:network_timeout)
48
+ end
49
+
50
+ opts[:driver] ||= 'ruby'
51
+
52
+ # redis-rb will silently retry an operation.
53
+ # This can lead to duplicate jobs if Sidekiq::Client's LPUSH
54
+ # is performed twice but I believe this is much, much rarer
55
+ # than the reconnect silently fixing a problem; we keep it
56
+ # on by default.
57
+ opts[:reconnect_attempts] ||= 1
58
+
59
+ opts
60
+ end
61
+
62
+ def determine_redis_provider
63
+ ENV[ENV['REDIS_PROVIDER'] || 'REDIS_URL']
64
+ end
65
+
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiWarden
4
+ class Scope
5
+ EXPIRE_TIME_FOR_ACCESS_TOKEN = 7.days.seconds
6
+ EXPIRE_TIME_FOR_REFRESH_TOKEN = 14.days.seconds
7
+
8
+ attr_reader :name, :options
9
+
10
+ # ==== Options
11
+ #
12
+ # * params_class: [ApiWarden::Authentication::Params]
13
+ # the class from which to retrieve authentication related params. Default is
14
+ # ApiWarden::Authentication::HeaderParams.
15
+ #
16
+ # * load_owner: [Proc]
17
+ # the block to be called to load the owner for the scope, so that you can call current_#{scope}
18
+ # to access the owner. Id, value for the access token and the authentication will be passed as arguments.
19
+ #
20
+ # ApiWarden.ward_by(:users, load_owner: proc { |id, value, auth| User.find(id) })
21
+ #
22
+ # * disable_refresh_token: [Boolean]
23
+ # whether or not to disable using refresh token to refresh access token. Default is false.
24
+ #
25
+ # * expire_time_for_access_token: [Fixnum]
26
+ # the expire time for access token in seconds. Default is EXPIRE_TIME_FOR_ACCESS_TOKEN.
27
+ #
28
+ # * value_for_access_token: [Proc]
29
+ # the block will be called to obtain the value for the access token key. The block will be
30
+ # passed with access_token, and other args you specified when calling generate_tokens_for.
31
+ # By default the access token will be used as the value.
32
+ #
33
+ # * on_authenticate_failed: [Proc]
34
+ # the block to be called when authentication failed. An authentication will be passed as an argument.
35
+ #
36
+ # * expire_time_for_refresh_token: [Fixnum]
37
+ # the expire time for refresh token in seconds, default is EXPIRE_TIME_FOR_REFRESH_TOKEN.
38
+ #
39
+ # * value_for_refresh_token: [Proc]
40
+ # the block will be called to obtain the value for the refresh token key. The block will be
41
+ # passed with refresh_token, and other args you specified when calling generate_tokens_for.
42
+ # By default the refresh token will be used as the value.
43
+ #
44
+ # * on_refresh_failed: [Proc]
45
+ # the block to be called when refreshing failed. An authentication will be passed as an argument.
46
+ def initialize(name, options = {})
47
+ @name = name
48
+
49
+ options[:params_class] ||= ApiWarden::Authentication::HeaderParams
50
+ options[:disable_refresh_token] ||= false
51
+ options[:expire_time_for_access_token] ||= EXPIRE_TIME_FOR_ACCESS_TOKEN
52
+ options[:expire_time_for_refresh_token] ||= EXPIRE_TIME_FOR_REFRESH_TOKEN
53
+
54
+ @options = options
55
+ end
56
+
57
+ def key_for_access_token(id, access_token)
58
+ "#{@name}_#{id}_access_token_#{access_token}"
59
+ end
60
+
61
+ def value_for_access_token(access_token, *args)
62
+ if options[:value_for_access_token].respond_to?(:call)
63
+ options[:value_for_access_token].call(access_token, *args)
64
+ else
65
+ access_token
66
+ end
67
+ end
68
+
69
+ def key_for_refresh_token(id, refresh_token)
70
+ "#{@name}_#{id}_refresh_token_#{refresh_token}"
71
+ end
72
+
73
+ def value_for_refresh_token(refresh_token, *args)
74
+ if options[:value_for_refresh_token].respond_to?(:call)
75
+ options[:value_for_refresh_token].call(refresh_token, *args)
76
+ else
77
+ refresh_token
78
+ end
79
+ end
80
+
81
+ private
82
+ def method_missing(method_name, *args)
83
+ key = (method_name[-1] == "?" ? method_name[0..-2] : method_name).to_sym
84
+ options[key]
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiWarden
4
+ VERSION = "0.1.0"
5
+ end
metadata ADDED
@@ -0,0 +1,196 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: api_warden
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mingxiang Xue
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-01-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: redis
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.2'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 3.2.1
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '3.2'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 3.2.1
33
+ - !ruby/object:Gem::Dependency
34
+ name: connection_pool
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '2.2'
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: 2.2.0
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - "~>"
48
+ - !ruby/object:Gem::Version
49
+ version: '2.2'
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: 2.2.0
53
+ - !ruby/object:Gem::Dependency
54
+ name: redis-namespace
55
+ requirement: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - "~>"
58
+ - !ruby/object:Gem::Version
59
+ version: '1.5'
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: 1.5.2
63
+ type: :development
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - "~>"
68
+ - !ruby/object:Gem::Version
69
+ version: '1.5'
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: 1.5.2
73
+ - !ruby/object:Gem::Dependency
74
+ name: fakeredis
75
+ requirement: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ type: :development
81
+ prerelease: false
82
+ version_requirements: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ - !ruby/object:Gem::Dependency
88
+ name: bundler
89
+ requirement: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - "~>"
92
+ - !ruby/object:Gem::Version
93
+ version: '1.16'
94
+ type: :development
95
+ prerelease: false
96
+ version_requirements: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - "~>"
99
+ - !ruby/object:Gem::Version
100
+ version: '1.16'
101
+ - !ruby/object:Gem::Dependency
102
+ name: rake
103
+ requirement: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - "~>"
106
+ - !ruby/object:Gem::Version
107
+ version: '10.0'
108
+ type: :development
109
+ prerelease: false
110
+ version_requirements: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - "~>"
113
+ - !ruby/object:Gem::Version
114
+ version: '10.0'
115
+ - !ruby/object:Gem::Dependency
116
+ name: rspec
117
+ requirement: !ruby/object:Gem::Requirement
118
+ requirements:
119
+ - - "~>"
120
+ - !ruby/object:Gem::Version
121
+ version: '3.0'
122
+ type: :development
123
+ prerelease: false
124
+ version_requirements: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - "~>"
127
+ - !ruby/object:Gem::Version
128
+ version: '3.0'
129
+ - !ruby/object:Gem::Dependency
130
+ name: rspec-json_expectations
131
+ requirement: !ruby/object:Gem::Requirement
132
+ requirements:
133
+ - - ">="
134
+ - !ruby/object:Gem::Version
135
+ version: '0'
136
+ type: :development
137
+ prerelease: false
138
+ version_requirements: !ruby/object:Gem::Requirement
139
+ requirements:
140
+ - - ">="
141
+ - !ruby/object:Gem::Version
142
+ version: '0'
143
+ description: Use access token to protect your API in rails.
144
+ email:
145
+ - 327110424@163.com
146
+ executables: []
147
+ extensions: []
148
+ extra_rdoc_files: []
149
+ files:
150
+ - ".gitignore"
151
+ - ".rspec"
152
+ - ".travis.yml"
153
+ - CODE_OF_CONDUCT.md
154
+ - Gemfile
155
+ - Gemfile.lock
156
+ - LICENSE.txt
157
+ - README.md
158
+ - Rakefile
159
+ - api_warden.gemspec
160
+ - bin/console
161
+ - bin/setup
162
+ - lib/api_warden.rb
163
+ - lib/api_warden/authentication.rb
164
+ - lib/api_warden/authentication/header_params.rb
165
+ - lib/api_warden/authentication/params.rb
166
+ - lib/api_warden/helpers.rb
167
+ - lib/api_warden/helpers/accessable.rb
168
+ - lib/api_warden/helpers/refreshable.rb
169
+ - lib/api_warden/redis_connection.rb
170
+ - lib/api_warden/scope.rb
171
+ - lib/api_warden/version.rb
172
+ homepage: https://github.com/UzxMx/api_warden
173
+ licenses:
174
+ - MIT
175
+ metadata: {}
176
+ post_install_message:
177
+ rdoc_options: []
178
+ require_paths:
179
+ - lib
180
+ required_ruby_version: !ruby/object:Gem::Requirement
181
+ requirements:
182
+ - - ">="
183
+ - !ruby/object:Gem::Version
184
+ version: '0'
185
+ required_rubygems_version: !ruby/object:Gem::Requirement
186
+ requirements:
187
+ - - ">="
188
+ - !ruby/object:Gem::Version
189
+ version: '0'
190
+ requirements: []
191
+ rubyforge_project:
192
+ rubygems_version: 2.6.14
193
+ signing_key:
194
+ specification_version: 4
195
+ summary: Use access token to protect your API in rails.
196
+ test_files: []