jwt_api 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/.gitignore +11 -0
- data/.rspec +3 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/Gemfile +10 -0
- data/Gemfile.lock +37 -0
- data/LICENSE.txt +21 -0
- data/README.md +90 -0
- data/Rakefile +8 -0
- data/bin/console +15 -0
- data/bin/setup +8 -0
- data/jwt_api.gemspec +35 -0
- data/lib/generators/jwt_api/setup_generator.rb +61 -0
- data/lib/generators/jwt_api/templates/api/base_controller.rb +46 -0
- data/lib/generators/jwt_api/templates/api/v1/authentication_controller.rb +39 -0
- data/lib/generators/jwt_api/templates/api/v1/passwords_controller.rb +90 -0
- data/lib/generators/jwt_api/templates/api/v1/users_controller.rb +41 -0
- data/lib/generators/jwt_api/templates/initializers/json_web_token.rb +11 -0
- data/lib/generators/jwt_api/templates/mailers/jwt_mailer.rb +10 -0
- data/lib/generators/jwt_api/templates/views/jwt_mailer/reset_password.html.erb +8 -0
- data/lib/generators/jwt_api/templates/views/users/_user.html.erb +3 -0
- data/lib/generators/jwt_api/templates/views/users/_user.json.jbuilder +4 -0
- data/lib/jwt_api/version.rb +5 -0
- data/lib/jwt_api.rb +33 -0
- metadata +90 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 19e4d4dcf76be937121c8a2559e64417c07c1218b352492985120076db85d4bd
|
4
|
+
data.tar.gz: ba9ac0f21978e74a0ada2837d6966b0d017b74043ab001948bb6c137184f9089
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: ba08a36a4111d4ecb70466481fbc67f55b62a831f56c866ce10e754af84e9091c570e5ce594043da49b3ec13cf389332e78beafcc5c30de02d6558a90a75b0a5
|
7
|
+
data.tar.gz: d57636254090a1e52d2e9e4408a1925fe7b4accb265b32b4a6933cbddd3439bb255ced6e6c84d35f3f99bac36ca26fa97c8c1a4117a00c9f6f516add5f38185d
|
data/.gitignore
ADDED
data/.rspec
ADDED
data/CHANGELOG.md
ADDED
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 lpolicastro@pm.me. 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/Gemfile.lock
ADDED
@@ -0,0 +1,37 @@
|
|
1
|
+
PATH
|
2
|
+
remote: .
|
3
|
+
specs:
|
4
|
+
jwt_api (0.1.0)
|
5
|
+
jwt (~> 2.2, >= 2.2.3)
|
6
|
+
|
7
|
+
GEM
|
8
|
+
remote: https://rubygems.org/
|
9
|
+
specs:
|
10
|
+
diff-lcs (1.4.4)
|
11
|
+
jwt (2.2.3)
|
12
|
+
rake (13.0.6)
|
13
|
+
rspec (3.10.0)
|
14
|
+
rspec-core (~> 3.10.0)
|
15
|
+
rspec-expectations (~> 3.10.0)
|
16
|
+
rspec-mocks (~> 3.10.0)
|
17
|
+
rspec-core (3.10.1)
|
18
|
+
rspec-support (~> 3.10.0)
|
19
|
+
rspec-expectations (3.10.1)
|
20
|
+
diff-lcs (>= 1.2.0, < 2.0)
|
21
|
+
rspec-support (~> 3.10.0)
|
22
|
+
rspec-mocks (3.10.2)
|
23
|
+
diff-lcs (>= 1.2.0, < 2.0)
|
24
|
+
rspec-support (~> 3.10.0)
|
25
|
+
rspec-support (3.10.2)
|
26
|
+
|
27
|
+
PLATFORMS
|
28
|
+
x86_64-darwin-20
|
29
|
+
|
30
|
+
DEPENDENCIES
|
31
|
+
jwt (~> 2.2, >= 2.2.3)
|
32
|
+
jwt_api!
|
33
|
+
rake (~> 13.0)
|
34
|
+
rspec (~> 3.0)
|
35
|
+
|
36
|
+
BUNDLED WITH
|
37
|
+
2.2.25
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2021 Leo Policastro
|
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,90 @@
|
|
1
|
+
# JwtApi
|
2
|
+
|
3
|
+
Generate user, session, and password api routes with JWT authentication.
|
4
|
+
|
5
|
+
## Installation
|
6
|
+
|
7
|
+
Add this line to your application's Gemfile:
|
8
|
+
|
9
|
+
```ruby
|
10
|
+
gem 'jwt_api'
|
11
|
+
```
|
12
|
+
|
13
|
+
And then execute:
|
14
|
+
|
15
|
+
$ bundle install
|
16
|
+
|
17
|
+
Or install it yourself as:
|
18
|
+
|
19
|
+
$ gem install jwt_api
|
20
|
+
|
21
|
+
Generate your API:
|
22
|
+
|
23
|
+
$ rails g jwt_api:setup
|
24
|
+
|
25
|
+
```
|
26
|
+
Running via Spring preloader in process 56238
|
27
|
+
create app/controllers/api
|
28
|
+
create app/controllers/api/base_controller.rb
|
29
|
+
create app/controllers/api/v1/authentication_controller.rb
|
30
|
+
create app/controllers/api/v1/passwords_controller.rb
|
31
|
+
create app/controllers/api/v1/users_controller.rb
|
32
|
+
insert config/routes.rb
|
33
|
+
create app/views/users
|
34
|
+
create app/views/users/_user.html.erb
|
35
|
+
create app/views/users/_user.json.jbuilder
|
36
|
+
create app/mailers/jwt_mailer.rb
|
37
|
+
create app/views/jwt_mailer
|
38
|
+
create app/views/jwt_mailer/reset_password.html.erb
|
39
|
+
create config/initializers/json_web_token.rb
|
40
|
+
generate migration
|
41
|
+
rails generate migration add_jti_to_users jti:string:uniq:index
|
42
|
+
Running via Spring preloader in process 56250
|
43
|
+
invoke active_record
|
44
|
+
create db/migrate/20210827123255_add_jti_to_users.rb
|
45
|
+
rake db:migrate
|
46
|
+
== 20210827123255 AddJtiToUsers: migrating ====================================
|
47
|
+
-- add_column(:users, :jti, :string)
|
48
|
+
-> 0.0061s
|
49
|
+
-- add_index(:users, :jti, {:unique=>true})
|
50
|
+
-> 0.0196s
|
51
|
+
== 20210827123255 AddJtiToUsers: migrated (0.0259s) ===========================
|
52
|
+
```
|
53
|
+
|
54
|
+
Feel free to remove the gem from your Gemfile, you now have everything you need in your application.
|
55
|
+
## Usage
|
56
|
+
|
57
|
+
1. Make sure that each user that needs access to the API has a JTI generated.
|
58
|
+
1. `User.first.jti = SecureRandom.uuid`
|
59
|
+
2. Request a JWT at the `/api/authenticate/` endpoint.
|
60
|
+
3. Include that token as a `Bearer` token in all other requests.
|
61
|
+
|
62
|
+
|
63
|
+
[![Run in Postman](https://run.pstmn.io/button.svg)](https://app.getpostman.com/run-collection/6130650-059cc2e3-88f7-48a8-95d0-d7dca1d7caef?action=collection%2Ffork&collection-url=entityId%3D6130650-059cc2e3-88f7-48a8-95d0-d7dca1d7caef%26entityType%3Dcollection%26workspaceId%3D128e0ba1-898b-40bb-8006-a329fb1c28de)
|
64
|
+
|
65
|
+
|
66
|
+
[Docs](https://documenter.getpostman.com/view/6130650/TzzHjXVv)
|
67
|
+
|
68
|
+
## Limitations
|
69
|
+
- Currently this will only work with a devise User model.
|
70
|
+
## Development
|
71
|
+
|
72
|
+
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.
|
73
|
+
|
74
|
+
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).
|
75
|
+
|
76
|
+
## Contributing
|
77
|
+
|
78
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/leopolicastro/jwt_api. 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]/jwt_api/blob/main/CODE_OF_CONDUCT.md).
|
79
|
+
|
80
|
+
## License
|
81
|
+
|
82
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
83
|
+
|
84
|
+
## Code of Conduct
|
85
|
+
|
86
|
+
Everyone interacting in the JwtApi project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/jwt_api/blob/main/CODE_OF_CONDUCT.md).
|
87
|
+
|
88
|
+
|
89
|
+
## TODO
|
90
|
+
- Create test suite and add to generator to copy into users app.
|
data/Rakefile
ADDED
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 "jwt_api"
|
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/jwt_api.gemspec
ADDED
@@ -0,0 +1,35 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative 'lib/jwt_api/version'
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = 'jwt_api'
|
7
|
+
spec.version = JwtApi::VERSION
|
8
|
+
spec.authors = ['Leo Policastro']
|
9
|
+
spec.email = ['lpolicastro@pm.me']
|
10
|
+
|
11
|
+
spec.summary = 'Write a short summary, because RubyGems requires one.'
|
12
|
+
spec.description = 'Write a longer description or delete this line.'
|
13
|
+
spec.homepage = 'https://github.com/leopolicastro/jwt_api/'
|
14
|
+
spec.license = 'MIT'
|
15
|
+
spec.required_ruby_version = '>= 2.4.0'
|
16
|
+
|
17
|
+
spec.metadata['homepage_uri'] = spec.homepage
|
18
|
+
spec.metadata['source_code_uri'] = spec.homepage
|
19
|
+
spec.metadata['changelog_uri'] = spec.homepage
|
20
|
+
|
21
|
+
# Specify which files should be added to the gem when it is released.
|
22
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
23
|
+
spec.files = Dir.chdir(File.expand_path(__dir__)) do
|
24
|
+
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
|
25
|
+
end
|
26
|
+
spec.bindir = 'exe'
|
27
|
+
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
28
|
+
spec.require_paths = ['lib']
|
29
|
+
|
30
|
+
# Uncomment to register a new dependency of your gem
|
31
|
+
spec.add_dependency 'jwt', '~> 2.2', '>= 2.2.3'
|
32
|
+
|
33
|
+
# For more information and examples about making a new gem, checkout our
|
34
|
+
# guide at: https://bundler.io/guides/creating_gem.html
|
35
|
+
end
|
@@ -0,0 +1,61 @@
|
|
1
|
+
require 'rails/generators/base'
|
2
|
+
|
3
|
+
module JwtApi
|
4
|
+
class SetupGenerator < Rails::Generators::Base
|
5
|
+
source_root File.expand_path('templates', __dir__)
|
6
|
+
|
7
|
+
def source_paths
|
8
|
+
[__dir__]
|
9
|
+
end
|
10
|
+
|
11
|
+
def copy_api_controllers
|
12
|
+
directory 'templates/api', 'app/controllers/api'
|
13
|
+
end
|
14
|
+
|
15
|
+
def add_api_namespace_to_routes
|
16
|
+
routes = 'config/routes.rb'
|
17
|
+
inject_into_file routes, after: 'Rails.application.routes.draw do' do
|
18
|
+
# TODO: this is ugly, there has to be a better way to do this
|
19
|
+
"\n\n# API routes
|
20
|
+
namespace :api, defaults: { format: :json } do
|
21
|
+
namespace :v1 do
|
22
|
+
# Auth
|
23
|
+
post 'auth' => 'authentication#authenticate_user'
|
24
|
+
delete 'auth' => 'authentication#logout'
|
25
|
+
# Users
|
26
|
+
resource :users
|
27
|
+
get 'me' => 'users#me'
|
28
|
+
# User Password Reset Flow
|
29
|
+
post 'passwords/reset' => 'passwords#reset_password_instructions'
|
30
|
+
get 'passwords/verify' => 'passwords#verify'
|
31
|
+
post 'passwords/update' => 'passwords#update_password'
|
32
|
+
end
|
33
|
+
end\n\n"
|
34
|
+
end
|
35
|
+
end
|
36
|
+
|
37
|
+
def copy_user_views
|
38
|
+
directory 'templates/views/users', 'app/views/users'
|
39
|
+
end
|
40
|
+
|
41
|
+
def copy_password_reset_mailer
|
42
|
+
copy_file 'templates/mailers/jwt_mailer.rb', 'app/mailers/jwt_mailer.rb'
|
43
|
+
end
|
44
|
+
|
45
|
+
def copy_password_reset_views
|
46
|
+
directory 'templates/views/jwt_mailer', 'app/views/jwt_mailer'
|
47
|
+
end
|
48
|
+
|
49
|
+
def copy_jwt_class
|
50
|
+
copy_file 'templates/initializers/json_web_token.rb', 'config/initializers/json_web_token.rb'
|
51
|
+
end
|
52
|
+
|
53
|
+
def generate_jti_migration
|
54
|
+
generate 'migration', 'add_jti_to_users', 'jti:string:uniq:index'
|
55
|
+
end
|
56
|
+
|
57
|
+
def run_migration
|
58
|
+
rake 'db:migrate'
|
59
|
+
end
|
60
|
+
end
|
61
|
+
end
|
@@ -0,0 +1,46 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# Base controller for API
|
4
|
+
class Api::BaseController < ApplicationController
|
5
|
+
skip_before_action :verify_authenticity_token
|
6
|
+
prepend_before_action :authenticate_request!
|
7
|
+
|
8
|
+
protected
|
9
|
+
|
10
|
+
def authenticate_request!
|
11
|
+
unless user_id_in_token?
|
12
|
+
render json: { errors: ['Unauthorized'] }, status: :unauthorized
|
13
|
+
return
|
14
|
+
end
|
15
|
+
@current_user = User.find(auth_token[:user_id])
|
16
|
+
rescue JWT::VerificationError, JWT::DecodeError
|
17
|
+
render json: { errors: ['Unauthorized'] }, status: :unauthorized
|
18
|
+
end
|
19
|
+
|
20
|
+
private
|
21
|
+
|
22
|
+
def http_token
|
23
|
+
@http_token ||= if request.headers['Authorization'].present?
|
24
|
+
request.headers['Authorization'].split.last
|
25
|
+
end
|
26
|
+
end
|
27
|
+
|
28
|
+
def auth_token
|
29
|
+
@auth_token ||= JsonWebToken.decode(http_token)
|
30
|
+
rescue JWT::ExpiredSignature
|
31
|
+
render json: { error: 'token expired' }
|
32
|
+
end
|
33
|
+
|
34
|
+
def jti_matches?
|
35
|
+
@current_user = User.find(auth_token[:user_id])
|
36
|
+
!@current_user.jti.nil? && @current_user.jti == auth_token[:jti]
|
37
|
+
end
|
38
|
+
|
39
|
+
def user_id_in_token?
|
40
|
+
http_token && auth_token && auth_token[:user_id].to_i && jti_matches?
|
41
|
+
end
|
42
|
+
|
43
|
+
def user_reset_token_in_params?
|
44
|
+
params[:reset_password_token]
|
45
|
+
end
|
46
|
+
end
|
@@ -0,0 +1,39 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
class Api::V1::AuthenticationController < Api::BaseController
|
4
|
+
skip_before_action :authenticate_request!, only: [:authenticate_user]
|
5
|
+
|
6
|
+
def authenticate_user
|
7
|
+
user = User.find_for_database_authentication(email: params[:email])
|
8
|
+
if !user.nil? && user.valid_password?(params[:password])
|
9
|
+
render json: payload(user)
|
10
|
+
else
|
11
|
+
render json: { errors: ['Invalid Username/Password'] }, status: :unauthorized
|
12
|
+
end
|
13
|
+
end
|
14
|
+
|
15
|
+
# Invalidate users JWT, logout user
|
16
|
+
def logout
|
17
|
+
@current_user.jti = SecureRandom.uuid
|
18
|
+
if @current_user.save
|
19
|
+
render json: { success: true }
|
20
|
+
else
|
21
|
+
render json: { success: false }, status: :unprocessable_entity
|
22
|
+
end
|
23
|
+
end
|
24
|
+
|
25
|
+
private
|
26
|
+
|
27
|
+
def payload(user)
|
28
|
+
return nil unless user&.id
|
29
|
+
|
30
|
+
iat = Time.now.to_i
|
31
|
+
exp = Time.now.to_i + 24 * 3600
|
32
|
+
{
|
33
|
+
token: JsonWebToken.encode({ user_id: user.id,
|
34
|
+
jti: user.jti,
|
35
|
+
iat: iat,
|
36
|
+
exp: exp })
|
37
|
+
}
|
38
|
+
end
|
39
|
+
end
|
@@ -0,0 +1,90 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# User controller
|
4
|
+
class Api::V1::PasswordsController < Api::BaseController
|
5
|
+
skip_before_action :authenticate_request!, only: %i[reset_password_instructions verify]
|
6
|
+
|
7
|
+
# Password Reset Flow
|
8
|
+
# 1. User requests password reset instructions by sending params with email
|
9
|
+
# to /api/v1/passwords/reset
|
10
|
+
def reset_password_instructions
|
11
|
+
@user = User.find_by(email: password_params[:email])
|
12
|
+
if @user.nil?
|
13
|
+
render json: { message: 'email not found' }, status: :not_found
|
14
|
+
else
|
15
|
+
@user.reset_password_token = SecureRandom.uuid
|
16
|
+
@user.reset_password_sent_at = Time.now
|
17
|
+
if @user.save
|
18
|
+
JwtMailer.reset_password(@user.id, @user.reset_password_token).deliver
|
19
|
+
render json: { message: 'reset password instructions sent' }, status: :ok
|
20
|
+
else
|
21
|
+
render json: { message: @user.errors }, status: :not_found
|
22
|
+
end
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
# Step 2: User clicks on link in email which sends them to /api/v1/passwords/verify
|
27
|
+
# with a token in the params, if a succesful response is received, the client can
|
28
|
+
# store the newly issued JWT and redirect the user to the password reset form
|
29
|
+
def verify
|
30
|
+
@user = User.where(reset_password_token: params[:token]).first
|
31
|
+
if @user.nil?
|
32
|
+
render json: { message: 'reset password token not found' }, status: :not_found
|
33
|
+
elsif @user.reset_password_sent_at < 1.hour.ago
|
34
|
+
render json: { message: 'reset password token has expired' }, status: :not_found
|
35
|
+
else
|
36
|
+
@user.reset_password_token = nil
|
37
|
+
@user.reset_password_sent_at = nil
|
38
|
+
@user.jti = SecureRandom.uuid
|
39
|
+
@user.save
|
40
|
+
|
41
|
+
iat = Time.now.to_i
|
42
|
+
exp = Time.now.to_i + 10 * 60
|
43
|
+
|
44
|
+
render json: {
|
45
|
+
token: JsonWebToken.encode({ user_id: @user.id,
|
46
|
+
jti: @user.jti,
|
47
|
+
iat: iat,
|
48
|
+
exp: exp })
|
49
|
+
}, status: :ok
|
50
|
+
end
|
51
|
+
end
|
52
|
+
|
53
|
+
# Step 3: User submits password reset form with new password and includes
|
54
|
+
# the newly issued Bearer token within 10 minutes of issuing the token
|
55
|
+
def update_password
|
56
|
+
if user_found? && passwords_match?(password_params[:password],
|
57
|
+
password_params[:password_confirmation])
|
58
|
+
|
59
|
+
password_update(password_params[:password])
|
60
|
+
end
|
61
|
+
end
|
62
|
+
|
63
|
+
private
|
64
|
+
|
65
|
+
def user_found?
|
66
|
+
@user = User.find(auth_token[:user_id])
|
67
|
+
rescue JWT::VerificationError, JWT::DecodeError
|
68
|
+
render json: { errors: ['Unauthorized'] }, status: :unauthorized
|
69
|
+
|
70
|
+
true
|
71
|
+
end
|
72
|
+
|
73
|
+
def passwords_match?(password, password_confirmation)
|
74
|
+
return false if password.nil? || (password != password_confirmation)
|
75
|
+
|
76
|
+
true
|
77
|
+
end
|
78
|
+
|
79
|
+
def password_update(password)
|
80
|
+
if @user.update(password: password, jti: SecureRandom.uuid)
|
81
|
+
render json: { message: 'password updated, please reauthenticate' }, status: :ok
|
82
|
+
else
|
83
|
+
render json: @user.errors, status: :unprocessable_entity
|
84
|
+
end
|
85
|
+
end
|
86
|
+
|
87
|
+
def password_params
|
88
|
+
params.require(:user).permit(:email, :password, :password_confirmation, :reset_password_token)
|
89
|
+
end
|
90
|
+
end
|
@@ -0,0 +1,41 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# User controller
|
4
|
+
class Api::V1::UsersController < Api::BaseController
|
5
|
+
skip_before_action :authenticate_request!, only: %i[create]
|
6
|
+
def create
|
7
|
+
unless user_params[:password] == user_params[:password_confirmation]
|
8
|
+
return render json: { message: "passwords don't match" }, status: :unprocessable_entity
|
9
|
+
end
|
10
|
+
|
11
|
+
user = User.new(user_params)
|
12
|
+
user.jti = SecureRandom.uuid
|
13
|
+
if user.save
|
14
|
+
render partial: 'users/user', locals: { user: user }, status: :created
|
15
|
+
else
|
16
|
+
render json: user.errors, status: :unprocessable_entity
|
17
|
+
end
|
18
|
+
end
|
19
|
+
|
20
|
+
# '/api/v1/me'
|
21
|
+
def me
|
22
|
+
render partial: 'users/user', locals: { user: @current_user }
|
23
|
+
end
|
24
|
+
|
25
|
+
def update
|
26
|
+
@current_user.update(user_params.except(:password_confirmation, :reset_password_token))
|
27
|
+
render partial: 'users/user', locals: { user: @current_user }
|
28
|
+
end
|
29
|
+
|
30
|
+
def destroy
|
31
|
+
@current_user.destroy
|
32
|
+
head :no_content
|
33
|
+
end
|
34
|
+
|
35
|
+
private
|
36
|
+
|
37
|
+
def user_params
|
38
|
+
params.require(:user).permit(:email, :password,
|
39
|
+
:password_confirmation)
|
40
|
+
end
|
41
|
+
end
|
@@ -0,0 +1,11 @@
|
|
1
|
+
class JsonWebToken
|
2
|
+
def self.encode(payload)
|
3
|
+
JWT.encode(payload, Rails.application.secrets.secret_key_base)
|
4
|
+
end
|
5
|
+
|
6
|
+
def self.decode(token)
|
7
|
+
HashWithIndifferentAccess.new(JWT.decode(token, Rails.application.secrets.secret_key_base)[0])
|
8
|
+
rescue StandardError
|
9
|
+
nil
|
10
|
+
end
|
11
|
+
end
|
@@ -0,0 +1,10 @@
|
|
1
|
+
class JwtMailer < ApplicationMailer
|
2
|
+
def reset_password(user_id, raw_token)
|
3
|
+
@resource = User.find(user_id)
|
4
|
+
# TODO: add url environement variable
|
5
|
+
@token_link = "http://localhost:3000/api/v1/passwords/verify?token=#{raw_token}"
|
6
|
+
@token = raw_token
|
7
|
+
mail(to: @resource.email, subject: 'Reset password instructions',
|
8
|
+
template_name: 'reset_password')
|
9
|
+
end
|
10
|
+
end
|
@@ -0,0 +1,8 @@
|
|
1
|
+
<p>Hello <%= @resource.email %>!</p>
|
2
|
+
|
3
|
+
<p>Someone has requested a link to change your password. You can do this by clicking on the link below.</p>
|
4
|
+
|
5
|
+
<a target="_blank" rel="noopener noreferrer" href="<%= @token_link %>">Reset Your Password</a>
|
6
|
+
|
7
|
+
<p>If you didn't request this, please ignore this email.</p>
|
8
|
+
<p>Your password won't change until you reset the password using the token above.</p>
|
data/lib/jwt_api.rb
ADDED
@@ -0,0 +1,33 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'jwt'
|
4
|
+
require_relative 'jwt_api/version'
|
5
|
+
|
6
|
+
module JwtApi
|
7
|
+
class Jwt
|
8
|
+
def initialize(key, algorithm = 'HS256')
|
9
|
+
@key = key
|
10
|
+
@algorithm = algorithm
|
11
|
+
end
|
12
|
+
|
13
|
+
def encode(payload)
|
14
|
+
JWT.encode(payload, @key, @algorithm)
|
15
|
+
end
|
16
|
+
|
17
|
+
def decode(token)
|
18
|
+
JWT.decode(token, @key, @algorithm)
|
19
|
+
end
|
20
|
+
end
|
21
|
+
end
|
22
|
+
|
23
|
+
class JsonWebToken
|
24
|
+
def self.encode(payload)
|
25
|
+
JWT.encode(payload, Rails.application.secrets.secret_key_base)
|
26
|
+
end
|
27
|
+
|
28
|
+
def self.decode(token)
|
29
|
+
HashWithIndifferentAccess.new(JWT.decode(token, Rails.application.secrets.secret_key_base)[0])
|
30
|
+
rescue StandardError
|
31
|
+
nil
|
32
|
+
end
|
33
|
+
end
|
metadata
ADDED
@@ -0,0 +1,90 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: jwt_api
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Leo Policastro
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2021-08-29 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: jwt
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - "~>"
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '2.2'
|
20
|
+
- - ">="
|
21
|
+
- !ruby/object:Gem::Version
|
22
|
+
version: 2.2.3
|
23
|
+
type: :runtime
|
24
|
+
prerelease: false
|
25
|
+
version_requirements: !ruby/object:Gem::Requirement
|
26
|
+
requirements:
|
27
|
+
- - "~>"
|
28
|
+
- !ruby/object:Gem::Version
|
29
|
+
version: '2.2'
|
30
|
+
- - ">="
|
31
|
+
- !ruby/object:Gem::Version
|
32
|
+
version: 2.2.3
|
33
|
+
description: Write a longer description or delete this line.
|
34
|
+
email:
|
35
|
+
- lpolicastro@pm.me
|
36
|
+
executables: []
|
37
|
+
extensions: []
|
38
|
+
extra_rdoc_files: []
|
39
|
+
files:
|
40
|
+
- ".gitignore"
|
41
|
+
- ".rspec"
|
42
|
+
- CHANGELOG.md
|
43
|
+
- CODE_OF_CONDUCT.md
|
44
|
+
- Gemfile
|
45
|
+
- Gemfile.lock
|
46
|
+
- LICENSE.txt
|
47
|
+
- README.md
|
48
|
+
- Rakefile
|
49
|
+
- bin/console
|
50
|
+
- bin/setup
|
51
|
+
- jwt_api.gemspec
|
52
|
+
- lib/generators/jwt_api/setup_generator.rb
|
53
|
+
- lib/generators/jwt_api/templates/api/base_controller.rb
|
54
|
+
- lib/generators/jwt_api/templates/api/v1/authentication_controller.rb
|
55
|
+
- lib/generators/jwt_api/templates/api/v1/passwords_controller.rb
|
56
|
+
- lib/generators/jwt_api/templates/api/v1/users_controller.rb
|
57
|
+
- lib/generators/jwt_api/templates/initializers/json_web_token.rb
|
58
|
+
- lib/generators/jwt_api/templates/mailers/jwt_mailer.rb
|
59
|
+
- lib/generators/jwt_api/templates/views/jwt_mailer/reset_password.html.erb
|
60
|
+
- lib/generators/jwt_api/templates/views/users/_user.html.erb
|
61
|
+
- lib/generators/jwt_api/templates/views/users/_user.json.jbuilder
|
62
|
+
- lib/jwt_api.rb
|
63
|
+
- lib/jwt_api/version.rb
|
64
|
+
homepage: https://github.com/leopolicastro/jwt_api/
|
65
|
+
licenses:
|
66
|
+
- MIT
|
67
|
+
metadata:
|
68
|
+
homepage_uri: https://github.com/leopolicastro/jwt_api/
|
69
|
+
source_code_uri: https://github.com/leopolicastro/jwt_api/
|
70
|
+
changelog_uri: https://github.com/leopolicastro/jwt_api/
|
71
|
+
post_install_message:
|
72
|
+
rdoc_options: []
|
73
|
+
require_paths:
|
74
|
+
- lib
|
75
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
76
|
+
requirements:
|
77
|
+
- - ">="
|
78
|
+
- !ruby/object:Gem::Version
|
79
|
+
version: 2.4.0
|
80
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
81
|
+
requirements:
|
82
|
+
- - ">="
|
83
|
+
- !ruby/object:Gem::Version
|
84
|
+
version: '0'
|
85
|
+
requirements: []
|
86
|
+
rubygems_version: 3.2.22
|
87
|
+
signing_key:
|
88
|
+
specification_version: 4
|
89
|
+
summary: Write a short summary, because RubyGems requires one.
|
90
|
+
test_files: []
|