tokenable-ruby 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.github/workflows/publish.yml +40 -0
- data/.github/workflows/rubocop.yml +16 -0
- data/.github/workflows/test.yml +21 -0
- data/.gitignore +9 -0
- data/.rspec +1 -0
- data/.rubocop.yml +22 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/Gemfile +10 -0
- data/LICENSE.txt +21 -0
- data/README.md +133 -0
- data/Rakefile +16 -0
- data/bin/console +15 -0
- data/bin/setup +8 -0
- data/config/routes.rb +5 -0
- data/lib/tokenable.rb +13 -0
- data/lib/tokenable/authable.rb +90 -0
- data/lib/tokenable/config.rb +32 -0
- data/lib/tokenable/controllers/tokens_controller.rb +21 -0
- data/lib/tokenable/engine.rb +11 -0
- data/lib/tokenable/railtie.rb +10 -0
- data/lib/tokenable/strategies/devise.rb +31 -0
- data/lib/tokenable/strategies/secure_password.rb +31 -0
- data/lib/tokenable/verifier.rb +32 -0
- data/lib/tokenable/version.rb +5 -0
- data/tokenable-ruby.gemspec +32 -0
- metadata +113 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 40e8d5ec3402eabc0468d0ddc40eccc571b7745719b5101da223d01c504e43ee
|
4
|
+
data.tar.gz: 950d44d72882ffd8a376837ce1150bb81a5c149ce31f45cc2ba90efa3b0d325d
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: a55f04fce6b1aabbc31fc0306793d7680636b1ed29e5397c33e1124e650ccff36e8eb28baaa72c6b3d1cd55785a030aaeed861ac986c4cfbfbe9aec63191650f
|
7
|
+
data.tar.gz: c0b41d1071a8212a09d50fddbd5e75b677e0d96864cf940b79057df16ce31767debf00e4168bab415134c81a428c8e2f029436a18f079817c99a7b975715de5d
|
@@ -0,0 +1,40 @@
|
|
1
|
+
name: Publish Gem
|
2
|
+
|
3
|
+
on:
|
4
|
+
release:
|
5
|
+
types: [published]
|
6
|
+
|
7
|
+
jobs:
|
8
|
+
build:
|
9
|
+
name: Build + Publish
|
10
|
+
runs-on: ubuntu-latest
|
11
|
+
|
12
|
+
steps:
|
13
|
+
- uses: actions/checkout@v2
|
14
|
+
- name: Set up Ruby 2.7
|
15
|
+
uses: actions/setup-ruby@v1
|
16
|
+
with:
|
17
|
+
ruby-version: 2.7
|
18
|
+
|
19
|
+
- name: Publish to GPR
|
20
|
+
run: |
|
21
|
+
mkdir -p $HOME/.gem
|
22
|
+
touch $HOME/.gem/credentials
|
23
|
+
chmod 0600 $HOME/.gem/credentials
|
24
|
+
printf -- "---\n:github: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials
|
25
|
+
gem build *.gemspec
|
26
|
+
gem push --KEY github --host https://rubygems.pkg.github.com/${OWNER} *.gem
|
27
|
+
env:
|
28
|
+
GEM_HOST_API_KEY: "Bearer ${{secrets.GITHUB_TOKEN}}"
|
29
|
+
OWNER: ${{ github.repository_owner }}
|
30
|
+
|
31
|
+
- name: Publish to RubyGems
|
32
|
+
run: |
|
33
|
+
mkdir -p $HOME/.gem
|
34
|
+
touch $HOME/.gem/credentials
|
35
|
+
chmod 0600 $HOME/.gem/credentials
|
36
|
+
printf -- "---\n:rubygems_api_key: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials
|
37
|
+
gem build *.gemspec
|
38
|
+
gem push *.gem
|
39
|
+
env:
|
40
|
+
GEM_HOST_API_KEY: "${{secrets.RUBYGEMS_AUTH_TOKEN}}"
|
@@ -0,0 +1,16 @@
|
|
1
|
+
name: Rubocop
|
2
|
+
|
3
|
+
on: push
|
4
|
+
|
5
|
+
jobs:
|
6
|
+
rubocop:
|
7
|
+
runs-on: ubuntu-latest
|
8
|
+
steps:
|
9
|
+
- uses: actions/checkout@v2
|
10
|
+
- name: Set up Ruby
|
11
|
+
uses: ruby/setup-ruby@v1
|
12
|
+
with:
|
13
|
+
ruby-version: 2.7
|
14
|
+
- run: gem install bundler -v 2.2.4
|
15
|
+
- run: bundle install
|
16
|
+
- run: bundle exec rubocop
|
@@ -0,0 +1,21 @@
|
|
1
|
+
name: Test
|
2
|
+
|
3
|
+
on: push
|
4
|
+
|
5
|
+
jobs:
|
6
|
+
test:
|
7
|
+
strategy:
|
8
|
+
fail-fast: false
|
9
|
+
matrix:
|
10
|
+
os: [ubuntu-latest, macos-latest, windows-latest]
|
11
|
+
ruby: [2.5, 2.6, 2.7, 3.0]
|
12
|
+
runs-on: ${{ matrix.os }}
|
13
|
+
steps:
|
14
|
+
- uses: actions/checkout@v2
|
15
|
+
- name: Set up Ruby
|
16
|
+
uses: ruby/setup-ruby@v1
|
17
|
+
with:
|
18
|
+
ruby-version: ${{ matrix.ruby }}
|
19
|
+
- run: gem install bundler -v 2.2.4
|
20
|
+
- run: bundle install
|
21
|
+
- run: bundle exec rspec
|
data/.gitignore
ADDED
data/.rspec
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
--require spec_helper
|
data/.rubocop.yml
ADDED
@@ -0,0 +1,22 @@
|
|
1
|
+
AllCops:
|
2
|
+
TargetRubyVersion: 2.5
|
3
|
+
|
4
|
+
Style/Documentation:
|
5
|
+
Enabled: false
|
6
|
+
|
7
|
+
Style/StringLiterals:
|
8
|
+
Enabled: true
|
9
|
+
EnforcedStyle: single_quotes
|
10
|
+
|
11
|
+
Style/StringLiteralsInInterpolation:
|
12
|
+
Enabled: true
|
13
|
+
EnforcedStyle: double_quotes
|
14
|
+
|
15
|
+
Style/TrailingCommaInArrayLiteral:
|
16
|
+
EnforcedStyleForMultiline: consistent_comma
|
17
|
+
|
18
|
+
Style/TrailingCommaInHashLiteral:
|
19
|
+
EnforcedStyleForMultiline: consistent_comma
|
20
|
+
|
21
|
+
Layout/LineLength:
|
22
|
+
Max: 150
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -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 marc@marcqualie.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
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2021 Marc Qualie
|
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,133 @@
|
|
1
|
+
# Tokenable
|
2
|
+
|
3
|
+
![Test](https://github.com/tokenable/tokenable-ruby/workflows/Test/badge.svg)
|
4
|
+
|
5
|
+
Tokenable is a gem for Rails to enable the ability for API applications to provide Authentication.
|
6
|
+
|
7
|
+
This allows you to provide authentication to mobile apps, or SPAs with ease.
|
8
|
+
|
9
|
+
## Installation
|
10
|
+
|
11
|
+
Add this line to your application's Gemfile:
|
12
|
+
|
13
|
+
```ruby
|
14
|
+
gem 'tokenable'
|
15
|
+
```
|
16
|
+
|
17
|
+
And then execute:
|
18
|
+
|
19
|
+
```
|
20
|
+
bundle install
|
21
|
+
```
|
22
|
+
|
23
|
+
## Usage
|
24
|
+
|
25
|
+
In your `config/routes.rb`, please add:
|
26
|
+
|
27
|
+
```ruby
|
28
|
+
mount Tokenable::Engine => '/api/auth'
|
29
|
+
```
|
30
|
+
|
31
|
+
And in your `User` model, please add an Auth Strategy. For example, if you are using `has_secure_password`, then you could use:
|
32
|
+
|
33
|
+
```ruby
|
34
|
+
class User < ApplicationRecord
|
35
|
+
include Tokenable::Strategies::SecurePassword
|
36
|
+
|
37
|
+
has_secure_password
|
38
|
+
end
|
39
|
+
```
|
40
|
+
|
41
|
+
You can chose from:
|
42
|
+
|
43
|
+
- `Tokenable::Strategies::SecurePassword`
|
44
|
+
- `Tokenable::Strategies::Devise`
|
45
|
+
|
46
|
+
You can also create your own stragery. This is as simple as creating a method on the User object.
|
47
|
+
|
48
|
+
```ruby
|
49
|
+
def self.from_tokenable_params(params)
|
50
|
+
user = User.find_by(something: params[:something])
|
51
|
+
return nil unless user.present?
|
52
|
+
|
53
|
+
return nil unless user.password_valid?(params[:password])
|
54
|
+
user
|
55
|
+
end
|
56
|
+
```
|
57
|
+
|
58
|
+
### Invalidate Tokens
|
59
|
+
|
60
|
+
If you want to be able to invalidate tokens from the server, then you can add `Tokenable::Verifier`.
|
61
|
+
|
62
|
+
```ruby
|
63
|
+
class User < ApplicationRecord
|
64
|
+
include Tokenable::Verifier
|
65
|
+
end
|
66
|
+
```
|
67
|
+
|
68
|
+
And running the following migration:
|
69
|
+
|
70
|
+
```bash
|
71
|
+
rails g migration AddTokenableVerifierToUsers tokenable_verifier:string
|
72
|
+
```
|
73
|
+
|
74
|
+
You can now invalidate all tokens by calling `user.invalidate_tokens!`.
|
75
|
+
|
76
|
+
### Token Expiry
|
77
|
+
|
78
|
+
By default, tokens will live forever. If you want to change this, you can set a config option (see below for how to set that up).
|
79
|
+
|
80
|
+
```ruby
|
81
|
+
Tokenable::Config.lifespan = 7.days
|
82
|
+
```
|
83
|
+
|
84
|
+
### Configuration Options
|
85
|
+
|
86
|
+
Tokenable works out of the box, with no config required, however you can tweak the settings, by creating `config/initializers/tokenable.rb` file.
|
87
|
+
|
88
|
+
```ruby
|
89
|
+
# The secret used to create these tokens. This is then used to verify the
|
90
|
+
# token is valid. Note: Tokens are not encrypted, and container the user_id.
|
91
|
+
# Default: Rails.application.secret_key_base
|
92
|
+
Tokenable::Config.secret = 'a-256-bit-string'
|
93
|
+
```
|
94
|
+
|
95
|
+
### Example Usage
|
96
|
+
|
97
|
+
Once you have this setup, you can login. For example, you could login using `axios` in JavaScript:
|
98
|
+
|
99
|
+
```js
|
100
|
+
const { data } = await axios.post("https://example.com/api/auth", {
|
101
|
+
email: "email@example.com",
|
102
|
+
password: "coolpassword123",
|
103
|
+
});
|
104
|
+
|
105
|
+
const token = data.data.token;
|
106
|
+
const user_id = data.data.user_id;
|
107
|
+
```
|
108
|
+
|
109
|
+
You then use this token in all future API requests:
|
110
|
+
|
111
|
+
```js
|
112
|
+
const { data } = await axios.get(`https://example.com/api/user/${user_id}`, {
|
113
|
+
headers: { Authorization: `Bearer ${token}` },
|
114
|
+
});
|
115
|
+
```
|
116
|
+
|
117
|
+
## Development
|
118
|
+
|
119
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
120
|
+
|
121
|
+
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).
|
122
|
+
|
123
|
+
## Contributing
|
124
|
+
|
125
|
+
Bug reports and pull requests are welcome on GitHub at <https://github.com/tokenable/tokenable-ruby>. 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/tokenable/tokenable-ruby/blob/main/CODE_OF_CONDUCT.md).
|
126
|
+
|
127
|
+
## License
|
128
|
+
|
129
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
130
|
+
|
131
|
+
## Code of Conduct
|
132
|
+
|
133
|
+
Everyone interacting in the Tokenable project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/tokenable/tokenable-ruby/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,16 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'bundler/gem_tasks'
|
4
|
+
require 'rake/testtask'
|
5
|
+
|
6
|
+
Rake::TestTask.new(:test) do |t|
|
7
|
+
t.libs << 'test'
|
8
|
+
t.libs << 'lib'
|
9
|
+
t.test_files = FileList['test/**/*_test.rb']
|
10
|
+
end
|
11
|
+
|
12
|
+
require 'rubocop/rake_task'
|
13
|
+
|
14
|
+
RuboCop::RakeTask.new
|
15
|
+
|
16
|
+
task default: %i[test rubocop]
|
data/bin/console
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
require 'bundler/setup'
|
5
|
+
require 'tokenable'
|
6
|
+
|
7
|
+
# You can add fixtures and/or initialization code here to make experimenting
|
8
|
+
# with your gem easier. You can also use a different console, if you like.
|
9
|
+
|
10
|
+
# (If you use this, don't forget to add pry to your Gemfile!)
|
11
|
+
# require "pry"
|
12
|
+
# Pry.start
|
13
|
+
|
14
|
+
require 'irb'
|
15
|
+
IRB.start(__FILE__)
|
data/bin/setup
ADDED
data/config/routes.rb
ADDED
data/lib/tokenable.rb
ADDED
@@ -0,0 +1,13 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative 'tokenable/version'
|
4
|
+
require_relative 'tokenable/authable'
|
5
|
+
require_relative 'tokenable/verifier'
|
6
|
+
require_relative 'tokenable/config'
|
7
|
+
require_relative 'tokenable/railtie' if defined?(Rails)
|
8
|
+
|
9
|
+
module Tokenable
|
10
|
+
class Error < StandardError; end
|
11
|
+
|
12
|
+
class Unauthorized < Error; end
|
13
|
+
end
|
@@ -0,0 +1,90 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# The main controller concern that will be injected to the application
|
4
|
+
|
5
|
+
require 'jwt'
|
6
|
+
require 'active_support/concern'
|
7
|
+
|
8
|
+
module Tokenable
|
9
|
+
module Authable
|
10
|
+
extend ActiveSupport::Concern
|
11
|
+
|
12
|
+
def user_signed_in?
|
13
|
+
current_user.present?
|
14
|
+
end
|
15
|
+
|
16
|
+
def current_user
|
17
|
+
@current_user ||= user_class.find(jwt_user_id)
|
18
|
+
rescue Tokenable::Unauthorized
|
19
|
+
nil
|
20
|
+
end
|
21
|
+
|
22
|
+
def require_tokenable_user!
|
23
|
+
raise Tokenable::Unauthorized, 'User not found in JWT token' unless jwt_user_id
|
24
|
+
raise Tokenable::Unauthorized, 'User is not signed in' unless user_signed_in?
|
25
|
+
raise Tokenable::Unauthorized, 'Token verifier is invalid' unless valid_token?
|
26
|
+
end
|
27
|
+
|
28
|
+
private
|
29
|
+
|
30
|
+
def verifier_enabled?
|
31
|
+
user_class.included_modules.include?(Tokenable::Verifier)
|
32
|
+
end
|
33
|
+
|
34
|
+
def valid_token?
|
35
|
+
return true unless verifier_enabled?
|
36
|
+
|
37
|
+
current_user.valid_verifier?(jwt_verifier)
|
38
|
+
end
|
39
|
+
|
40
|
+
def user_class
|
41
|
+
Tokenable::Config.user_class
|
42
|
+
end
|
43
|
+
|
44
|
+
def token_from_header
|
45
|
+
request.authorization.to_s.split(' ').last
|
46
|
+
end
|
47
|
+
|
48
|
+
def token_from_user(user)
|
49
|
+
jwt_data = {
|
50
|
+
data: {
|
51
|
+
user_id: user.id,
|
52
|
+
},
|
53
|
+
}
|
54
|
+
|
55
|
+
jwt_data[:exp] = jwt_expiry_time if jwt_expiry_time
|
56
|
+
|
57
|
+
jwt_data[:data][:verifier] = user.current_verifier if verifier_enabled?
|
58
|
+
|
59
|
+
JWT.encode(jwt_data, jwt_secret, 'HS256')
|
60
|
+
end
|
61
|
+
|
62
|
+
def jwt_user_id
|
63
|
+
jwt.dig('data', 'user_id')
|
64
|
+
end
|
65
|
+
|
66
|
+
def jwt_verifier
|
67
|
+
jwt.dig('data', 'verifier')
|
68
|
+
end
|
69
|
+
|
70
|
+
def jwt
|
71
|
+
raise Tokenable::Unauthorized, 'Bearer token not provided' unless token_from_header.present?
|
72
|
+
|
73
|
+
@jwt ||= JWT.decode(token_from_header, jwt_secret, true, { algorithm: 'HS256' }).first.to_h
|
74
|
+
rescue JWT::ExpiredSignature
|
75
|
+
raise Tokenable::Unauthorized, 'Token has expired'
|
76
|
+
rescue JWT::VerificationError
|
77
|
+
raise Tokenable::Unauthorized, 'The tokenable secret used in this token does not match the one supplied in Tokenable::Config.secret'
|
78
|
+
rescue JWT::DecodeError
|
79
|
+
raise Tokenable::Unauthorized, 'JWT exception thrown'
|
80
|
+
end
|
81
|
+
|
82
|
+
def jwt_expiry_time
|
83
|
+
Tokenable::Config.lifespan ? Tokenable::Config.lifespan.from_now.to_i : nil
|
84
|
+
end
|
85
|
+
|
86
|
+
def jwt_secret
|
87
|
+
Tokenable::Config.secret
|
88
|
+
end
|
89
|
+
end
|
90
|
+
end
|
@@ -0,0 +1,32 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Tokenable
|
4
|
+
class Config
|
5
|
+
# How long should the token last before it expires?
|
6
|
+
# E.G: Tokenable::Config.lifespan = 7.days
|
7
|
+
mattr_accessor :lifespan, default: nil
|
8
|
+
|
9
|
+
# The secret used by JWT to encode the Token.
|
10
|
+
# We default to Rails secret_key_base
|
11
|
+
# This can be any 256 bit string.
|
12
|
+
mattr_writer :secret, default: -> { Rails.application.secret_key_base }
|
13
|
+
|
14
|
+
# The user model that we will perform actions on
|
15
|
+
mattr_writer :user_class, default: -> { User }
|
16
|
+
|
17
|
+
# We do this, as some of our defaults need to live in a Proc (as this library is loaded before Rails)
|
18
|
+
# This means we can return the value when the method is called, instead of the Proc.
|
19
|
+
def self.method_missing(method_name, *args, &block)
|
20
|
+
class_variable_defined?("@@#{method_name}") ? proc_reader(method_name) : super
|
21
|
+
end
|
22
|
+
|
23
|
+
def self.respond_to_missing?(method_name, include_private = false)
|
24
|
+
class_variable_defined?("@@#{method_name}") || super
|
25
|
+
end
|
26
|
+
|
27
|
+
def self.proc_reader(key)
|
28
|
+
value = class_variable_get("@@#{key}")
|
29
|
+
value.is_a?(Proc) ? value.call : value
|
30
|
+
end
|
31
|
+
end
|
32
|
+
end
|
@@ -0,0 +1,21 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Tokenable
|
4
|
+
class TokensController < ::ActionController::API
|
5
|
+
include Authable
|
6
|
+
|
7
|
+
def create
|
8
|
+
user = User.from_tokenable_params(params)
|
9
|
+
raise Tokenable::Unauthorized unless user
|
10
|
+
|
11
|
+
response = {
|
12
|
+
data: {
|
13
|
+
token: token_from_user(user),
|
14
|
+
user_id: user.id,
|
15
|
+
},
|
16
|
+
}
|
17
|
+
|
18
|
+
render json: response, status: 201
|
19
|
+
end
|
20
|
+
end
|
21
|
+
end
|
@@ -0,0 +1,11 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative 'controllers/tokens_controller'
|
4
|
+
require_relative 'strategies/devise'
|
5
|
+
require_relative 'strategies/secure_password'
|
6
|
+
|
7
|
+
module Tokenable
|
8
|
+
class Engine < ::Rails::Engine
|
9
|
+
isolate_namespace Tokenable
|
10
|
+
end
|
11
|
+
end
|
@@ -0,0 +1,31 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Tokenable
|
4
|
+
module Strategies
|
5
|
+
module Devise
|
6
|
+
extend ActiveSupport::Concern
|
7
|
+
|
8
|
+
class_methods do
|
9
|
+
def from_tokenable_params(params)
|
10
|
+
email, password = parse_auth_params(params)
|
11
|
+
|
12
|
+
user = User.find_by(email: email)
|
13
|
+
return nil unless user
|
14
|
+
|
15
|
+
return nil unless user.valid_password?(password)
|
16
|
+
|
17
|
+
user
|
18
|
+
end
|
19
|
+
|
20
|
+
private
|
21
|
+
|
22
|
+
def parse_auth_params(params)
|
23
|
+
[
|
24
|
+
params.require(:email),
|
25
|
+
params.require(:password),
|
26
|
+
]
|
27
|
+
end
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
31
|
+
end
|
@@ -0,0 +1,31 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Tokenable
|
4
|
+
module Strategies
|
5
|
+
module SecurePassword
|
6
|
+
extend ActiveSupport::Concern
|
7
|
+
|
8
|
+
class_methods do
|
9
|
+
def from_tokenable_params(params)
|
10
|
+
email, password = parse_auth_params(params)
|
11
|
+
|
12
|
+
user = User.find_by(email: email)
|
13
|
+
return nil unless user
|
14
|
+
|
15
|
+
return nil unless user.authenticate(password)
|
16
|
+
|
17
|
+
user
|
18
|
+
end
|
19
|
+
|
20
|
+
private
|
21
|
+
|
22
|
+
def parse_auth_params(params)
|
23
|
+
[
|
24
|
+
params.require(:email),
|
25
|
+
params.require(:password),
|
26
|
+
]
|
27
|
+
end
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
31
|
+
end
|
@@ -0,0 +1,32 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Tokenable
|
4
|
+
module Verifier
|
5
|
+
extend ActiveSupport::Concern
|
6
|
+
|
7
|
+
def valid_verifier?(verifier)
|
8
|
+
raise Tokenable::Unauthorized, "#{verifier_key} field is missing" unless has_attribute?(verifier_key)
|
9
|
+
|
10
|
+
current_verifier == verifier
|
11
|
+
end
|
12
|
+
|
13
|
+
def current_verifier
|
14
|
+
read_attribute(verifier_key) || issue_verifier!
|
15
|
+
end
|
16
|
+
|
17
|
+
def invalidate_tokens!
|
18
|
+
issue_verifier!
|
19
|
+
end
|
20
|
+
|
21
|
+
def issue_verifier!
|
22
|
+
update!(verifier_key => SecureRandom.uuid)
|
23
|
+
read_attribute(verifier_key)
|
24
|
+
end
|
25
|
+
|
26
|
+
private
|
27
|
+
|
28
|
+
def verifier_key
|
29
|
+
:tokenable_verifier
|
30
|
+
end
|
31
|
+
end
|
32
|
+
end
|
@@ -0,0 +1,32 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative 'lib/tokenable/version'
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = 'tokenable-ruby'
|
7
|
+
spec.version = Tokenable::VERSION
|
8
|
+
spec.authors = ['Marc Qualie', 'Scott Robertson']
|
9
|
+
spec.email = ['marc@marcqualie.com', 'scott@scottrobertson.me']
|
10
|
+
|
11
|
+
spec.summary = "JWT authentication for Rails API's"
|
12
|
+
spec.homepage = 'https://github.com/tokenable/tokenable-ruby'
|
13
|
+
spec.license = 'MIT'
|
14
|
+
spec.required_ruby_version = Gem::Requirement.new('>= 2.5')
|
15
|
+
|
16
|
+
spec.metadata['homepage_uri'] = spec.homepage
|
17
|
+
spec.metadata['source_code_uri'] = 'https://github.com/tokenable/tokenable-ruby'
|
18
|
+
spec.metadata['changelog_uri'] = 'https://github.com/tokenable/tokenable-ruby/releases'
|
19
|
+
|
20
|
+
# Specify which files should be added to the gem when it is released.
|
21
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
22
|
+
spec.files = Dir.chdir(File.expand_path(__dir__)) do
|
23
|
+
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
|
24
|
+
end
|
25
|
+
|
26
|
+
spec.bindir = 'exe'
|
27
|
+
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
28
|
+
spec.require_paths = ['lib']
|
29
|
+
|
30
|
+
spec.add_dependency 'jwt', '~> 2.2', '< 3'
|
31
|
+
spec.add_dependency 'rails', '~> 6.0', '< 6.2'
|
32
|
+
end
|
metadata
ADDED
@@ -0,0 +1,113 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: tokenable-ruby
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Marc Qualie
|
8
|
+
- Scott Robertson
|
9
|
+
autorequire:
|
10
|
+
bindir: exe
|
11
|
+
cert_chain: []
|
12
|
+
date: 2021-01-17 00:00:00.000000000 Z
|
13
|
+
dependencies:
|
14
|
+
- !ruby/object:Gem::Dependency
|
15
|
+
name: jwt
|
16
|
+
requirement: !ruby/object:Gem::Requirement
|
17
|
+
requirements:
|
18
|
+
- - "~>"
|
19
|
+
- !ruby/object:Gem::Version
|
20
|
+
version: '2.2'
|
21
|
+
- - "<"
|
22
|
+
- !ruby/object:Gem::Version
|
23
|
+
version: '3'
|
24
|
+
type: :runtime
|
25
|
+
prerelease: false
|
26
|
+
version_requirements: !ruby/object:Gem::Requirement
|
27
|
+
requirements:
|
28
|
+
- - "~>"
|
29
|
+
- !ruby/object:Gem::Version
|
30
|
+
version: '2.2'
|
31
|
+
- - "<"
|
32
|
+
- !ruby/object:Gem::Version
|
33
|
+
version: '3'
|
34
|
+
- !ruby/object:Gem::Dependency
|
35
|
+
name: rails
|
36
|
+
requirement: !ruby/object:Gem::Requirement
|
37
|
+
requirements:
|
38
|
+
- - "~>"
|
39
|
+
- !ruby/object:Gem::Version
|
40
|
+
version: '6.0'
|
41
|
+
- - "<"
|
42
|
+
- !ruby/object:Gem::Version
|
43
|
+
version: '6.2'
|
44
|
+
type: :runtime
|
45
|
+
prerelease: false
|
46
|
+
version_requirements: !ruby/object:Gem::Requirement
|
47
|
+
requirements:
|
48
|
+
- - "~>"
|
49
|
+
- !ruby/object:Gem::Version
|
50
|
+
version: '6.0'
|
51
|
+
- - "<"
|
52
|
+
- !ruby/object:Gem::Version
|
53
|
+
version: '6.2'
|
54
|
+
description:
|
55
|
+
email:
|
56
|
+
- marc@marcqualie.com
|
57
|
+
- scott@scottrobertson.me
|
58
|
+
executables: []
|
59
|
+
extensions: []
|
60
|
+
extra_rdoc_files: []
|
61
|
+
files:
|
62
|
+
- ".github/workflows/publish.yml"
|
63
|
+
- ".github/workflows/rubocop.yml"
|
64
|
+
- ".github/workflows/test.yml"
|
65
|
+
- ".gitignore"
|
66
|
+
- ".rspec"
|
67
|
+
- ".rubocop.yml"
|
68
|
+
- CODE_OF_CONDUCT.md
|
69
|
+
- Gemfile
|
70
|
+
- LICENSE.txt
|
71
|
+
- README.md
|
72
|
+
- Rakefile
|
73
|
+
- bin/console
|
74
|
+
- bin/setup
|
75
|
+
- config/routes.rb
|
76
|
+
- lib/tokenable.rb
|
77
|
+
- lib/tokenable/authable.rb
|
78
|
+
- lib/tokenable/config.rb
|
79
|
+
- lib/tokenable/controllers/tokens_controller.rb
|
80
|
+
- lib/tokenable/engine.rb
|
81
|
+
- lib/tokenable/railtie.rb
|
82
|
+
- lib/tokenable/strategies/devise.rb
|
83
|
+
- lib/tokenable/strategies/secure_password.rb
|
84
|
+
- lib/tokenable/verifier.rb
|
85
|
+
- lib/tokenable/version.rb
|
86
|
+
- tokenable-ruby.gemspec
|
87
|
+
homepage: https://github.com/tokenable/tokenable-ruby
|
88
|
+
licenses:
|
89
|
+
- MIT
|
90
|
+
metadata:
|
91
|
+
homepage_uri: https://github.com/tokenable/tokenable-ruby
|
92
|
+
source_code_uri: https://github.com/tokenable/tokenable-ruby
|
93
|
+
changelog_uri: https://github.com/tokenable/tokenable-ruby/releases
|
94
|
+
post_install_message:
|
95
|
+
rdoc_options: []
|
96
|
+
require_paths:
|
97
|
+
- lib
|
98
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
99
|
+
requirements:
|
100
|
+
- - ">="
|
101
|
+
- !ruby/object:Gem::Version
|
102
|
+
version: '2.5'
|
103
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
104
|
+
requirements:
|
105
|
+
- - ">="
|
106
|
+
- !ruby/object:Gem::Version
|
107
|
+
version: '0'
|
108
|
+
requirements: []
|
109
|
+
rubygems_version: 3.1.4
|
110
|
+
signing_key:
|
111
|
+
specification_version: 4
|
112
|
+
summary: JWT authentication for Rails API's
|
113
|
+
test_files: []
|