token_secret_auth 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 4eb919fd271312c8f4bc8eb9ad88f9df541e067f
4
+ data.tar.gz: b6baf874507a1c6f3660606a59514a5112839ab8
5
+ SHA512:
6
+ metadata.gz: f841553378bbf8e844dc24f0c047b5142c42f3a959b7c10f3d89569ca64c7e67db5e488a1de2b39ab2632cfbbab0a6a328ba678eec385851da9ea7912d4aa6e2
7
+ data.tar.gz: d97252337e1a6211273013af52c55856f3c79aff3b99698bf7fd5f5bc07cfdcf1671d09fe8d63c70534f626330ccd1b6026728662a33486d91e8289632bcce23
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.1.3
5
+ before_install: gem install bundler -v 1.15.3
@@ -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 tgaff@alumni.nd.edu. 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,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in token_secret_auth.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 tgaff
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,188 @@
1
+ # TokenSecretAuth
2
+
3
+ TokenSecretAuth aims to be a simple implementation of token+secret authentication.
4
+
5
+ Clients using this can send a token + secret that looks like: `{ token: "koV3Zel321fe", secret: "fffixk5ptz2puaf1sk3wo5szpkrpjnhp" }`
6
+
7
+ * **token** is a hashed form of the model **id**
8
+
9
+ * **secret** is randomly assigned and can be **encrypted** using `has_secure_password` or a similar implementation.
10
+
11
+ ## Why should I use this?
12
+
13
+
14
+ > OR Why did you release this?
15
+
16
+ Many APIs use a token or a token+secret to authenticate API clients. If that token+secret grants similar power as a login+password it **should be protected just like a password**
17
+
18
+ However, while looking for a gem to handle mobile API authentication I found that many solutions fit into one of two categories:
19
+
20
+ 1. They required Devise
21
+ 1. They did not encrypt the token (or secret) properly
22
+
23
+
24
+ ### Other benefits
25
+
26
+ * It's plain-old ruby - any model that responds to `.find(id)` and works with or in a manner similar to `has_secure_password` will work. (model instance should respond to `model_instance#password=`)
27
+ * Flexible: you can send token+secret in the URL or in the header or any other way you can interpret in a controller method.
28
+
29
+ ## Installation
30
+
31
+ Add this line to your application's Gemfile:
32
+
33
+ ```ruby
34
+ gem 'token_secret_auth'
35
+ ```
36
+
37
+ And then execute:
38
+
39
+ $ bundle
40
+
41
+ Or install it yourself as:
42
+
43
+ $ gem install token_secret_auth
44
+
45
+ In your model file add:
46
+
47
+ include TokenSecretAuth
48
+
49
+ This grants your model instances the following methods:
50
+
51
+ #token, #decode_token, #generate_secret
52
+
53
+ Also add to the model:
54
+
55
+ has_secure_password
56
+
57
+ Create and run a migration to add the `password_digest` field to your model.
58
+ For example on rails:
59
+
60
+ $ rails generate migration AddPasswordDigestToApiClients password_digest:string
61
+
62
+ Note: you do not need a 'token' field on your model. `#token` is a virtual attribute derived from the model ID. `password` is your secret.
63
+
64
+ ## Usage
65
+
66
+ #### Generating a token
67
+
68
+ Tokens are generated from the model ID.
69
+
70
+ ```ruby
71
+ SomeModel.find(1000).token # => o9WM01OR1jgD
72
+ ```
73
+
74
+ #### Generating a secret
75
+
76
+ Secrets are randomly generated by `Model.generate_secret` or `#generate_secret`.
77
+ Store the secret using `#password=` or similar encrypted functionality.
78
+
79
+ ```ruby
80
+ client = ApiClient.find_by_token('afuoisjdjl')
81
+ client.password = client.generate_secret
82
+ client.save # bcrypt/has_secure_password will handle encryption
83
+ ```
84
+
85
+ On Rails you may want to simply generate the password using active record callbacks:
86
+
87
+ ```ruby
88
+ before_validation :set_secret, on: [ :new, :create ]
89
+
90
+ def set_secret
91
+ self.password = generate_secret
92
+ end
93
+ ```
94
+
95
+
96
+ #### Passing token+secret to client
97
+
98
+ If your API allows a client to login and then receive a new API token+secret the responding controller method may look something like this.
99
+
100
+ ```ruby
101
+ def try_login
102
+ @email = login_params[:email]
103
+ @pass = login_params[:password]
104
+ @user = User.find_by(email: @email).try(:authenticate, @pass)
105
+ if @user
106
+ api_client = @user.api_clients.create
107
+ # IMPORTANT - this is the only time you can see the secret decrypted
108
+ render json: { token: api_client.token, secret: api_client.secret }
109
+ else
110
+ render json: {password: ["Invalid account or password"]}, status: :unauthorized
111
+ end
112
+ end
113
+ ```
114
+
115
+ To perform authentication with the token + secret, for example as a `before_action` in an `ApplicationController`:
116
+
117
+ ```ruby
118
+ def current_user
119
+ if params[:credentials]
120
+ token = credentials_params[:token]
121
+ secret = credentials_params[:secret]
122
+ begin
123
+ api_client = ApiClient.authenticate_by_credentials(token, secret)
124
+ rescue ActiveRecord::RecordNotFound
125
+ # if someone sends a decodable token but the record doesn't exist
126
+ end
127
+ end
128
+
129
+ if api_client
130
+ @current_user = api_client.user
131
+ else
132
+ render json: {errors: ['Unauthorized token or secret']}, status: :unauthorized }
133
+ end
134
+ end
135
+ ```
136
+
137
+ Headers are an even better way to pass authentication tokens. **TODO:**
138
+
139
+ ```ruby
140
+
141
+ ```
142
+
143
+
144
+ #### salt
145
+
146
+ If you'd like to change the salt used for hashing **IDs** to generate `token`s you can add an initializer:
147
+
148
+ ```ruby
149
+ # config/initializers/token_secret_auth.rb
150
+
151
+ TokenSecretAuth.configure do |config|
152
+ config.id_salt = 'some appropriately salty bytes'
153
+ end
154
+ ```
155
+
156
+ > Note: the salt used for hashing the secret (password) is controlled by your BCrypt config.
157
+
158
+ ## FAQ
159
+
160
+ ### Why not devise?
161
+
162
+ Devise is a great solution and I often recommend it. However, it is sometimes more complexity than needed for something this simple. TokenSecretAuth does not require devise.
163
+
164
+ ### Why do I need to encrypt my API token?
165
+
166
+ If your token or token+secret grants a user similar power as a login+password then it should be encrypted with one-way encryption **just like a password**.
167
+
168
+ ### How do I get the secret?
169
+
170
+ The secret is the password field on the model. It's only available when the instance is first created after that you can't retrieve it - - that's the whole point of one-way encryption.
171
+
172
+ ## Development
173
+
174
+ 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.
175
+
176
+ 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).
177
+
178
+ ## Contributing
179
+
180
+ Bug reports and pull requests are welcome on GitHub at https://github.com/tgaff/token_secret_auth. 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.
181
+
182
+ ## License
183
+
184
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
185
+
186
+ ## Code of Conduct
187
+
188
+ Everyone interacting in the TokenSecretAuth project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/token_secret_auth/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
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "token_secret_auth"
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
@@ -0,0 +1,3 @@
1
+ require 'token_secret_auth/version'
2
+ require 'token_secret_auth/base'
3
+
@@ -0,0 +1,105 @@
1
+ module TokenSecretAuth
2
+ class << self
3
+ require 'hashids'
4
+ # salt for the id ONLY,
5
+ # optional config - even if user doesn't change this
6
+ # the only possible leak is the id
7
+ DEFAULT_SALT = 'NaCl NaHCO3 NH4ClO3 NaBr MgCl2'
8
+
9
+ # TokenSecretAuth.hash_id
10
+ # returns the stored instance of Hashids
11
+ # used for generating any Token
12
+ def hash_id
13
+ @hid
14
+ end
15
+
16
+ # recommended configuration:
17
+ # TokenSecretAuth.configure do |config|
18
+ # config.id_salt = 'some appropriate saltiness'
19
+ # end
20
+ def configure
21
+ yield self
22
+ @id_salt = DEFAULT_SALT if @id_salt.nil?
23
+ set_hash_id_instance(@id_salt)
24
+ end
25
+
26
+ # set salt for hashing IDs
27
+ def id_salt=(salt)
28
+ @id_salt = salt
29
+ end
30
+ protected
31
+ # TokenSecretAuth.set_hash_id_instance
32
+ # call only once
33
+ def set_hash_id_instance(salt)
34
+ @hid = Hashids.new(salt, 12)
35
+ end
36
+ end
37
+
38
+
39
+ module ClassMethods
40
+ def decode_token(token)
41
+ decoded = TokenSecretAuth.hash_id.decode(token).first
42
+ end
43
+
44
+ # .find_with_token
45
+ # Use on model files to find a particular instance based on the token (hashed ID)
46
+ def find_with_token(token)
47
+ begin
48
+ find(decode_token(token))
49
+ rescue Hashids::InputError
50
+ # controller should handle not found when we can't decode bad token
51
+ return find(nil)
52
+ end
53
+ end
54
+
55
+ # .authenticate_by_credentials
56
+ # finds correct instance by its token and then authenticates the password for that instance
57
+ def authenticate_by_credentials(token, secret=nil)
58
+ account = find_with_token(token)
59
+ # note BCrypt's authenticate will return false or the object when matched
60
+ if account
61
+ account.authenticate(secret)
62
+ end
63
+ end
64
+
65
+ # create a new randomly generated secret
66
+ def generate_secret
67
+ rand(36**secret_length).to_s(36)
68
+ end
69
+
70
+ # the default length for a secret
71
+ def secret_length
72
+ @secret_length ||= 32
73
+ end
74
+
75
+ private
76
+ end
77
+
78
+ def self.included(base)
79
+ base.extend(ClassMethods)
80
+ end
81
+
82
+ # Returns the object's ID attribute encoded as a token
83
+ def token
84
+ return nil if !id
85
+ encode(id)
86
+ end
87
+
88
+ # the model can call this method to generate a new password for the user
89
+ # it should then encrypt this password for storage in db
90
+ def generate_secret
91
+ self.password = self.class.generate_secret
92
+ end
93
+
94
+
95
+ private
96
+ def secret_length
97
+ @secret_length ||= 32
98
+ end
99
+
100
+ def encode(value)
101
+ TokenSecretAuth.hash_id.encode(value)
102
+ end
103
+
104
+ self.configure {} # Necessary to perform default setup
105
+ end
@@ -0,0 +1,3 @@
1
+ module TokenSecretAuth
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,29 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "token_secret_auth/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "token_secret_auth"
8
+ spec.version = TokenSecretAuth::VERSION
9
+ spec.authors = ["tgaff"]
10
+ spec.email = ["tgaff@alumni.nd.edu"]
11
+
12
+ spec.summary = %q{Simple token+secret authentication gem.}
13
+ spec.description = %q{Simple token + secret authentication gem with encrypted secrets.}
14
+ spec.homepage = "https://github.com/tgaff/token_secret_auth"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ # spec.bindir = "exe"
21
+ # spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_runtime_dependency "hashids", "~>1.0"
25
+ spec.add_development_dependency "bundler", "~> 1"
26
+ spec.add_development_dependency "rake", "~> 10.0"
27
+ spec.add_development_dependency "rspec", "~> 3.0"
28
+ spec.add_development_dependency "pry", "~> 0.11"
29
+ end
metadata ADDED
@@ -0,0 +1,128 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: token_secret_auth
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - tgaff
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-01-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: hashids
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.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: pry
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '0.11'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '0.11'
83
+ description: Simple token + secret authentication gem with encrypted secrets.
84
+ email:
85
+ - tgaff@alumni.nd.edu
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - ".rspec"
92
+ - ".travis.yml"
93
+ - CODE_OF_CONDUCT.md
94
+ - Gemfile
95
+ - LICENSE.txt
96
+ - README.md
97
+ - Rakefile
98
+ - bin/console
99
+ - bin/setup
100
+ - lib/token_secret_auth.rb
101
+ - lib/token_secret_auth/base.rb
102
+ - lib/token_secret_auth/version.rb
103
+ - token_secret_auth.gemspec
104
+ homepage: https://github.com/tgaff/token_secret_auth
105
+ licenses:
106
+ - MIT
107
+ metadata: {}
108
+ post_install_message:
109
+ rdoc_options: []
110
+ require_paths:
111
+ - lib
112
+ required_ruby_version: !ruby/object:Gem::Requirement
113
+ requirements:
114
+ - - ">="
115
+ - !ruby/object:Gem::Version
116
+ version: '0'
117
+ required_rubygems_version: !ruby/object:Gem::Requirement
118
+ requirements:
119
+ - - ">="
120
+ - !ruby/object:Gem::Version
121
+ version: '0'
122
+ requirements: []
123
+ rubyforge_project:
124
+ rubygems_version: 2.5.1
125
+ signing_key:
126
+ specification_version: 4
127
+ summary: Simple token+secret authentication gem.
128
+ test_files: []