jwt_rails_api_auth 1.0.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 +7 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/Gemfile +13 -0
- data/LICENSE.txt +21 -0
- data/README.md +128 -0
- data/README_NEW.md +0 -0
- data/Rakefile +12 -0
- data/bin/console +11 -0
- data/bin/setup +8 -0
- data/lib/generators/auth/USAGE +8 -0
- data/lib/generators/auth/auth_generator.rb +87 -0
- data/lib/generators/auth/templates/concerns/authenticatable.rb +77 -0
- data/lib/generators/auth/templates/controllers/auth_controller.rb +84 -0
- data/lib/generators/auth/templates/controllers/password_resets_controller.rb +34 -0
- data/lib/generators/auth/templates/controllers/users_controller.rb +28 -0
- data/lib/generators/auth/templates/initializers/rails_auth_generator.rb +6 -0
- data/lib/generators/auth/templates/mailers/application_mailer.rb +4 -0
- data/lib/generators/auth/templates/mailers/user_mailer.rb +6 -0
- data/lib/generators/auth/templates/migrations/create_refresh_token.rb +14 -0
- data/lib/generators/auth/templates/migrations/create_user.rb +19 -0
- data/lib/generators/auth/templates/models/refresh_token.rb +9 -0
- data/lib/generators/auth/templates/models/user.rb +33 -0
- data/lib/generators/auth/templates/serializers/user_serializer.rb +3 -0
- data/lib/jwt_rails_api_auth/configuration.rb +15 -0
- data/lib/jwt_rails_api_auth/version.rb +5 -0
- data/lib/jwt_rails_api_auth.rb +15 -0
- metadata +136 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: dad33cdca353eeb19fdeaa43506aac4b0befd645b12ec11dd7a961a22b2b0ed9
|
4
|
+
data.tar.gz: 17d215ffa73a2edf08b86a26821455259143c1be15a69ae25b0b3dfc429121ed
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 178edb954c6e849d1980995027749630e5fa555e53878d555f13f37ec886c8e54739225bcc08e15e9e690a811290d5adf1dfdef80d6a4c692e7ac2faaa4ef968
|
7
|
+
data.tar.gz: ba2fe26f98fcaa7287fbf28ba8fea2dabfca18368f96d816c25c63540eacba18a02a9a3462c252b47ca1524f9d551fdd8ed55dc69dc06ae4c1cd76922bfb3295
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
[INSERT CONTACT METHOD].
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: 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) 2025 Zeyad Hassan
|
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,128 @@
|
|
1
|
+
|
2
|
+
|
3
|
+
|
4
|
+
[](https://badge.fury.io/rb/jwt_rails_api_auth)
|
5
|
+
|
6
|
+
|
7
|
+
# JWT Rails-api auth
|
8
|
+
|
9
|
+
**JWTRailsAPIAuth** is a Rails generator that scaffolds a **JWT-based authentication system for rails API** with user management, password resets, refresh token rotation, and secure cookie handling. It saves you weeks of setup by providing all the models, controllers, serializers, and mailers you need for a robust, production-ready authentication flow.
|
10
|
+
|
11
|
+
## Features
|
12
|
+
|
13
|
+
- 🔑 **JWT Authentication**
|
14
|
+
- Access tokens (short-lived, default 15 min)
|
15
|
+
- Refresh tokens (stored securely in HttpOnly cookies)
|
16
|
+
- Token rotation + reuse detection
|
17
|
+
- Logout everywhere
|
18
|
+
- 👤 **User management**
|
19
|
+
- User model with secure password
|
20
|
+
- Role support (admin, user)
|
21
|
+
- ✉️ **Password reset**
|
22
|
+
- Password reset tokens (sent in response until now, you can surly sent via email)
|
23
|
+
- 🛠️ **Rails Generators**
|
24
|
+
- models (`user`,`refresh_token`)
|
25
|
+
- controllers (`auth`, `users`, `password_resets`)
|
26
|
+
- serializers (`user`)
|
27
|
+
- mailers (`user`)
|
28
|
+
- concern (`Authenticatable`)
|
29
|
+
- initializers (`jwt_rails_api_auth`)
|
30
|
+
|
31
|
+
## Installation
|
32
|
+
|
33
|
+
Add this line to your application's Gemfile:
|
34
|
+
|
35
|
+
```bash
|
36
|
+
gem 'jwt_rails_api_auth', '~> 1.0'
|
37
|
+
```
|
38
|
+
|
39
|
+
and then run :
|
40
|
+
```bash
|
41
|
+
bundle Install
|
42
|
+
```
|
43
|
+
Or install it using :
|
44
|
+
```bash
|
45
|
+
gem install jwt_rails_api_auth
|
46
|
+
```
|
47
|
+
|
48
|
+
## Usage/Examples
|
49
|
+
Generate the full authentication system:
|
50
|
+
```bash
|
51
|
+
rails generate auth
|
52
|
+
```
|
53
|
+
|
54
|
+
Then run:
|
55
|
+
```bash
|
56
|
+
bundle install
|
57
|
+
rails db:migrate
|
58
|
+
```
|
59
|
+
|
60
|
+
### What’s Scaffolded
|
61
|
+
|
62
|
+
- **controllers/concerns**
|
63
|
+
- `authenticatable.rb`:
|
64
|
+
Provides JWT-based authentication methods for controllers, including token encoding/decoding, user authorization, and admin checks.
|
65
|
+
|
66
|
+
- **controllers**
|
67
|
+
- `auth_controller.rb`:
|
68
|
+
Handles login, logout, and refresh token actions.
|
69
|
+
- `users_controller.rb`:
|
70
|
+
Manages user creation and allows admins to promote users.
|
71
|
+
- `password_resets_controller.rb`:
|
72
|
+
Handles password reset functionality.
|
73
|
+
|
74
|
+
- **models**
|
75
|
+
- `user.rb`
|
76
|
+
- `refresh_token.rb`
|
77
|
+
|
78
|
+
- **initializers**
|
79
|
+
- `jwt_rails_api_auth.rb`:
|
80
|
+
Template for configuring JwtRailsApiAuth (JWT secret, token expiry, role-based access).
|
81
|
+
|
82
|
+
- **serializers**
|
83
|
+
- `user_serializer.rb`
|
84
|
+
|
85
|
+
- **mailers**
|
86
|
+
- `user_mailer.rb`
|
87
|
+
- `application_mailer.rb`
|
88
|
+
|
89
|
+
- **migrations**
|
90
|
+
- `create_user.rb`
|
91
|
+
- `create_refresh_token.rb`
|
92
|
+
|
93
|
+
- **Also insert required gems in your gemfile and add cors**
|
94
|
+
## API Routes & Request Details
|
95
|
+
|
96
|
+
- **signup**
|
97
|
+
- header: Content-Type application/json
|
98
|
+
- 
|
99
|
+
<!--  signup bad username taken -->
|
100
|
+
<!--  username null -->
|
101
|
+
- **login**
|
102
|
+
- header: Content-Type application/json
|
103
|
+
- 
|
104
|
+
<!--  login bad -->
|
105
|
+
header
|
106
|
+
- **me (current user)**
|
107
|
+
- 
|
108
|
+
- **expired or invalid token**
|
109
|
+
- 
|
110
|
+
- **refresh**
|
111
|
+
- 
|
112
|
+
- **password resets**
|
113
|
+
- 
|
114
|
+
- 
|
115
|
+
- **Logout**
|
116
|
+
- 
|
117
|
+
|
118
|
+
|
119
|
+
## 🤝 Contributing
|
120
|
+
|
121
|
+
Bug reports and pull requests are welcome on GitHub at [https://github.com/Zeyad-Hassan-1/authJWT](https://github.com/Zeyad-Hassan-1/authJWT).
|
122
|
+
|
123
|
+
This project follows a [Code of Conduct](CODE_OF_CONDUCT.md). Please respect it in all interactions.
|
124
|
+
|
125
|
+
|
126
|
+
## Authors
|
127
|
+
|
128
|
+
- [@Zeyad Hassan](https://https://github.com/Zeyad-Hassan-1)
|
data/README_NEW.md
ADDED
File without changes
|
data/Rakefile
ADDED
data/bin/console
ADDED
@@ -0,0 +1,11 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
require "bundler/setup"
|
5
|
+
require "jwt_rails_api_auth"
|
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
|
+
require "irb"
|
11
|
+
IRB.start(__FILE__)
|
data/bin/setup
ADDED
@@ -0,0 +1,87 @@
|
|
1
|
+
class AuthGenerator < Rails::Generators::Base
|
2
|
+
include Rails::Generators::Migration
|
3
|
+
source_root File.expand_path("templates", __dir__)
|
4
|
+
|
5
|
+
def modify_gemfile
|
6
|
+
insert_into_file "Gemfile", after: /^source ['"].*['"]\n/ do
|
7
|
+
<<~RUBY
|
8
|
+
gem 'bcrypt', '~> 3.1', '>= 3.1.12'
|
9
|
+
gem 'jwt', '~> 2.5'
|
10
|
+
gem 'rack-cors'
|
11
|
+
gem 'active_model_serializers', '~> 0.10.12'
|
12
|
+
RUBY
|
13
|
+
end
|
14
|
+
end
|
15
|
+
|
16
|
+
def modify_application_rb
|
17
|
+
insert_into_file "config/application.rb", after: "config.api_only = true\n" do
|
18
|
+
<<~RUBY
|
19
|
+
config.middleware.use ActionDispatch::Cookies
|
20
|
+
RUBY
|
21
|
+
end
|
22
|
+
|
23
|
+
end
|
24
|
+
|
25
|
+
def add_routes
|
26
|
+
route <<~RUBY
|
27
|
+
# config/routes.rb
|
28
|
+
post '/login', to: 'auth#login'
|
29
|
+
post '/refresh', to: 'auth#refresh'
|
30
|
+
post '/logout', to: 'auth#logout'
|
31
|
+
post '/signup', to: 'users#create'
|
32
|
+
get '/me', to: 'users#me'
|
33
|
+
resources :password_resets, only: [:create] do
|
34
|
+
collection do
|
35
|
+
put '/', to: 'password_resets#update' # PUT /password_resets
|
36
|
+
end
|
37
|
+
end
|
38
|
+
RUBY
|
39
|
+
end
|
40
|
+
|
41
|
+
def create_auth_files
|
42
|
+
template "controllers/auth_controller.rb", "app/controllers/auth_controller.rb"
|
43
|
+
template "serializers/user_serializer.rb", "app/serializers/user_serializer.rb"
|
44
|
+
template "controllers/users_controller.rb", "app/controllers/users_controller.rb"
|
45
|
+
template "controllers/password_resets_controller.rb", "app/controllers/password_resets_controller.rb"
|
46
|
+
template "models/user.rb", "app/models/user.rb"
|
47
|
+
template "models/refresh_token.rb", "app/models/refresh_token.rb"
|
48
|
+
template "mailers/user_mailer.rb", "app/mailers/user_mailer.rb"
|
49
|
+
template "mailers/application_mailer.rb", "app/mailers/application_mailer.rb"
|
50
|
+
template "concerns/authenticatable.rb", "app/controllers/concerns/authenticatable.rb"
|
51
|
+
template "initializers/jwt_rails_api_auth.rb", "config/initializers/jwt_rails_api_auth.rb"
|
52
|
+
end
|
53
|
+
|
54
|
+
def modify_application_controller
|
55
|
+
inject_into_class "app/controllers/application_controller.rb", "ApplicationController" do
|
56
|
+
" include Authenticatable\n"
|
57
|
+
end
|
58
|
+
end
|
59
|
+
|
60
|
+
|
61
|
+
def self.next_migration_number(dirname)
|
62
|
+
@prev_migration_nr ||= Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
|
63
|
+
@prev_migration_nr += 1
|
64
|
+
@prev_migration_nr.to_s
|
65
|
+
end
|
66
|
+
|
67
|
+
def copy_migration
|
68
|
+
migration_template "migrations/create_user.rb", "db/migrate/create_users.rb"
|
69
|
+
migration_template "migrations/create_refresh_token.rb", "db/migrate/create_refresh_tokens.rb"
|
70
|
+
end
|
71
|
+
|
72
|
+
def enable_cors
|
73
|
+
insert_into_file "config/application.rb"do
|
74
|
+
<<~RUBY
|
75
|
+
Rails.application.config.middleware.insert_before 0, Rack::Cors do
|
76
|
+
allow do
|
77
|
+
origins "example.com"
|
78
|
+
|
79
|
+
resource "*",
|
80
|
+
headers: :any,
|
81
|
+
methods: [:get, :post, :put, :patch, :delete, :options, :head]
|
82
|
+
end
|
83
|
+
end
|
84
|
+
RUBY
|
85
|
+
end
|
86
|
+
end
|
87
|
+
end
|
@@ -0,0 +1,77 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Authenticatable
|
4
|
+
extend ActiveSupport::Concern
|
5
|
+
|
6
|
+
included do
|
7
|
+
include ActionController::Cookies
|
8
|
+
before_action :authorized
|
9
|
+
|
10
|
+
SECRET_KEY = JwtRailsApiAuth.configuration.jwt_secret
|
11
|
+
|
12
|
+
def encode_token(payload, exp = JwtRailsApiAuth.configuration.access_token_expiry.from_now)
|
13
|
+
|
14
|
+
|
15
|
+
payload[:exp] = exp.to_i
|
16
|
+
payload[:admin] = @user.admin? if @user.is_a?(User) && JwtRailsApiAuth.configuration.enable_roles
|
17
|
+
|
18
|
+
token = JWT.encode(payload, SECRET_KEY)
|
19
|
+
|
20
|
+
end
|
21
|
+
|
22
|
+
def decoded_token
|
23
|
+
header = request.headers['Authorization']
|
24
|
+
return nil unless header
|
25
|
+
|
26
|
+
token = header.split(" ")[1]
|
27
|
+
puts "🔍 DECODE_TOKEN DEBUG: Token: #{token}"
|
28
|
+
|
29
|
+
begin
|
30
|
+
decoded = JWT.decode(token, SECRET_KEY, true, { algorithm: 'HS256', verify_expiration: true })
|
31
|
+
puts " Token valid, expires at: #{Time.at(decoded[0]['exp'])}" if decoded[0]['exp']
|
32
|
+
decoded
|
33
|
+
rescue JWT::ExpiredSignature => e
|
34
|
+
puts " ❌ Token expired: #{e.message}"
|
35
|
+
@token_expired = true
|
36
|
+
nil
|
37
|
+
rescue JWT::DecodeError => e
|
38
|
+
puts " ❌ Token decode error: #{e.message}"
|
39
|
+
nil
|
40
|
+
end
|
41
|
+
end
|
42
|
+
|
43
|
+
def current_user
|
44
|
+
return @current_user if defined?(@current_user)
|
45
|
+
|
46
|
+
if decoded_token
|
47
|
+
user_id = decoded_token[0]['user_id']
|
48
|
+
@current_user = User.find_by(id: user_id)
|
49
|
+
else
|
50
|
+
@current_user = nil
|
51
|
+
end
|
52
|
+
end
|
53
|
+
|
54
|
+
def current_admin
|
55
|
+
current_user && (current_user.admin? || (decoded_token && decoded_token[0]['admin']))
|
56
|
+
end
|
57
|
+
|
58
|
+
def authorized
|
59
|
+
# Check if token is expired first
|
60
|
+
if @token_expired
|
61
|
+
render json: { error: 'Token has expired' }, status: :unauthorized
|
62
|
+
return false
|
63
|
+
end
|
64
|
+
|
65
|
+
unless current_user
|
66
|
+
render json: { message: 'Please log in' }, status: :unauthorized
|
67
|
+
return false
|
68
|
+
end
|
69
|
+
|
70
|
+
true
|
71
|
+
end
|
72
|
+
|
73
|
+
def admin_authorized
|
74
|
+
authorized && current_admin
|
75
|
+
end
|
76
|
+
end
|
77
|
+
end
|
@@ -0,0 +1,84 @@
|
|
1
|
+
require "digest"
|
2
|
+
|
3
|
+
class AuthController < ApplicationController
|
4
|
+
skip_before_action :authorized, only: [:login, :refresh, :logout]
|
5
|
+
rescue_from ActiveRecord::RecordNotFound, with: :handle_record_not_found
|
6
|
+
|
7
|
+
def login
|
8
|
+
user = User.find_by!(username: params[:username])
|
9
|
+
if user.authenticate(params[:password])
|
10
|
+
access_token = encode_token({ user_id: user.id }, 15.minutes.from_now)
|
11
|
+
refresh_raw = user.generate_refresh_token
|
12
|
+
|
13
|
+
set_refresh_cookie(refresh_raw, 7.days.from_now)
|
14
|
+
|
15
|
+
render json: {
|
16
|
+
user: UserSerializer.new(user),
|
17
|
+
access_token: access_token
|
18
|
+
# (we're NOT returning refresh in JSON for security)
|
19
|
+
}, status: :ok
|
20
|
+
else
|
21
|
+
render json: { error: "Invalid credentials" }, status: :unauthorized
|
22
|
+
end
|
23
|
+
end
|
24
|
+
|
25
|
+
def refresh
|
26
|
+
raw = cookies.encrypted[:refresh_token] || params[:refresh_token]
|
27
|
+
return render json: { error: "missing refresh token" }, status: :unauthorized if raw.blank?
|
28
|
+
|
29
|
+
digest = Digest::SHA256.hexdigest(raw)
|
30
|
+
rt = RefreshToken.find_by(token_digest: digest)
|
31
|
+
|
32
|
+
if rt.nil? || rt.revoked_at.present? || rt.expires_at.past?
|
33
|
+
rt&.user&.revoke_all_refresh_tokens!
|
34
|
+
cookies.delete(:refresh_token)
|
35
|
+
return render json: { error: "Invalid or reused refresh token. Logged out everywhere." }, status: :unauthorized
|
36
|
+
end
|
37
|
+
|
38
|
+
# Issue new access + refresh token
|
39
|
+
new_access_token = encode_token({ user_id: rt.user_id })
|
40
|
+
new_refresh_token = rt.user.generate_refresh_token
|
41
|
+
|
42
|
+
# revoke the old token
|
43
|
+
rt.update!(revoked_at: Time.current)
|
44
|
+
|
45
|
+
# 🔑 store new refresh token in HttpOnly cookie
|
46
|
+
set_refresh_cookie(new_refresh_token, 7.days.from_now)
|
47
|
+
|
48
|
+
render json: { access_token: new_access_token }, status: :ok
|
49
|
+
end
|
50
|
+
|
51
|
+
|
52
|
+
|
53
|
+
def logout
|
54
|
+
raw = cookies.encrypted[:refresh_token] || params[:refresh_token]
|
55
|
+
if raw.present?
|
56
|
+
digest = Digest::SHA256.hexdigest(raw)
|
57
|
+
RefreshToken.find_by(token_digest: digest)&.destroy
|
58
|
+
cookies.delete(:refresh_token)
|
59
|
+
end
|
60
|
+
render json: { message: "Logged out" }, status: :ok
|
61
|
+
end
|
62
|
+
|
63
|
+
|
64
|
+
private
|
65
|
+
|
66
|
+
def set_refresh_cookie(raw_token, expires_at)
|
67
|
+
cookies.encrypted[:refresh_token] = {
|
68
|
+
value: raw_token,
|
69
|
+
httponly: true,
|
70
|
+
secure: Rails.env.production?,
|
71
|
+
same_site: :lax,
|
72
|
+
expires: expires_at
|
73
|
+
}
|
74
|
+
end
|
75
|
+
|
76
|
+
def login_params
|
77
|
+
params.permit(:username, :password)
|
78
|
+
end
|
79
|
+
|
80
|
+
def handle_record_not_found(e)
|
81
|
+
render json: { message: "User doesn't exist" }, status: :unauthorized
|
82
|
+
end
|
83
|
+
|
84
|
+
end
|
@@ -0,0 +1,34 @@
|
|
1
|
+
# app/controllers/password_resets_controller.rb
|
2
|
+
class PasswordResetsController < ApplicationController
|
3
|
+
skip_before_action :authorized
|
4
|
+
|
5
|
+
# Request reset (step 1)
|
6
|
+
# New version using username
|
7
|
+
def create
|
8
|
+
user = User.find_by(email: params[:email])
|
9
|
+
if user
|
10
|
+
user.generate_password_reset_token!
|
11
|
+
# Send token via your preferred method (API response, SMS, etc.)
|
12
|
+
render json: {
|
13
|
+
message: "Reset instructions sent",
|
14
|
+
token: user.reset_token # In production, send this via email/SMS instead
|
15
|
+
}
|
16
|
+
else
|
17
|
+
render json: { error: "Username not found" }, status: :not_found
|
18
|
+
end
|
19
|
+
end
|
20
|
+
|
21
|
+
# Actual reset (step 2)
|
22
|
+
def update
|
23
|
+
user = User.find_by(reset_token: params[:token])
|
24
|
+
if user&.reset_sent_at && !user.password_reset_expired?
|
25
|
+
if user.update(password: params[:password], reset_token: nil)
|
26
|
+
render json: { message: "Password updated" }
|
27
|
+
else
|
28
|
+
render json: { errors: user.errors.full_messages }, status: :unprocessable_entity
|
29
|
+
end
|
30
|
+
else
|
31
|
+
render json: { error: "Invalid or expired token" }, status: :unprocessable_entity
|
32
|
+
end
|
33
|
+
end
|
34
|
+
end
|
@@ -0,0 +1,28 @@
|
|
1
|
+
class UsersController < ApplicationController
|
2
|
+
skip_before_action :authorized, only: [:create]
|
3
|
+
rescue_from ActiveRecord::RecordInvalid, with: :handle_invalid_record
|
4
|
+
|
5
|
+
# app/controllers/users_controller.rb
|
6
|
+
def create
|
7
|
+
user = User.create!(user_params)
|
8
|
+
@token = encode_token(user_id: user.id)
|
9
|
+
render json: {
|
10
|
+
user: UserSerializer.new(user),
|
11
|
+
token: @token
|
12
|
+
}, status: :created
|
13
|
+
end
|
14
|
+
|
15
|
+
def me
|
16
|
+
render json: current_user, status: :ok
|
17
|
+
end
|
18
|
+
|
19
|
+
private
|
20
|
+
|
21
|
+
def user_params
|
22
|
+
params.permit(:username, :password, :bio, :email)
|
23
|
+
end
|
24
|
+
|
25
|
+
def handle_invalid_record(e)
|
26
|
+
render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
|
27
|
+
end
|
28
|
+
end
|
@@ -0,0 +1,14 @@
|
|
1
|
+
class CreateRefreshTokens < ActiveRecord::Migration[8.0]
|
2
|
+
def change
|
3
|
+
create_table :refresh_tokens do |t|
|
4
|
+
t.references :user, null: false, foreign_key: true
|
5
|
+
t.string :token_digest, null: false
|
6
|
+
t.datetime :expires_at, null: false
|
7
|
+
t.datetime :revoked_at
|
8
|
+
|
9
|
+
t.timestamps
|
10
|
+
end
|
11
|
+
|
12
|
+
add_index :refresh_tokens, :token_digest, unique: true
|
13
|
+
end
|
14
|
+
end
|
@@ -0,0 +1,19 @@
|
|
1
|
+
class CreateUsers < ActiveRecord::Migration[8.0]
|
2
|
+
def change
|
3
|
+
create_table :users do |t|
|
4
|
+
t.string :username, null: false
|
5
|
+
t.string :email
|
6
|
+
t.string :password_digest, null: false
|
7
|
+
t.string :bio
|
8
|
+
t.boolean :admin, default: false, null: false
|
9
|
+
t.string :reset_token
|
10
|
+
t.datetime :reset_sent_at
|
11
|
+
|
12
|
+
t.timestamps
|
13
|
+
end
|
14
|
+
|
15
|
+
add_index :users, :username, unique: true
|
16
|
+
add_index :users, :admin
|
17
|
+
add_index :users, :reset_token, unique: true
|
18
|
+
end
|
19
|
+
end
|
@@ -0,0 +1,33 @@
|
|
1
|
+
require "digest"
|
2
|
+
|
3
|
+
class User < ApplicationRecord
|
4
|
+
has_secure_password
|
5
|
+
has_many :refresh_tokens, dependent: :destroy
|
6
|
+
validates :username, uniqueness: true
|
7
|
+
|
8
|
+
# returns the RAW token (client uses this), stores only SHA256 digest
|
9
|
+
def generate_refresh_token
|
10
|
+
raw = SecureRandom.hex(64)
|
11
|
+
digest = Digest::SHA256.hexdigest(raw)
|
12
|
+
refresh_tokens.create!(
|
13
|
+
token_digest: digest,
|
14
|
+
expires_at: 7.days.from_now
|
15
|
+
)
|
16
|
+
raw
|
17
|
+
end
|
18
|
+
|
19
|
+
# revoke all tokens for this user
|
20
|
+
def revoke_all_refresh_tokens!
|
21
|
+
refresh_tokens.update_all(revoked_at: Time.current)
|
22
|
+
end
|
23
|
+
|
24
|
+
def generate_password_reset_token!
|
25
|
+
self.reset_token = SecureRandom.urlsafe_base64
|
26
|
+
self.reset_sent_at = Time.now.utc
|
27
|
+
save!(validate: false) # Skip validations for password reset
|
28
|
+
end
|
29
|
+
|
30
|
+
def password_reset_expired?
|
31
|
+
reset_sent_at < 1.hour.ago
|
32
|
+
end
|
33
|
+
end
|
@@ -0,0 +1,15 @@
|
|
1
|
+
module JwtRailsApiAuth
|
2
|
+
class Configuration
|
3
|
+
attr_accessor :jwt_secret,
|
4
|
+
:access_token_expiry,
|
5
|
+
:refresh_token_expiry,
|
6
|
+
:enable_roles
|
7
|
+
|
8
|
+
def initialize
|
9
|
+
@jwt_secret = nil
|
10
|
+
@access_token_expiry = 15.minutes
|
11
|
+
@refresh_token_expiry = 30.days
|
12
|
+
@enable_roles = false
|
13
|
+
end
|
14
|
+
end
|
15
|
+
end
|
@@ -0,0 +1,15 @@
|
|
1
|
+
require "jwt_rails_api_auth/version"
|
2
|
+
require "jwt_rails_api_auth/configuration"
|
3
|
+
|
4
|
+
module JwtRailsApiAuth
|
5
|
+
class Error < StandardError; end
|
6
|
+
|
7
|
+
class << self
|
8
|
+
attr_accessor :configuration
|
9
|
+
|
10
|
+
def configure
|
11
|
+
self.configuration ||= Configuration.new
|
12
|
+
yield(configuration)
|
13
|
+
end
|
14
|
+
end
|
15
|
+
end
|
metadata
ADDED
@@ -0,0 +1,136 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: jwt_rails_api_auth
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 1.0.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Zeyad Hassan
|
8
|
+
bindir: exe
|
9
|
+
cert_chain: []
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
11
|
+
dependencies:
|
12
|
+
- !ruby/object:Gem::Dependency
|
13
|
+
name: rails
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
15
|
+
requirements:
|
16
|
+
- - ">="
|
17
|
+
- !ruby/object:Gem::Version
|
18
|
+
version: '6.0'
|
19
|
+
type: :runtime
|
20
|
+
prerelease: false
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
22
|
+
requirements:
|
23
|
+
- - ">="
|
24
|
+
- !ruby/object:Gem::Version
|
25
|
+
version: '6.0'
|
26
|
+
- !ruby/object:Gem::Dependency
|
27
|
+
name: bcrypt
|
28
|
+
requirement: !ruby/object:Gem::Requirement
|
29
|
+
requirements:
|
30
|
+
- - ">="
|
31
|
+
- !ruby/object:Gem::Version
|
32
|
+
version: 3.1.12
|
33
|
+
type: :runtime
|
34
|
+
prerelease: false
|
35
|
+
version_requirements: !ruby/object:Gem::Requirement
|
36
|
+
requirements:
|
37
|
+
- - ">="
|
38
|
+
- !ruby/object:Gem::Version
|
39
|
+
version: 3.1.12
|
40
|
+
- !ruby/object:Gem::Dependency
|
41
|
+
name: jwt
|
42
|
+
requirement: !ruby/object:Gem::Requirement
|
43
|
+
requirements:
|
44
|
+
- - "~>"
|
45
|
+
- !ruby/object:Gem::Version
|
46
|
+
version: '2.5'
|
47
|
+
type: :runtime
|
48
|
+
prerelease: false
|
49
|
+
version_requirements: !ruby/object:Gem::Requirement
|
50
|
+
requirements:
|
51
|
+
- - "~>"
|
52
|
+
- !ruby/object:Gem::Version
|
53
|
+
version: '2.5'
|
54
|
+
- !ruby/object:Gem::Dependency
|
55
|
+
name: rack-cors
|
56
|
+
requirement: !ruby/object:Gem::Requirement
|
57
|
+
requirements:
|
58
|
+
- - ">="
|
59
|
+
- !ruby/object:Gem::Version
|
60
|
+
version: '0'
|
61
|
+
type: :runtime
|
62
|
+
prerelease: false
|
63
|
+
version_requirements: !ruby/object:Gem::Requirement
|
64
|
+
requirements:
|
65
|
+
- - ">="
|
66
|
+
- !ruby/object:Gem::Version
|
67
|
+
version: '0'
|
68
|
+
- !ruby/object:Gem::Dependency
|
69
|
+
name: active_model_serializers
|
70
|
+
requirement: !ruby/object:Gem::Requirement
|
71
|
+
requirements:
|
72
|
+
- - "~>"
|
73
|
+
- !ruby/object:Gem::Version
|
74
|
+
version: 0.10.12
|
75
|
+
type: :runtime
|
76
|
+
prerelease: false
|
77
|
+
version_requirements: !ruby/object:Gem::Requirement
|
78
|
+
requirements:
|
79
|
+
- - "~>"
|
80
|
+
- !ruby/object:Gem::Version
|
81
|
+
version: 0.10.12
|
82
|
+
email:
|
83
|
+
- " studying.zezo@gmail.com"
|
84
|
+
executables: []
|
85
|
+
extensions: []
|
86
|
+
extra_rdoc_files: []
|
87
|
+
files:
|
88
|
+
- CHANGELOG.md
|
89
|
+
- CODE_OF_CONDUCT.md
|
90
|
+
- Gemfile
|
91
|
+
- LICENSE.txt
|
92
|
+
- README.md
|
93
|
+
- README_NEW.md
|
94
|
+
- Rakefile
|
95
|
+
- bin/console
|
96
|
+
- bin/setup
|
97
|
+
- lib/generators/auth/USAGE
|
98
|
+
- lib/generators/auth/auth_generator.rb
|
99
|
+
- lib/generators/auth/templates/concerns/authenticatable.rb
|
100
|
+
- lib/generators/auth/templates/controllers/auth_controller.rb
|
101
|
+
- lib/generators/auth/templates/controllers/password_resets_controller.rb
|
102
|
+
- lib/generators/auth/templates/controllers/users_controller.rb
|
103
|
+
- lib/generators/auth/templates/initializers/rails_auth_generator.rb
|
104
|
+
- lib/generators/auth/templates/mailers/application_mailer.rb
|
105
|
+
- lib/generators/auth/templates/mailers/user_mailer.rb
|
106
|
+
- lib/generators/auth/templates/migrations/create_refresh_token.rb
|
107
|
+
- lib/generators/auth/templates/migrations/create_user.rb
|
108
|
+
- lib/generators/auth/templates/models/refresh_token.rb
|
109
|
+
- lib/generators/auth/templates/models/user.rb
|
110
|
+
- lib/generators/auth/templates/serializers/user_serializer.rb
|
111
|
+
- lib/jwt_rails_api_auth.rb
|
112
|
+
- lib/jwt_rails_api_auth/configuration.rb
|
113
|
+
- lib/jwt_rails_api_auth/version.rb
|
114
|
+
homepage: https://github.com/Zeyad-Hassan-1/authJWT.git
|
115
|
+
licenses:
|
116
|
+
- MIT
|
117
|
+
metadata: {}
|
118
|
+
rdoc_options: []
|
119
|
+
require_paths:
|
120
|
+
- lib
|
121
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
122
|
+
requirements:
|
123
|
+
- - ">="
|
124
|
+
- !ruby/object:Gem::Version
|
125
|
+
version: 3.2.0
|
126
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
127
|
+
requirements:
|
128
|
+
- - ">="
|
129
|
+
- !ruby/object:Gem::Version
|
130
|
+
version: '0'
|
131
|
+
requirements: []
|
132
|
+
rubygems_version: 3.6.9
|
133
|
+
specification_version: 4
|
134
|
+
summary: Provides Rails generators for authentication, user management, password resets,
|
135
|
+
and mailers, streamlining the setup of secure user authentication in Rails applications.
|
136
|
+
test_files: []
|