Skip to content

Commit ea75a5d

Browse files
committed
feat : Define JWT Generate Task
`development` 환경 어플리케이션 초기화 및 실행 시, 자동으로 JWT를 발급하도록 task를 정의한 후, initializer에 추가했습니다. - `initializer/init_db`를 `init_app`으로 이름을 변경했습니다. - `seeds.rb`에서는 데이터 초기화 & 초기 데이터 주입에 대한 책임만 질 수 있도록 분리했습니다. - `init_app` 내에서 `development` 환경에서만 Seed Data 주입 및 JWT 발급이 되도록 했습니다. * 사용하지 않는 `cors` initializer는 삭제했습니다.
1 parent cb6e20c commit ea75a5d

File tree

3 files changed

+27
-20
lines changed

3 files changed

+27
-20
lines changed
Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
1+
require "rake"
2+
13
if Rails.env.development?
24
Rails.application.config.after_initialize do
3-
require "rake"
45
Rails.application.load_tasks
56
unless ActiveRecord::Base.connection.data_source_exists?("schema_migrations")
67
Rake::Task["db:create"].invoke
78
Rake::Task["db:migrate"].invoke
8-
Rake::Task["db:seed:replant"].invoke
99
end
10+
Rake::Task["db:seed"].invoke
11+
Rake::Task["jwt:generate_for_user"].invoke
12+
Rake::Task["jwt:generate_for_admin"].invoke
1013
end
1114
end
1215

1316
if Rails.env.test?
1417
Rails.application.config.after_initialize do
15-
require "rake"
1618
Rails.application.load_tasks
1719
unless ActiveRecord::Base.connection.data_source_exists?("schema_migrations")
1820
Rake::Task["db:create"].invoke

db/seeds.rb

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,3 @@
1-
require "jwt"
2-
3-
def generate_static_jwt(user_id, role)
4-
payload = {
5-
id: user_id,
6-
role: role,
7-
iat: Time.now.to_i,
8-
exp: Time.now.to_i + (24 * 60 * 60)
9-
}
10-
secret = ENV["JWT_SECRET"]
11-
JWT.encode(payload, secret, 'HS256')
12-
end
13-
141
if User.table_exists?
152
puts "> User table already exists"
163
ActiveRecord::Base.connection.execute("TRUNCATE TABLE users RESTART IDENTITY CASCADE")
@@ -46,7 +33,3 @@ def generate_static_jwt(user_id, role)
4633
])
4734
puts "> Schedule dummy data insert succeeded"
4835
puts ""
49-
50-
puts "> User (user_id 1) JWT : #{generate_static_jwt(1, "user")}"
51-
puts "> Admin (user_id 2) JWT : #{generate_static_jwt(2, "admin")}"
52-
puts ""

lib/tasks/jwt.rake

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
namespace :jwt do
2+
desc "Generate a static JWT token"
3+
task generate_for_user: :environment do
4+
puts "> User (user_id 1) JWT : #{generate_static_jwt(1, "user")}"
5+
end
6+
task generate_for_admin: :environment do
7+
puts "> Admin (user_id 2) JWT : #{generate_static_jwt(2, "admin")}"
8+
end
9+
10+
private
11+
def generate_static_jwt(user_id, role)
12+
# require "jwt"
13+
payload = {
14+
id: user_id,
15+
role: role,
16+
iat: Time.now.to_i,
17+
exp: Time.now.to_i + (24 * 60 * 60)
18+
}
19+
secret = ENV["JWT_SECRET"]
20+
JWT.encode(payload, secret, "HS256")
21+
end
22+
end

0 commit comments

Comments
 (0)