denise-oneill-inbox-ru commited on
Commit
38367b5
·
verified ·
1 Parent(s): 5010ad7

D8 staging from 92665ef4298ecff6735b080ff7901f2c19f719a7 (part 2)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. db/migrate/20260509092831_create_reactions.rb +12 -0
  3. db/migrate/20260509131453_create_active_storage_tables.active_storage.rb +57 -0
  4. db/migrate/20260509131454_create_action_text_tables.action_text.rb +26 -0
  5. db/migrate/20260509131455_create_impressions_table.rb +21 -0
  6. db/migrate/20260513091031_create_settings.rb +15 -0
  7. db/migrate/20260513093050_create_blocked_request_logs.rb +14 -0
  8. db/migrate/20260513101634_create_versions.rb +40 -0
  9. db/migrate/20260513101635_add_object_changes_to_versions.rb +12 -0
  10. db/migrate/20260901031325_create_solid_queue_tables.rb +131 -0
  11. db/migrate/20260902133833_create_friendly_id_slugs.rb +21 -0
  12. db/migrate/20260902133901_add_locale_to_friendly_id_slugs.rb +11 -0
  13. db/migrate/20260922010000_create_image_deliveries.rb +22 -0
  14. db/schema.rb +393 -0
  15. db/seeds.rb +66 -0
  16. deploy/huggingface/README.md +10 -0
  17. docs/rails_blog_management_implementation_plan.en.md +2487 -0
  18. docs/rails_blog_management_implementation_plan.vi.md +2487 -0
  19. docs/rails_blog_management_requirement.en.md +281 -0
  20. docs/rails_blog_management_requirement.vi.md +281 -0
  21. lib/coverage_baseline.rb +31 -0
  22. lib/jwt_encoder.rb +11 -0
  23. lib/tasks/.keep +0 -0
  24. package.json +5 -0
  25. public/400.html +135 -0
  26. public/404.html +135 -0
  27. public/406-unsupported-browser.html +135 -0
  28. public/422.html +135 -0
  29. public/500.html +135 -0
  30. public/favicon.ico +3 -0
  31. public/favicon.png +0 -0
  32. public/favicon.svg +0 -0
  33. public/robots.txt +1 -0
  34. script/.keep +0 -0
  35. script/check_coverage_baseline +41 -0
  36. script/ci_local +9 -0
  37. script/source_archive +8 -0
  38. spec/blueprints/user_blueprint_spec.rb +21 -0
  39. spec/config/active_storage_r2_contract_spec.rb +128 -0
  40. spec/config/d4_runtime_contract_spec.rb +197 -0
  41. spec/config/d8_docker_contract_spec.rb +46 -0
  42. spec/config/d8_hugging_face_host_authorization_spec.rb +47 -0
  43. spec/config/postgresql_adapter_spec.rb +9 -0
  44. spec/config/production_boot_spec.rb +141 -0
  45. spec/config/solid_queue_primary_database_spec.rb +97 -0
  46. spec/controllers/admin/audit_logs_controller_spec.rb +66 -0
  47. spec/controllers/admin/dashboard_controller_spec.rb +16 -0
  48. spec/controllers/admin/settings_controller_spec.rb +36 -0
  49. spec/controllers/api/v1/auth/sessions_controller_spec.rb +13 -0
  50. spec/controllers/api/v1/base_controller_spec.rb +107 -0
.gitattributes CHANGED
@@ -13,3 +13,4 @@ app/assets/images/login.png filter=lfs diff=lfs merge=lfs -text
13
  app/assets/images/profile.png filter=lfs diff=lfs merge=lfs -text
14
  app/assets/images/registration.png filter=lfs diff=lfs merge=lfs -text
15
  app/assets/images/unlock.png filter=lfs diff=lfs merge=lfs -text
 
 
13
  app/assets/images/profile.png filter=lfs diff=lfs merge=lfs -text
14
  app/assets/images/registration.png filter=lfs diff=lfs merge=lfs -text
15
  app/assets/images/unlock.png filter=lfs diff=lfs merge=lfs -text
16
+ public/favicon.ico filter=lfs diff=lfs merge=lfs -text
db/migrate/20260509092831_create_reactions.rb ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class CreateReactions < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :reactions do |t|
4
+ t.string :kind
5
+ t.references :user, null: false, foreign_key: true
6
+ t.references :post, null: false, foreign_key: true
7
+
8
+ t.timestamps
9
+ end
10
+ add_index :reactions, [ :user_id, :post_id, :kind ], unique: true
11
+ end
12
+ end
db/migrate/20260509131453_create_active_storage_tables.active_storage.rb ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This migration comes from active_storage (originally 20170806125915)
2
+ class CreateActiveStorageTables < ActiveRecord::Migration[7.0]
3
+ def change
4
+ # Use Active Record's configured type for primary and foreign keys
5
+ primary_key_type, foreign_key_type = primary_and_foreign_key_types
6
+
7
+ create_table :active_storage_blobs, id: primary_key_type do |t|
8
+ t.string :key, null: false
9
+ t.string :filename, null: false
10
+ t.string :content_type
11
+ t.text :metadata
12
+ t.string :service_name, null: false
13
+ t.bigint :byte_size, null: false
14
+ t.string :checksum
15
+
16
+ if connection.supports_datetime_with_precision?
17
+ t.datetime :created_at, precision: 6, null: false
18
+ else
19
+ t.datetime :created_at, null: false
20
+ end
21
+
22
+ t.index [ :key ], unique: true
23
+ end
24
+
25
+ create_table :active_storage_attachments, id: primary_key_type do |t|
26
+ t.string :name, null: false
27
+ t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type
28
+ t.references :blob, null: false, type: foreign_key_type
29
+
30
+ if connection.supports_datetime_with_precision?
31
+ t.datetime :created_at, precision: 6, null: false
32
+ else
33
+ t.datetime :created_at, null: false
34
+ end
35
+
36
+ t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true
37
+ t.foreign_key :active_storage_blobs, column: :blob_id
38
+ end
39
+
40
+ create_table :active_storage_variant_records, id: primary_key_type do |t|
41
+ t.belongs_to :blob, null: false, index: false, type: foreign_key_type
42
+ t.string :variation_digest, null: false
43
+
44
+ t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true
45
+ t.foreign_key :active_storage_blobs, column: :blob_id
46
+ end
47
+ end
48
+
49
+ private
50
+ def primary_and_foreign_key_types
51
+ config = Rails.configuration.generators
52
+ setting = config.options[config.orm][:primary_key_type]
53
+ primary_key_type = setting || :primary_key
54
+ foreign_key_type = setting || :bigint
55
+ [ primary_key_type, foreign_key_type ]
56
+ end
57
+ end
db/migrate/20260509131454_create_action_text_tables.action_text.rb ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This migration comes from action_text (originally 20180528164100)
2
+ class CreateActionTextTables < ActiveRecord::Migration[6.0]
3
+ def change
4
+ # Use Active Record's configured type for primary and foreign keys
5
+ primary_key_type, foreign_key_type = primary_and_foreign_key_types
6
+
7
+ create_table :action_text_rich_texts, id: primary_key_type do |t|
8
+ t.string :name, null: false
9
+ t.text :body, size: :long
10
+ t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type
11
+
12
+ t.timestamps
13
+
14
+ t.index [ :record_type, :record_id, :name ], name: "index_action_text_rich_texts_uniqueness", unique: true
15
+ end
16
+ end
17
+
18
+ private
19
+ def primary_and_foreign_key_types
20
+ config = Rails.configuration.generators
21
+ setting = config.options[config.orm][:primary_key_type]
22
+ primary_key_type = setting || :primary_key
23
+ foreign_key_type = setting || :bigint
24
+ [ primary_key_type, foreign_key_type ]
25
+ end
26
+ end
db/migrate/20260509131455_create_impressions_table.rb ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class CreateImpressionsTable < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :impressions do |t|
4
+ t.string :impressionable_type
5
+ t.integer :impressionable_id
6
+ t.integer :user_id
7
+ t.string :controller_name
8
+ t.string :action_name
9
+ t.string :view_name
10
+ t.string :request_hash
11
+ t.string :ip_address
12
+ t.string :session_hash
13
+ t.text :message
14
+ t.text :referrer
15
+ t.text :params
16
+ t.timestamps
17
+ end
18
+ add_index :impressions, [ :impressionable_type, :impressionable_id ], name: "index_impressions_on_impressionable"
19
+ add_index :impressions, :user_id
20
+ end
21
+ end
db/migrate/20260513091031_create_settings.rb ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class CreateSettings < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :settings do |t|
4
+ t.string :key, null: false
5
+ t.text :value
6
+ t.string :value_type, default: "string"
7
+ t.string :category, default: "general"
8
+ t.text :description
9
+ t.timestamps
10
+ end
11
+
12
+ add_index :settings, :key, unique: true
13
+ add_index :settings, :category
14
+ end
15
+ end
db/migrate/20260513093050_create_blocked_request_logs.rb ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class CreateBlockedRequestLogs < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :blocked_request_logs do |t|
4
+ t.string :ip, null: false
5
+ t.string :path
6
+ t.string :reason, null: false
7
+ t.string :user_agent
8
+ t.timestamps
9
+ end
10
+
11
+ add_index :blocked_request_logs, :ip
12
+ add_index :blocked_request_logs, :created_at
13
+ end
14
+ end
db/migrate/20260513101634_create_versions.rb ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This migration creates the `versions` table for the Version class.
2
+ # All other migrations PT provides are optional.
3
+ class CreateVersions < ActiveRecord::Migration[8.1]
4
+ # The largest text column available in all supported RDBMS is
5
+ # 1024^3 - 1 bytes, roughly one gibibyte. We specify a size
6
+ # so that MySQL will use `longtext` instead of `text`. Otherwise,
7
+ # when serializing very large objects, `text` might not be big enough.
8
+ TEXT_BYTES = 1_073_741_823
9
+
10
+ def change
11
+ create_table :versions do |t|
12
+ # Consider using bigint type for performance if you are going to store only numeric ids.
13
+ # t.bigint :whodunnit
14
+ t.string :whodunnit
15
+
16
+ # Known issue in MySQL: fractional second precision
17
+ # -------------------------------------------------
18
+ #
19
+ # MySQL timestamp columns do not support fractional seconds unless
20
+ # defined with "fractional seconds precision". MySQL users should manually
21
+ # add fractional seconds precision to this migration, specifically, to
22
+ # the `created_at` column.
23
+ # (https://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html)
24
+ #
25
+ # MySQL users should also upgrade to at least rails 4.2, which is the first
26
+ # version of ActiveRecord with support for fractional seconds in MySQL.
27
+ # (https://github.com/rails/rails/pull/14359)
28
+ #
29
+ # MySQL users should use the following line for `created_at`
30
+ # t.datetime :created_at, limit: 6
31
+ t.datetime :created_at
32
+
33
+ t.bigint :item_id, null: false
34
+ t.string :item_type, null: false
35
+ t.string :event, null: false
36
+ t.text :object, limit: TEXT_BYTES
37
+ end
38
+ add_index :versions, %i[item_type item_id]
39
+ end
40
+ end
db/migrate/20260513101635_add_object_changes_to_versions.rb ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This migration adds the optional `object_changes` column, in which PaperTrail
2
+ # will store the `changes` diff for each update event. See the readme for
3
+ # details.
4
+ class AddObjectChangesToVersions < ActiveRecord::Migration[8.1]
5
+ # The largest text column available in all supported RDBMS.
6
+ # See `create_versions.rb` for details.
7
+ TEXT_BYTES = 1_073_741_823
8
+
9
+ def change
10
+ add_column :versions, :object_changes, :text, limit: TEXT_BYTES
11
+ end
12
+ end
db/migrate/20260901031325_create_solid_queue_tables.rb ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class CreateSolidQueueTables < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table "solid_queue_blocked_executions", force: :cascade do |t|
4
+ t.bigint "job_id", null: false
5
+ t.string "queue_name", null: false
6
+ t.integer "priority", default: 0, null: false
7
+ t.string "concurrency_key", null: false
8
+ t.datetime "expires_at", null: false
9
+ t.datetime "created_at", null: false
10
+ t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release"
11
+ t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance"
12
+ t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true
13
+ end
14
+
15
+ create_table "solid_queue_claimed_executions", force: :cascade do |t|
16
+ t.bigint "job_id", null: false
17
+ t.bigint "process_id"
18
+ t.datetime "created_at", null: false
19
+ t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true
20
+ t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id"
21
+ end
22
+
23
+ create_table "solid_queue_failed_executions", force: :cascade do |t|
24
+ t.bigint "job_id", null: false
25
+ t.text "error"
26
+ t.datetime "created_at", null: false
27
+ t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true
28
+ end
29
+
30
+ create_table "solid_queue_jobs", force: :cascade do |t|
31
+ t.string "queue_name", null: false
32
+ t.string "class_name", null: false
33
+ t.text "arguments"
34
+ t.integer "priority", default: 0, null: false
35
+ t.string "active_job_id"
36
+ t.datetime "scheduled_at"
37
+ t.datetime "finished_at"
38
+ t.string "concurrency_key"
39
+ t.datetime "created_at", null: false
40
+ t.datetime "updated_at", null: false
41
+ t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id"
42
+ t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name"
43
+ t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at"
44
+ t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering"
45
+ t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting"
46
+ end
47
+
48
+ create_table "solid_queue_pauses", force: :cascade do |t|
49
+ t.string "queue_name", null: false
50
+ t.datetime "created_at", null: false
51
+ t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true
52
+ end
53
+
54
+ create_table "solid_queue_processes", force: :cascade do |t|
55
+ t.string "kind", null: false
56
+ t.datetime "last_heartbeat_at", null: false
57
+ t.bigint "supervisor_id"
58
+ t.integer "pid", null: false
59
+ t.string "hostname"
60
+ t.text "metadata"
61
+ t.datetime "created_at", null: false
62
+ t.string "name", null: false
63
+ t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at"
64
+ t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true
65
+ t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id"
66
+ end
67
+
68
+ create_table "solid_queue_ready_executions", force: :cascade do |t|
69
+ t.bigint "job_id", null: false
70
+ t.string "queue_name", null: false
71
+ t.integer "priority", default: 0, null: false
72
+ t.datetime "created_at", null: false
73
+ t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true
74
+ t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all"
75
+ t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue"
76
+ end
77
+
78
+ create_table "solid_queue_recurring_executions", force: :cascade do |t|
79
+ t.bigint "job_id", null: false
80
+ t.string "task_key", null: false
81
+ t.datetime "run_at", null: false
82
+ t.datetime "created_at", null: false
83
+ t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true
84
+ t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true
85
+ end
86
+
87
+ create_table "solid_queue_recurring_tasks", force: :cascade do |t|
88
+ t.string "key", null: false
89
+ t.string "schedule", null: false
90
+ t.string "command", limit: 2048
91
+ t.string "class_name"
92
+ t.text "arguments"
93
+ t.string "queue_name"
94
+ t.integer "priority", default: 0
95
+ t.boolean "static", default: true, null: false
96
+ t.text "description"
97
+ t.datetime "created_at", null: false
98
+ t.datetime "updated_at", null: false
99
+ t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true
100
+ t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static"
101
+ end
102
+
103
+ create_table "solid_queue_scheduled_executions", force: :cascade do |t|
104
+ t.bigint "job_id", null: false
105
+ t.string "queue_name", null: false
106
+ t.integer "priority", default: 0, null: false
107
+ t.datetime "scheduled_at", null: false
108
+ t.datetime "created_at", null: false
109
+ t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true
110
+ t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all"
111
+ end
112
+
113
+ create_table "solid_queue_semaphores", force: :cascade do |t|
114
+ t.string "key", null: false
115
+ t.integer "value", default: 1, null: false
116
+ t.datetime "expires_at", null: false
117
+ t.datetime "created_at", null: false
118
+ t.datetime "updated_at", null: false
119
+ t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at"
120
+ t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value"
121
+ t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true
122
+ end
123
+
124
+ add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
125
+ add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
126
+ add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
127
+ add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
128
+ add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
129
+ add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
130
+ end
131
+ end
db/migrate/20260902133833_create_friendly_id_slugs.rb ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIGRATION_CLASS =
2
+ if ActiveRecord::VERSION::MAJOR >= 5
3
+ ActiveRecord::Migration["#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}"]
4
+ else
5
+ ActiveRecord::Migration
6
+ end
7
+
8
+ class CreateFriendlyIdSlugs < MIGRATION_CLASS
9
+ def change
10
+ create_table :friendly_id_slugs do |t|
11
+ t.string :slug, null: false
12
+ t.integer :sluggable_id, null: false
13
+ t.string :sluggable_type, limit: 50
14
+ t.string :scope
15
+ t.datetime :created_at
16
+ end
17
+ add_index :friendly_id_slugs, [ :sluggable_type, :sluggable_id ]
18
+ add_index :friendly_id_slugs, [ :slug, :sluggable_type ], length: { slug: 140, sluggable_type: 50 }
19
+ add_index :friendly_id_slugs, [ :slug, :sluggable_type, :scope ], length: { slug: 70, sluggable_type: 50, scope: 70 }, unique: true
20
+ end
21
+ end
db/migrate/20260902133901_add_locale_to_friendly_id_slugs.rb ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class AddLocaleToFriendlyIdSlugs < ActiveRecord::Migration[8.1]
2
+ def change
3
+ add_column :friendly_id_slugs, :locale, :string, null: false
4
+
5
+ remove_index :friendly_id_slugs, [ :slug, :sluggable_type ]
6
+ add_index :friendly_id_slugs, [ :slug, :sluggable_type, :locale ], length: { slug: 140, sluggable_type: 50, locale: 2 }
7
+ remove_index :friendly_id_slugs, [ :slug, :sluggable_type, :scope ]
8
+ add_index :friendly_id_slugs, [ :slug, :sluggable_type, :scope, :locale ], length: { slug: 70, sluggable_type: 50, scope: 70, locale: 2 }, unique: true, name: :index_friendly_id_slugs_unique
9
+ add_index :friendly_id_slugs, :locale
10
+ end
11
+ end
db/migrate/20260922010000_create_image_deliveries.rb ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class CreateImageDeliveries < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :image_deliveries do |t|
4
+ t.references :active_storage_blob,
5
+ null: false,
6
+ foreign_key: { to_table: :active_storage_blobs },
7
+ index: { unique: true }
8
+ t.string :cloudinary_public_id
9
+ t.string :cloudinary_asset_id
10
+ t.string :cloudinary_version
11
+ t.string :source_checksum, null: false
12
+ t.string :status, null: false, default: "pending"
13
+ t.string :failure_reason
14
+
15
+ t.timestamps
16
+ end
17
+
18
+ add_check_constraint :image_deliveries,
19
+ "status IN ('pending', 'ready', 'failed')",
20
+ name: "image_deliveries_status_check"
21
+ end
22
+ end
db/schema.rb ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is auto-generated from the current state of the database. Instead
2
+ # of editing this file, please use the migrations feature of Active Record to
3
+ # incrementally modify your database, and then regenerate this schema definition.
4
+ #
5
+ # This file is the source Rails uses to define your schema when running `bin/rails
6
+ # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
7
+ # be faster and is potentially less error prone than running all of your
8
+ # migrations from scratch. Old migrations may fail to apply correctly if those
9
+ # migrations use external dependencies or application code.
10
+ #
11
+ # It's strongly recommended that you check this file into your version control system.
12
+
13
+ ActiveRecord::Schema[8.1].define(version: 2026_09_22_010000) do
14
+ # These are extensions that must be enabled in order to support this database
15
+ enable_extension "pg_catalog.plpgsql"
16
+
17
+ create_table "action_text_rich_texts", force: :cascade do |t|
18
+ t.text "body"
19
+ t.datetime "created_at", null: false
20
+ t.string "name", null: false
21
+ t.bigint "record_id", null: false
22
+ t.string "record_type", null: false
23
+ t.datetime "updated_at", null: false
24
+ t.index ["record_type", "record_id", "name"], name: "index_action_text_rich_texts_uniqueness", unique: true
25
+ end
26
+
27
+ create_table "active_storage_attachments", force: :cascade do |t|
28
+ t.bigint "blob_id", null: false
29
+ t.datetime "created_at", null: false
30
+ t.string "name", null: false
31
+ t.bigint "record_id", null: false
32
+ t.string "record_type", null: false
33
+ t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
34
+ t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
35
+ end
36
+
37
+ create_table "active_storage_blobs", force: :cascade do |t|
38
+ t.bigint "byte_size", null: false
39
+ t.string "checksum"
40
+ t.string "content_type"
41
+ t.datetime "created_at", null: false
42
+ t.string "filename", null: false
43
+ t.string "key", null: false
44
+ t.text "metadata"
45
+ t.string "service_name", null: false
46
+ t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
47
+ end
48
+
49
+ create_table "active_storage_variant_records", force: :cascade do |t|
50
+ t.bigint "blob_id", null: false
51
+ t.string "variation_digest", null: false
52
+ t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
53
+ end
54
+
55
+ create_table "blocked_request_logs", force: :cascade do |t|
56
+ t.datetime "created_at", null: false
57
+ t.string "ip", null: false
58
+ t.string "path"
59
+ t.string "reason", null: false
60
+ t.datetime "updated_at", null: false
61
+ t.string "user_agent"
62
+ t.index ["created_at"], name: "index_blocked_request_logs_on_created_at"
63
+ t.index ["ip"], name: "index_blocked_request_logs_on_ip"
64
+ end
65
+
66
+ create_table "categories", force: :cascade do |t|
67
+ t.datetime "created_at", null: false
68
+ t.string "name", null: false
69
+ t.string "slug", null: false
70
+ t.datetime "updated_at", null: false
71
+ t.index ["name"], name: "index_categories_on_name", unique: true
72
+ t.index ["slug"], name: "index_categories_on_slug", unique: true
73
+ end
74
+
75
+ create_table "comments", force: :cascade do |t|
76
+ t.text "body"
77
+ t.datetime "created_at", null: false
78
+ t.datetime "discarded_at"
79
+ t.integer "post_id", null: false
80
+ t.datetime "updated_at", null: false
81
+ t.integer "user_id", null: false
82
+ t.index ["discarded_at"], name: "index_comments_on_discarded_at"
83
+ t.index ["post_id"], name: "index_comments_on_post_id"
84
+ t.index ["user_id"], name: "index_comments_on_user_id"
85
+ end
86
+
87
+ create_table "friendly_id_slugs", force: :cascade do |t|
88
+ t.datetime "created_at"
89
+ t.string "locale", null: false
90
+ t.string "scope"
91
+ t.string "slug", null: false
92
+ t.integer "sluggable_id", null: false
93
+ t.string "sluggable_type", limit: 50
94
+ t.index ["locale"], name: "index_friendly_id_slugs_on_locale"
95
+ t.index ["slug", "sluggable_type", "locale"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_locale"
96
+ t.index ["slug", "sluggable_type", "scope", "locale"], name: "index_friendly_id_slugs_unique", unique: true
97
+ t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id"
98
+ end
99
+
100
+ create_table "image_deliveries", force: :cascade do |t|
101
+ t.bigint "active_storage_blob_id", null: false
102
+ t.string "cloudinary_asset_id"
103
+ t.string "cloudinary_public_id"
104
+ t.string "cloudinary_version"
105
+ t.datetime "created_at", null: false
106
+ t.string "failure_reason"
107
+ t.string "source_checksum", null: false
108
+ t.string "status", default: "pending", null: false
109
+ t.datetime "updated_at", null: false
110
+ t.index ["active_storage_blob_id"], name: "index_image_deliveries_on_active_storage_blob_id", unique: true
111
+ t.check_constraint "status::text = ANY (ARRAY['pending'::character varying, 'ready'::character varying, 'failed'::character varying]::text[])", name: "image_deliveries_status_check"
112
+ end
113
+
114
+ create_table "impressions", force: :cascade do |t|
115
+ t.string "action_name"
116
+ t.string "controller_name"
117
+ t.datetime "created_at", null: false
118
+ t.integer "impressionable_id"
119
+ t.string "impressionable_type"
120
+ t.string "ip_address"
121
+ t.text "message"
122
+ t.text "params"
123
+ t.text "referrer"
124
+ t.string "request_hash"
125
+ t.string "session_hash"
126
+ t.datetime "updated_at", null: false
127
+ t.integer "user_id"
128
+ t.string "view_name"
129
+ t.index ["impressionable_type", "impressionable_id"], name: "index_impressions_on_impressionable"
130
+ t.index ["user_id"], name: "index_impressions_on_user_id"
131
+ end
132
+
133
+ create_table "jwt_denylist", force: :cascade do |t|
134
+ t.datetime "exp", null: false
135
+ t.string "jti", null: false
136
+ t.index ["jti"], name: "index_jwt_denylist_on_jti"
137
+ end
138
+
139
+ create_table "post_tags", force: :cascade do |t|
140
+ t.datetime "created_at", null: false
141
+ t.integer "post_id", null: false
142
+ t.integer "tag_id", null: false
143
+ t.datetime "updated_at", null: false
144
+ t.index ["post_id", "tag_id"], name: "index_post_tags_on_post_id_and_tag_id", unique: true
145
+ t.index ["post_id"], name: "index_post_tags_on_post_id"
146
+ t.index ["tag_id"], name: "index_post_tags_on_tag_id"
147
+ end
148
+
149
+ create_table "post_translations", force: :cascade do |t|
150
+ t.datetime "created_at", null: false
151
+ t.string "locale", null: false
152
+ t.integer "post_id", null: false
153
+ t.string "slug"
154
+ t.string "title"
155
+ t.datetime "updated_at", null: false
156
+ t.index ["post_id", "locale"], name: "index_post_translations_on_post_id_and_locale", unique: true
157
+ t.index ["post_id"], name: "index_post_translations_on_post_id"
158
+ t.index ["slug"], name: "index_post_translations_on_slug"
159
+ end
160
+
161
+ create_table "posts", force: :cascade do |t|
162
+ t.integer "category_id", null: false
163
+ t.string "cloudinary_public_id"
164
+ t.integer "comments_count", default: 0
165
+ t.datetime "created_at", null: false
166
+ t.datetime "discarded_at"
167
+ t.integer "impressions_count", default: 0
168
+ t.datetime "published_at"
169
+ t.datetime "scheduled_at"
170
+ t.string "status", default: "draft", null: false
171
+ t.datetime "updated_at", null: false
172
+ t.integer "user_id", null: false
173
+ t.index ["category_id"], name: "index_posts_on_category_id"
174
+ t.index ["discarded_at"], name: "index_posts_on_discarded_at"
175
+ t.index ["published_at"], name: "index_posts_on_published_at"
176
+ t.index ["status"], name: "index_posts_on_status"
177
+ t.index ["user_id"], name: "index_posts_on_user_id"
178
+ end
179
+
180
+ create_table "reactions", force: :cascade do |t|
181
+ t.datetime "created_at", null: false
182
+ t.string "kind"
183
+ t.integer "post_id", null: false
184
+ t.datetime "updated_at", null: false
185
+ t.integer "user_id", null: false
186
+ t.index ["post_id"], name: "index_reactions_on_post_id"
187
+ t.index ["user_id", "post_id", "kind"], name: "index_reactions_on_user_id_and_post_id_and_kind", unique: true
188
+ t.index ["user_id"], name: "index_reactions_on_user_id"
189
+ end
190
+
191
+ create_table "settings", force: :cascade do |t|
192
+ t.string "category", default: "general"
193
+ t.datetime "created_at", null: false
194
+ t.text "description"
195
+ t.string "key", null: false
196
+ t.datetime "updated_at", null: false
197
+ t.text "value"
198
+ t.string "value_type", default: "string"
199
+ t.index ["category"], name: "index_settings_on_category"
200
+ t.index ["key"], name: "index_settings_on_key", unique: true
201
+ end
202
+
203
+ create_table "solid_queue_blocked_executions", force: :cascade do |t|
204
+ t.string "concurrency_key", null: false
205
+ t.datetime "created_at", null: false
206
+ t.datetime "expires_at", null: false
207
+ t.bigint "job_id", null: false
208
+ t.integer "priority", default: 0, null: false
209
+ t.string "queue_name", null: false
210
+ t.index ["concurrency_key", "priority", "job_id"], name: "index_solid_queue_blocked_executions_for_release"
211
+ t.index ["expires_at", "concurrency_key"], name: "index_solid_queue_blocked_executions_for_maintenance"
212
+ t.index ["job_id"], name: "index_solid_queue_blocked_executions_on_job_id", unique: true
213
+ end
214
+
215
+ create_table "solid_queue_claimed_executions", force: :cascade do |t|
216
+ t.datetime "created_at", null: false
217
+ t.bigint "job_id", null: false
218
+ t.bigint "process_id"
219
+ t.index ["job_id"], name: "index_solid_queue_claimed_executions_on_job_id", unique: true
220
+ t.index ["process_id", "job_id"], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id"
221
+ end
222
+
223
+ create_table "solid_queue_failed_executions", force: :cascade do |t|
224
+ t.datetime "created_at", null: false
225
+ t.text "error"
226
+ t.bigint "job_id", null: false
227
+ t.index ["job_id"], name: "index_solid_queue_failed_executions_on_job_id", unique: true
228
+ end
229
+
230
+ create_table "solid_queue_jobs", force: :cascade do |t|
231
+ t.string "active_job_id"
232
+ t.text "arguments"
233
+ t.string "class_name", null: false
234
+ t.string "concurrency_key"
235
+ t.datetime "created_at", null: false
236
+ t.datetime "finished_at"
237
+ t.integer "priority", default: 0, null: false
238
+ t.string "queue_name", null: false
239
+ t.datetime "scheduled_at"
240
+ t.datetime "updated_at", null: false
241
+ t.index ["active_job_id"], name: "index_solid_queue_jobs_on_active_job_id"
242
+ t.index ["class_name"], name: "index_solid_queue_jobs_on_class_name"
243
+ t.index ["finished_at"], name: "index_solid_queue_jobs_on_finished_at"
244
+ t.index ["queue_name", "finished_at"], name: "index_solid_queue_jobs_for_filtering"
245
+ t.index ["scheduled_at", "finished_at"], name: "index_solid_queue_jobs_for_alerting"
246
+ end
247
+
248
+ create_table "solid_queue_pauses", force: :cascade do |t|
249
+ t.datetime "created_at", null: false
250
+ t.string "queue_name", null: false
251
+ t.index ["queue_name"], name: "index_solid_queue_pauses_on_queue_name", unique: true
252
+ end
253
+
254
+ create_table "solid_queue_processes", force: :cascade do |t|
255
+ t.datetime "created_at", null: false
256
+ t.string "hostname"
257
+ t.string "kind", null: false
258
+ t.datetime "last_heartbeat_at", null: false
259
+ t.text "metadata"
260
+ t.string "name", null: false
261
+ t.integer "pid", null: false
262
+ t.bigint "supervisor_id"
263
+ t.index ["last_heartbeat_at"], name: "index_solid_queue_processes_on_last_heartbeat_at"
264
+ t.index ["name", "supervisor_id"], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true
265
+ t.index ["supervisor_id"], name: "index_solid_queue_processes_on_supervisor_id"
266
+ end
267
+
268
+ create_table "solid_queue_ready_executions", force: :cascade do |t|
269
+ t.datetime "created_at", null: false
270
+ t.bigint "job_id", null: false
271
+ t.integer "priority", default: 0, null: false
272
+ t.string "queue_name", null: false
273
+ t.index ["job_id"], name: "index_solid_queue_ready_executions_on_job_id", unique: true
274
+ t.index ["priority", "job_id"], name: "index_solid_queue_poll_all"
275
+ t.index ["queue_name", "priority", "job_id"], name: "index_solid_queue_poll_by_queue"
276
+ end
277
+
278
+ create_table "solid_queue_recurring_executions", force: :cascade do |t|
279
+ t.datetime "created_at", null: false
280
+ t.bigint "job_id", null: false
281
+ t.datetime "run_at", null: false
282
+ t.string "task_key", null: false
283
+ t.index ["job_id"], name: "index_solid_queue_recurring_executions_on_job_id", unique: true
284
+ t.index ["task_key", "run_at"], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true
285
+ end
286
+
287
+ create_table "solid_queue_recurring_tasks", force: :cascade do |t|
288
+ t.text "arguments"
289
+ t.string "class_name"
290
+ t.string "command", limit: 2048
291
+ t.datetime "created_at", null: false
292
+ t.text "description"
293
+ t.string "key", null: false
294
+ t.integer "priority", default: 0
295
+ t.string "queue_name"
296
+ t.string "schedule", null: false
297
+ t.boolean "static", default: true, null: false
298
+ t.datetime "updated_at", null: false
299
+ t.index ["key"], name: "index_solid_queue_recurring_tasks_on_key", unique: true
300
+ t.index ["static"], name: "index_solid_queue_recurring_tasks_on_static"
301
+ end
302
+
303
+ create_table "solid_queue_scheduled_executions", force: :cascade do |t|
304
+ t.datetime "created_at", null: false
305
+ t.bigint "job_id", null: false
306
+ t.integer "priority", default: 0, null: false
307
+ t.string "queue_name", null: false
308
+ t.datetime "scheduled_at", null: false
309
+ t.index ["job_id"], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true
310
+ t.index ["scheduled_at", "priority", "job_id"], name: "index_solid_queue_dispatch_all"
311
+ end
312
+
313
+ create_table "solid_queue_semaphores", force: :cascade do |t|
314
+ t.datetime "created_at", null: false
315
+ t.datetime "expires_at", null: false
316
+ t.string "key", null: false
317
+ t.datetime "updated_at", null: false
318
+ t.integer "value", default: 1, null: false
319
+ t.index ["expires_at"], name: "index_solid_queue_semaphores_on_expires_at"
320
+ t.index ["key", "value"], name: "index_solid_queue_semaphores_on_key_and_value"
321
+ t.index ["key"], name: "index_solid_queue_semaphores_on_key", unique: true
322
+ end
323
+
324
+ create_table "tags", force: :cascade do |t|
325
+ t.datetime "created_at", null: false
326
+ t.string "name", null: false
327
+ t.string "slug", null: false
328
+ t.datetime "updated_at", null: false
329
+ t.index ["name"], name: "index_tags_on_name", unique: true
330
+ t.index ["slug"], name: "index_tags_on_slug", unique: true
331
+ end
332
+
333
+ create_table "users", force: :cascade do |t|
334
+ t.string "avatar_public_id"
335
+ t.datetime "confirmation_sent_at"
336
+ t.string "confirmation_token"
337
+ t.datetime "confirmed_at"
338
+ t.datetime "created_at", null: false
339
+ t.datetime "current_sign_in_at"
340
+ t.string "current_sign_in_ip"
341
+ t.string "email", default: "", null: false
342
+ t.string "encrypted_password", default: "", null: false
343
+ t.integer "failed_attempts", default: 0, null: false
344
+ t.string "full_name"
345
+ t.string "jti", null: false
346
+ t.datetime "last_sign_in_at"
347
+ t.string "last_sign_in_ip"
348
+ t.datetime "locked_at"
349
+ t.datetime "remember_created_at"
350
+ t.datetime "reset_password_sent_at"
351
+ t.string "reset_password_token"
352
+ t.string "role", default: "reader", null: false
353
+ t.integer "sign_in_count", default: 0, null: false
354
+ t.string "unconfirmed_email"
355
+ t.string "unlock_token"
356
+ t.datetime "updated_at", null: false
357
+ t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
358
+ t.index ["email"], name: "index_users_on_email", unique: true
359
+ t.index ["jti"], name: "index_users_on_jti", unique: true
360
+ t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
361
+ t.index ["unlock_token"], name: "index_users_on_unlock_token", unique: true
362
+ end
363
+
364
+ create_table "versions", force: :cascade do |t|
365
+ t.datetime "created_at"
366
+ t.string "event", null: false
367
+ t.bigint "item_id", null: false
368
+ t.string "item_type", null: false
369
+ t.text "object"
370
+ t.text "object_changes"
371
+ t.string "whodunnit"
372
+ t.index ["item_type", "item_id"], name: "index_versions_on_item_type_and_item_id"
373
+ end
374
+
375
+ add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
376
+ add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
377
+ add_foreign_key "comments", "posts"
378
+ add_foreign_key "comments", "users"
379
+ add_foreign_key "image_deliveries", "active_storage_blobs"
380
+ add_foreign_key "post_tags", "posts"
381
+ add_foreign_key "post_tags", "tags"
382
+ add_foreign_key "post_translations", "posts"
383
+ add_foreign_key "posts", "categories"
384
+ add_foreign_key "posts", "users"
385
+ add_foreign_key "reactions", "posts"
386
+ add_foreign_key "reactions", "users"
387
+ add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
388
+ add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
389
+ add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
390
+ add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
391
+ add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
392
+ add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
393
+ end
db/seeds.rb ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ unless Rails.env.test?
2
+ # This file should ensure the existence of records required to run the application in every environment (production,
3
+ # development, test). The code here should be idempotent so that it can be executed at any point in every environment.
4
+ # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
5
+ #
6
+ # Example:
7
+ #
8
+ # ["Action", "Comedy", "Drama", "Horror"].each do |genre_name|
9
+ # MovieGenre.find_or_create_by!(name: genre_name)
10
+ # end
11
+
12
+ # Create test users
13
+ users = [
14
+ { email: 'admin@example.com', full_name: 'Admin User', role: 'admin', password: 'Password123!' },
15
+ { email: 'author@example.com', full_name: 'Author User', role: 'author', password: 'Password123!' },
16
+ { email: 'reader@example.com', full_name: 'Reader User', role: 'reader', password: 'Password123!' }
17
+ ]
18
+
19
+ users.each do |user_attrs|
20
+ User.find_or_create_by!(email: user_attrs[:email]) do |user|
21
+ user.full_name = user_attrs[:full_name]
22
+ user.role = user_attrs[:role]
23
+ user.password = user_attrs[:password]
24
+ user.password_confirmation = user_attrs[:password]
25
+ user.confirmed_at = Time.current
26
+ end
27
+ end
28
+
29
+ puts "Created test users:"
30
+ puts "- admin@example.com (admin)"
31
+ puts "- author@example.com (author)"
32
+ puts "- reader@example.com (reader)"
33
+ puts "Password for all: Password123!"
34
+
35
+ # Create default security settings
36
+ security_settings = [
37
+ { key: "rack_login_limit", value: "5", value_type: "integer", category: "security", description: "Max login attempts per period" },
38
+ { key: "rack_login_period", value: "60", value_type: "integer", category: "security", description: "Login throttle period in seconds" },
39
+ { key: "devise_lock_attempts", value: "5", value_type: "integer", category: "security", description: "Max failed attempts before account lock" },
40
+ { key: "blocked_ips", value: "[]", value_type: "array", category: "security", description: "List of blocked IP addresses" },
41
+ { key: "whitelist_ips", value: "[]", value_type: "array", category: "security", description: "List of whitelisted IP addresses" },
42
+ { key: "maintenance_mode", value: "false", value_type: "boolean", category: "general", description: "Enable maintenance mode" },
43
+
44
+ # Media settings
45
+ { key: "thumbnail_width", value: "800", value_type: "integer", category: "media", description: "Post thumbnail width (px)" },
46
+ { key: "thumbnail_height", value: "450", value_type: "integer", category: "media", description: "Post thumbnail height (px)" },
47
+ { key: "slideshow_max_size", value: "5", value_type: "integer", category: "media", description: "Max images in slideshow" },
48
+ { key: "max_upload_size_mb", value: "10", value_type: "integer", category: "media", description: "Max upload size in MB" },
49
+
50
+ # Email settings
51
+ { key: "smtp_providers", value: '[{"name":"Postmark","host":"smtp.postmarkapp.com","port":587,"username":"","password":"","active":true}]', value_type: "array", category: "email", description: "SMTP provider list" },
52
+ { key: "smtp_strategy", value: "round_robin", value_type: "string", category: "email", description: "SMTP selection strategy (round_robin, random)" },
53
+ { key: "smtp_force_provider", value: "", value_type: "string", category: "email", description: "Force specific SMTP provider" }
54
+ ]
55
+
56
+ security_settings.each do |setting_attrs|
57
+ Setting.find_or_create_by!(key: setting_attrs[:key]) do |setting|
58
+ setting.value = setting_attrs[:value]
59
+ setting.value_type = setting_attrs[:value_type]
60
+ setting.category = setting_attrs[:category]
61
+ setting.description = setting_attrs[:description]
62
+ end
63
+ end
64
+
65
+ puts "\nCreated default settings (security, media, email)"
66
+ end
deploy/huggingface/README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Rails 8 Blog Staging
3
+ sdk: docker
4
+ app_port: 7860
5
+ ---
6
+
7
+ # Rails 8 Blog — Staging
8
+
9
+ Deployment mirror of the Rails application.
10
+ Not a production release.
docs/rails_blog_management_implementation_plan.en.md ADDED
@@ -0,0 +1,2487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Detailed Implementation Plan: Rails Blog Management (Enterprise & API Ready)
2
+
3
+ > **Version:** 1.1 | **Stack:** Ruby on Rails 8, Hotwire, Cloudinary, Devise + JWT, Redis, Sidekiq, Mobility
4
+ > **Document objective:** A step-by-step guide detailed enough for both the AI assistant and the developer to execute independently.
5
+ >
6
+ > **Changelog v1.1:** Fixed `database.yml` for SQLite3; added `dotenv-rails`; added `omniauthable`; added `Category`, `Tag` models; added `BlockedRequestLog` model + migration; added `AdminNotificationJob` + `AdminMailer`; added Cloudinary Media Library SDK; added a base `AdminController`; added a Settings UI controller + view; fixed Pagy usage in the API; clarified the 4-step Post workflow; added GitHub Actions CI config.
7
+
8
+ ---
9
+
10
+ ## 📊 Progress Tracking
11
+
12
+ | Phase | Status | Description |
13
+ |-------|--------|-------------|
14
+ | Phase 0 | ✅ Completed | Project Bootstrap & Environment Configuration |
15
+ | Phase 1 | ✅ Completed | Authentication & Authorization (Devise + JWT) |
16
+ | Phase 2 | ✅ Completed | Multilingual Post Management |
17
+ | Phase 3 | ⏳ Pending | Cloudinary Integration |
18
+ | Phase 4 | ✅ Completed | Multi-layer Security & Rate Limiting |
19
+ | Phase 5 | ✅ Completed | API v1 |
20
+ | Phase 6 | ✅ Completed | Admin Dashboard & System Settings |
21
+ | Phase 7 | ⏳ Pending | Audit Log & Soft Delete |
22
+ | Phase 8 | ⏳ Pending | Slideshow Engine |
23
+ | Phase 9 | ⏳ Pending | Multi-layer Caching |
24
+ | Phase 10 | ⏳ Pending | Testing & Health Checks |
25
+
26
+ **Last Updated:** May 13, 2026
27
+
28
+ ---
29
+
30
+ ## Table of Contents
31
+
32
+ 1. [Architectural Overview](#tong-quan)
33
+ 2. [Phase 0: Project Bootstrap & Environment Configuration](#phrase-0)
34
+ 3. [Phase 1: Authentication & Authorization (Devise + JWT)](#phrase-1)
35
+ 4. [Phase 2: Multilingual Post Management](#phrase-2)
36
+ 5. [Phase 3: Cloudinary Integration](#phrase-3)
37
+ 6. [Phase 4: Multi-layer Security & Rate Limiting](#phrase-4)
38
+ 7. [Phase 5: API v1](#phrase-5)
39
+ 8. [Phase 6: Admin Dashboard & System Settings](#phrase-6)
40
+ 9. [Phase 7: Audit Log & Soft Delete](#phrase-7)
41
+ 10. [Phase 8: Slideshow Engine](#phrase-8)
42
+ 11. [Phase 9: Multi-layer Caching](#phrase-9)
43
+ 12. [Phase 10: Testing & Health Checks](#phrase-10)
44
+ 13. [GitHub Actions CI/CD](#ci-cd)
45
+ 14. [Appendix: ERD & Dependency Map](#phu-luc)
46
+
47
+ ---
48
+
49
+ ## 1. Architectural Overview {#tong-quan}
50
+
51
+ ```
52
+ ┌─────────────────────────────────────────────────────────────┐
53
+ │ CLIENT LAYER │
54
+ │ Browser (Hotwire/Turbo/Stimulus) | Vue.js / Mobile App │
55
+ └──────────────────────┬──────────────────────────────────────┘
56
+ │ HTTP / WebSocket
57
+ ┌──────────────────────▼──────────────────────────────────────┐
58
+ │ RAILS 8 APP │
59
+ │ ┌──────────────┐ ┌──────────────┐ ┌───────────────────┐ │
60
+ │ │ Web Routes │ │ API v1 │ │ Admin Namespace │ │
61
+ │ │ /vi /en ... │ │ /api/v1/... │ │ /admin/... │ │
62
+ │ └──────────────┘ └──────────────┘ └───────────────────┘ │
63
+ │ ┌─────────────────────────────────────────────────────────┐│
64
+ │ │ Middleware Stack: Rack::Attack → RateLimiter → Devise ││
65
+ │ └─────────────────────────────────────────────────────────┘│
66
+ └──────────┬─────────────────┬───────────────────┬────────────┘
67
+ │ │ │
68
+ ┌──────▼──────┐ ┌───────▼──────┐ ┌────────▼───────┐
69
+ │ sqlite3 │ │ Redis │ │ Cloudinary │
70
+ │ (Primary) │ │ (Cache/Queue)│ │ (Media CDN) │
71
+ └─────────────┘ └──────────────┘ └────────────────┘
72
+ │
73
+ ┌────────▼───────┐
74
+ │ Sidekiq │
75
+ │ (Background) │
76
+ └────────────────┘
77
+ ```
78
+
79
+ ### Supported Languages
80
+
81
+ | Layer | Language |
82
+ |---|---|
83
+ | **Backend / Admin UI** | English (en), Vietnamese (vi) |
84
+ | **Frontend / Post content** | en, vi, ru, ja, ko, th, de (7 languages) |
85
+
86
+ ### Dependency Order (Build Order)
87
+
88
+ ```
89
+ Phase 0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10
90
+ (Each phase depends on the previous one. Do not skip the order.)
91
+ ```
92
+
93
+ ---
94
+
95
+ ## 2. Phase 0: Project Bootstrap & Environment Configuration {#phrase-0}
96
+
97
+ **Objective:** Build a Rails 8 foundation with all dependencies, DB, Redis, and CI configuration.
98
+
99
+ ### 0.1 Create a new project
100
+
101
+ ```bash
102
+ rails new . --force \
103
+ --database=sqlite3 \
104
+ --asset-pipeline=propshaft \
105
+ --javascript=importmap \
106
+ --skip-test # RSpec will be added later
107
+ cd .
108
+ ```
109
+
110
+ ### 0.2 Gemfile — Add all dependencies from the start
111
+
112
+ ```ruby
113
+ # Gemfile
114
+
115
+ # === AUTH ===
116
+ gem 'devise'
117
+ gem 'devise-jwt'
118
+
119
+ # === AUTHORIZATION ===
120
+ gem 'pundit'
121
+
122
+ # === I18N / MULTILINGUAL DATA ===
123
+ gem 'mobility'
124
+ gem 'mobility-actiontext' # integrates ActionText + Mobility
125
+
126
+ # === MEDIA ===
127
+ gem 'cloudinary'
128
+ gem 'activestorage' # already built into Rails; declared here for clarity
129
+
130
+ # === RICH TEXT ===
131
+ # ActionText is built into Rails 8
132
+
133
+ # === BACKGROUND JOBS ===
134
+ gem 'sidekiq'
135
+ gem 'sidekiq-scheduler' # for Publish Scheduling
136
+
137
+ # === CACHING / RATE LIMIT ===
138
+ gem 'redis'
139
+ gem 'rack-attack'
140
+
141
+ # === SLUG ===
142
+ gem 'friendly_id'
143
+
144
+ # === SOFT DELETE ===
145
+ gem 'discard' # or paranoia
146
+
147
+ # === AUDIT ===
148
+ gem 'paper_trail'
149
+
150
+ # === PAGINATION ===
151
+ gem 'pagy'
152
+
153
+ # === SERIALIZER (API) ===
154
+ gem 'blueprinter' # or fast_jsonapi
155
+
156
+ # === VIEW COMPONENTS ===
157
+ gem 'view_component'
158
+
159
+ # === COUNTER CACHE / UNIQUE VIEWS ===
160
+ gem 'impressionist'
161
+
162
+ group :development, :test do
163
+ gem 'rspec-rails'
164
+ gem 'factory_bot_rails'
165
+ gem 'faker'
166
+ gem 'webmock'
167
+ gem 'simplecov'
168
+ gem 'shoulda-matchers'
169
+ end
170
+
171
+ group :development do
172
+ gem 'letter_opener' # preview email locally
173
+ gem 'annotate'
174
+ gem 'rubocop-rails-omakase', require: false
175
+ gem 'dotenv-rails' # load .env in development/test
176
+ end
177
+ ```
178
+
179
+ ```bash
180
+ bundle install
181
+ ```
182
+
183
+ ### 0.3 Database Configuration
184
+
185
+ ```yaml
186
+ # config/database.yml
187
+ default: &default
188
+ adapter: sqlite3
189
+ pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
190
+ timeout: 5000
191
+
192
+ development:
193
+ <<: *default
194
+ database: storage/rails_8_blog_development.sqlite3
195
+
196
+ test:
197
+ <<: *default
198
+ database: storage/rails_8_blog_test.sqlite3
199
+
200
+ production:
201
+ <<: *default
202
+ database: storage/rails_8_blog_production.sqlite3
203
+ # If you later switch to PostgreSQL, use DATABASE_URL:
204
+ # url: <%= ENV['DATABASE_URL'] %>
205
+ ```
206
+
207
+ > **Note:** SQLite3 does not use `username/password/host`. Those fields are only for PostgreSQL/MySQL. Rails 8 stores the DB file in the `storage/` directory by default.
208
+
209
+ ```bash
210
+ rails db:create
211
+ ```
212
+
213
+ ### 0.4 Redis & Sidekiq Configuration
214
+
215
+ ```ruby
216
+ # config/initializers/sidekiq.rb
217
+ Sidekiq.configure_server do |config|
218
+ config.redis = { url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0') }
219
+ end
220
+
221
+ Sidekiq.configure_client do |config|
222
+ config.redis = { url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0') }
223
+ end
224
+ ```
225
+
226
+ ```ruby
227
+ # config/application.rb — add to the Application class
228
+ config.active_job.queue_adapter = :sidekiq
229
+ config.cache_store = :redis_cache_store, {
230
+ url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/1'),
231
+ namespace: 'blog_cache'
232
+ }
233
+ ```
234
+
235
+ ```yaml
236
+ # config/sidekiq.yml
237
+ :queues:
238
+ - default
239
+ - mailers
240
+ - media
241
+ - critical
242
+ ```
243
+
244
+ ### 0.5 I18n Configuration
245
+
246
+ ```ruby
247
+ # config/application.rb
248
+ config.i18n.available_locales = [:en, :vi, :ru, :ja, :ko, :th, :de]
249
+ config.i18n.default_locale = :en
250
+ config.i18n.fallbacks = true
251
+ ```
252
+
253
+ ```ruby
254
+ # config/initializers/mobility.rb
255
+ Mobility.configure do |config|
256
+ config.plugins do
257
+ backend :table # uses the post_translations table
258
+ active_record
259
+ reader
260
+ writer
261
+ fallbacks({ vi: :en, ru: :en, ja: :en, ko: :en, th: :en, de: :en })
262
+ presence
263
+ cache
264
+ dirty
265
+ column_fallback
266
+ end
267
+ end
268
+ ```
269
+
270
+ ### 0.6 Environment Variables (.env)
271
+
272
+ ```bash
273
+ # .env (used with dotenv-rails in development)
274
+ DATABASE_URL=sqlite3://...
275
+ REDIS_URL=redis://localhost:6379/0
276
+ CLOUDINARY_CLOUD_NAME=your_cloud_name
277
+ CLOUDINARY_API_KEY=your_api_key
278
+ CLOUDINARY_API_SECRET=your_api_secret
279
+ DEVISE_JWT_SECRET_KEY=<rake secret>
280
+ ```
281
+
282
+ ### ✅ Checklist Phase 0
283
+
284
+ - [x] `rails new` successful, server starts successfully
285
+ - [x] `bundle install` runs without errors
286
+ - [x] `rails db:create` creates the database
287
+ - [x] Redis connects successfully (check: `redis-cli ping`)
288
+ - [x] Sidekiq worker runs successfully: `bundle exec sidekiq`
289
+
290
+ ---
291
+
292
+ ## 3. Phase 1: Authentication & Authorization (Devise + JWT) {#phrase-1}
293
+
294
+ **Objective:** A login system with full Devise modules, JWT for API, and 3-role authorization.
295
+
296
+ ### 1.1 Install Devise
297
+
298
+ ```bash
299
+ rails generate devise:install
300
+ rails generate devise User
301
+ ```
302
+
303
+ ### 1.2 User Migration — All Devise modules + custom fields
304
+
305
+ ```ruby
306
+ # db/migrate/XXXXXX_devise_create_users.rb
307
+ class DeviseCreateUsers < ActiveRecord::Migration[8.0]
308
+ def change
309
+ create_table :users do |t|
310
+ ## Core
311
+ t.string :email, null: false, default: ""
312
+ t.string :encrypted_password, null: false, default: ""
313
+ t.string :full_name
314
+ t.string :role, null: false, default: "reader"
315
+
316
+ ## Cloudinary Avatar
317
+ t.string :avatar_public_id
318
+
319
+ ## Recoverable
320
+ t.string :reset_password_token
321
+ t.datetime :reset_password_sent_at
322
+
323
+ ## Rememberable
324
+ t.datetime :remember_created_at
325
+
326
+ ## Trackable
327
+ t.integer :sign_in_count, default: 0, null: false
328
+ t.datetime :current_sign_in_at
329
+ t.datetime :last_sign_in_at
330
+ t.string :current_sign_in_ip
331
+ t.string :last_sign_in_ip
332
+
333
+ ## Confirmable
334
+ t.string :confirmation_token
335
+ t.datetime :confirmed_at
336
+ t.datetime :confirmation_sent_at
337
+ t.string :unconfirmed_email
338
+
339
+ ## Lockable
340
+ t.integer :failed_attempts, default: 0, null: false
341
+ t.string :unlock_token
342
+ t.datetime :locked_at
343
+
344
+ ## JWT
345
+ t.string :jti, null: false
346
+
347
+ t.timestamps null: false
348
+ end
349
+
350
+ add_index :users, :email, unique: true
351
+ add_index :users, :reset_password_token, unique: true
352
+ add_index :users, :confirmation_token, unique: true
353
+ add_index :users, :unlock_token, unique: true
354
+ add_index :users, :jti, unique: true
355
+ end
356
+ end
357
+ ```
358
+
359
+ ### 1.3 JWT Denylist table
360
+
361
+ ```ruby
362
+ # rails generate migration CreateJwtDenylist
363
+ class CreateJwtDenylist < ActiveRecord::Migration[8.0]
364
+ def change
365
+ create_table :jwt_denylist do |t|
366
+ t.string :jti, null: false
367
+ t.datetime :exp, null: false
368
+ end
369
+ add_index :jwt_denylist, :jti
370
+ end
371
+ end
372
+ ```
373
+
374
+ ```ruby
375
+ # app/models/jwt_denylist.rb
376
+ class JwtDenylist < ApplicationRecord
377
+ include Devise::JWT::RevocationStrategies::Denylist
378
+ self.table_name = 'jwt_denylist'
379
+ end
380
+ ```
381
+
382
+ ### 1.4 Model User
383
+
384
+ ```ruby
385
+ # app/models/user.rb
386
+ class User < ApplicationRecord
387
+ include Devise::JWT::RevocationStrategies::JTIMatcher
388
+
389
+ devise :database_authenticatable,
390
+ :registerable,
391
+ :recoverable,
392
+ :rememberable,
393
+ :validatable,
394
+ :confirmable,
395
+ :lockable,
396
+ :timeoutable,
397
+ :trackable,
398
+ :omniauthable, omniauth_providers: [:google_oauth2], # Ready for future OAuth
399
+ :jwt_authenticatable, jwt_revocation_strategy: JwtDenylist
400
+
401
+ ROLES = %w[admin author reader].freeze
402
+
403
+ validates :role, inclusion: { in: ROLES }
404
+ validates :full_name, presence: true, length: { maximum: 100 }
405
+
406
+ # Scopes
407
+ scope :admins, -> { where(role: 'admin') }
408
+ scope :authors, -> { where(role: 'author') }
409
+ scope :readers, -> { where(role: 'reader') }
410
+
411
+ # Role helpers
412
+ def admin?; role == 'admin'; end
413
+ def author?; role == 'author'; end
414
+ def reader?; role == 'reader'; end
415
+
416
+ # Expanded JWT payload
417
+ def jwt_payload
418
+ super.merge('role' => role)
419
+ end
420
+
421
+ # Cloudinary avatar URL
422
+ def avatar_url(size: 200)
423
+ return nil unless avatar_public_id.present?
424
+ Cloudinary::Utils.cloudinary_url(avatar_public_id,
425
+ width: size, height: size, crop: :fill, gravity: :face, fetch_format: :auto)
426
+ end
427
+ end
428
+ ```
429
+
430
+ ### 1.5 Devise Configuration (config/initializers/devise.rb) — Key points
431
+
432
+ ```ruby
433
+ Devise.setup do |config|
434
+ config.mailer_sender = ENV['MAILER_SENDER']
435
+ config.secret_key = ENV['DEVISE_JWT_SECRET_KEY']
436
+
437
+ # Confirmable
438
+ config.allow_unconfirmed_access_for = 24.hours
439
+ config.confirm_within = 24.hours
440
+
441
+ # Lockable — the number of attempts is loaded from the Setting DB (see Phase 6)
442
+ config.maximum_attempts = 5
443
+ config.lock_strategy = :failed_attempts
444
+ config.unlock_strategy = :email
445
+
446
+ # Timeoutable
447
+ config.timeout_in = 30.minutes
448
+
449
+ # JWT
450
+ config.jwt do |jwt|
451
+ jwt.secret = ENV['DEVISE_JWT_SECRET_KEY']
452
+ jwt.dispatch_requests = [
453
+ ['POST', %r{^/api/v1/auth/sign_in$}]
454
+ ]
455
+ jwt.revocation_requests = [
456
+ ['DELETE', %r{^/api/v1/auth/sign_out$}]
457
+ ]
458
+ jwt.expiration_time = 24.hours.to_i
459
+ end
460
+ end
461
+ ```
462
+
463
+ ### 1.6 Pundit — Policies
464
+
465
+ ```ruby
466
+ # app/policies/application_policy.rb
467
+ class ApplicationPolicy
468
+ attr_reader :user, :record
469
+
470
+ def initialize(user, record)
471
+ raise Pundit::NotAuthorizedError, "must be logged in" unless user
472
+ @user = user
473
+ @record = record
474
+ end
475
+
476
+ def index? = false
477
+ def show? = false
478
+ def create? = false
479
+ def update? = false
480
+ def destroy? = false
481
+ end
482
+ ```
483
+
484
+ ```ruby
485
+ # app/policies/post_policy.rb
486
+ class PostPolicy < ApplicationPolicy
487
+ def index? = true
488
+ def show? = true
489
+
490
+ def create? = user.author? || user.admin?
491
+
492
+ def update?
493
+ user.admin? || record.user == user
494
+ end
495
+
496
+ def destroy?
497
+ user.admin? || record.user == user
498
+ end
499
+
500
+ def publish?
501
+ user.admin? || record.user == user
502
+ end
503
+
504
+ class Scope < ApplicationPolicy::Scope
505
+ def resolve
506
+ if user.admin?
507
+ scope.all
508
+ elsif user.author?
509
+ scope.where(user: user).or(scope.published)
510
+ else
511
+ scope.published
512
+ end
513
+ end
514
+ end
515
+ end
516
+ ```
517
+
518
+ ```ruby
519
+ # app/policies/user_policy.rb
520
+ class UserPolicy < ApplicationPolicy
521
+ def index? = user.admin?
522
+ def show? = user.admin? || record == user
523
+ def update? = user.admin? || record == user
524
+ def destroy? = user.admin?
525
+ end
526
+ ```
527
+
528
+ ### 1.7 ApplicationController
529
+
530
+ ```ruby
531
+ # app/controllers/application_controller.rb
532
+ class ApplicationController < ActionController::Base
533
+ include Pundit::Authorization
534
+
535
+ before_action :set_locale
536
+ before_action :authenticate_user!, except: [:home, :show]
537
+
538
+ rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
539
+
540
+ private
541
+
542
+ def set_locale
543
+ locale = params[:locale] || session[:locale] || I18n.default_locale
544
+ I18n.locale = I18n.available_locales.include?(locale.to_sym) ? locale : I18n.default_locale
545
+ end
546
+
547
+ def user_not_authorized
548
+ flash[:alert] = t('errors.not_authorized')
549
+ redirect_back(fallback_location: root_path)
550
+ end
551
+ end
552
+ ```
553
+
554
+ ### ✅ Checklist Phase 1
555
+
556
+ - [x] `rails db:migrate` successful
557
+ - [x] Registration / login / logout work (web form)
558
+ - [x] Account confirmation email sends successfully (using local letter_opener)
559
+ - [x] Account is locked after 5 wrong password attempts
560
+ - [x] JWT token is returned when POST `/api/v1/auth/sign_in`
561
+ - [x] JWT token is added to the denylist when DELETE `/api/v1/auth/sign_out`
562
+ - [x] Pundit raises `NotAuthorizedError` when a reader tries to access an admin action
563
+
564
+ ---
565
+
566
+ ## 4. Phase 2: Multilingual Post Management {#phrase-2}
567
+
568
+ **Objective:** Post model with 7 languages, a separate slug for each language, status workflow, and multilingual ActionText.
569
+
570
+ ### 2.1 Migrations
571
+
572
+ ```bash
573
+ rails generate migration CreateCategories name:string slug:string
574
+ rails generate migration CreateTags name:string slug:string
575
+ rails generate migration CreatePosts
576
+ rails generate migration CreatePostTranslations
577
+ rails generate migration CreatePostTags post:references tag:references
578
+ rails generate migration CreateComments body:text discarded_at:datetime:index user:references post:references
579
+ rails generate migration CreateReactions kind:string user:references post:references
580
+ ```
581
+
582
+ ### 2.1b Models Category & Tag
583
+
584
+ ```ruby
585
+ # app/models/category.rb
586
+ class Category < ApplicationRecord
587
+ extend FriendlyId
588
+ friendly_id :name, use: :slugged
589
+
590
+ has_many :posts, dependent: :restrict_with_error
591
+
592
+ validates :name, presence: true, uniqueness: true
593
+ validates :slug, presence: true, uniqueness: true
594
+
595
+ before_validation :generate_slug, if: -> { slug.blank? && name.present? }
596
+
597
+ private
598
+
599
+ def generate_slug
600
+ self.slug = name.parameterize
601
+ end
602
+ end
603
+ ```
604
+
605
+ ```ruby
606
+ # app/models/tag.rb
607
+ class Tag < ApplicationRecord
608
+ extend FriendlyId
609
+ friendly_id :name, use: :slugged
610
+
611
+ has_many :post_tags, dependent: :destroy
612
+ has_many :posts, through: :post_tags
613
+
614
+ validates :name, presence: true, uniqueness: true
615
+ validates :slug, presence: true, uniqueness: true
616
+
617
+ before_validation :generate_slug, if: -> { slug.blank? && name.present? }
618
+
619
+ private
620
+
621
+ def generate_slug
622
+ self.slug = name.parameterize
623
+ end
624
+ end
625
+ ```
626
+
627
+ ```ruby
628
+ # db/migrate/XXXXXX_create_posts.rb
629
+ class CreatePosts < ActiveRecord::Migration[8.0]
630
+ def change
631
+ create_table :posts do |t|
632
+ t.references :user, null: false, foreign_key: true
633
+ t.references :category, null: false, foreign_key: true
634
+ t.string :cloudinary_public_id # thumbnail
635
+ t.string :status, null: false, default: 'draft'
636
+ t.integer :comments_count, default: 0 # counter cache
637
+ t.integer :impressions_count, default: 0 # unique views
638
+ t.datetime :published_at
639
+ t.datetime :scheduled_at
640
+
641
+ t.timestamps
642
+ end
643
+ add_index :posts, :status
644
+ add_index :posts, :published_at
645
+ end
646
+ end
647
+ ```
648
+
649
+ ```ruby
650
+ # db/migrate/XXXXXX_create_post_translations.rb
651
+ # (Mobility generates this automatically when using the migration generator, but the structure below is the desired one)
652
+ class CreatePostTranslations < ActiveRecord::Migration[8.0]
653
+ def change
654
+ create_table :post_translations do |t|
655
+ t.references :post, null: false, foreign_key: true
656
+ t.string :locale, null: false
657
+ t.string :title
658
+ t.string :slug
659
+
660
+ t.timestamps
661
+ end
662
+ add_index :post_translations, [:post_id, :locale], unique: true
663
+ add_index :post_translations, :slug
664
+ end
665
+ end
666
+ ```
667
+
668
+ ### 2.2 Model Post
669
+
670
+ ```ruby
671
+ # app/models/post.rb
672
+ class Post < ApplicationRecord
673
+ # --- Associations ---
674
+ belongs_to :user
675
+ belongs_to :category
676
+ has_many :post_tags, dependent: :destroy
677
+ has_many :tags, through: :post_tags
678
+ has_many :comments, dependent: :destroy
679
+ has_many :reactions, dependent: :destroy
680
+ has_many :slideshow_assets, dependent: :destroy, -> { order(:position) }
681
+
682
+ # --- ActionText (multilingual via different field names) ---
683
+ has_rich_text :content_en
684
+ has_rich_text :content_vi
685
+ has_rich_text :content_ru
686
+ has_rich_text :content_ja
687
+ has_rich_text :content_ko
688
+ has_rich_text :content_th
689
+ has_rich_text :content_de
690
+
691
+ # --- Mobility (translate title + slug) ---
692
+ extend Mobility
693
+ translates :title, :slug, backend: :table
694
+
695
+ # --- FriendlyId (generate slug from title) ---
696
+ extend FriendlyId
697
+ friendly_id :title, use: [:mobility, :history]
698
+
699
+ # --- Impressionist (unique views) ---
700
+ is_impressionable counter_cache: true, column_name: :impressions_count,
701
+ unique: :ip_address
702
+
703
+ # --- Discard (soft delete) ---
704
+ include Discard::Model
705
+
706
+ # --- Enums ---
707
+ STATUSES = %w[draft pending scheduled published].freeze
708
+ validates :status, inclusion: { in: STATUSES }
709
+
710
+ # --- Scopes ---
711
+ scope :published, -> { where(status: 'published').where('published_at <= ?', Time.current) }
712
+ scope :scheduled, -> { where(status: 'scheduled').where('scheduled_at > ?', Time.current) }
713
+ scope :by_locale, ->(locale) { joins(:post_translations).where(post_translations: { locale: locale }) }
714
+
715
+ # --- Validations ---
716
+ validates :status, presence: true
717
+ validate :scheduled_at_must_be_future, if: :scheduled?
718
+
719
+ # --- Callbacks ---
720
+ after_save :schedule_publish_job, if: :saved_change_to_scheduled_at?
721
+ after_update :rename_cloudinary_assets_job, if: :saved_change_to_slug?
722
+
723
+ # --- Helpers ---
724
+ def content_for(locale)
725
+ send(:"content_#{locale}")
726
+ end
727
+
728
+ def thumbnail_url(**options)
729
+ return nil unless cloudinary_public_id.present?
730
+ Cloudinary::Utils.cloudinary_url(cloudinary_public_id,
731
+ { fetch_format: :auto, quality: :auto }.merge(options))
732
+ end
733
+
734
+ def scheduled?
735
+ status == 'scheduled'
736
+ end
737
+
738
+ def published?
739
+ status == 'published'
740
+ end
741
+
742
+ private
743
+
744
+ def scheduled_at_must_be_future
745
+ errors.add(:scheduled_at, :must_be_future) if scheduled_at.present? && scheduled_at <= Time.current
746
+ end
747
+
748
+ def schedule_publish_job
749
+ PublishPostJob.set(wait_until: scheduled_at).perform_later(id) if scheduled?
750
+ end
751
+
752
+ def rename_cloudinary_assets_job
753
+ RenameCloudinaryAssetsJob.perform_later(id)
754
+ end
755
+ end
756
+ ```
757
+
758
+ ### 2.3 Sidekiq Jobs for Workflow
759
+
760
+ ```ruby
761
+ # app/jobs/publish_post_job.rb
762
+ class PublishPostJob < ApplicationJob
763
+ queue_as :default
764
+
765
+ def perform(post_id)
766
+ post = Post.find_by(id: post_id)
767
+ return unless post&.scheduled?
768
+ return if post.scheduled_at > Time.current
769
+
770
+ post.update!(status: 'published', published_at: Time.current)
771
+ Rails.logger.info "Post ##{post_id} published at #{Time.current}"
772
+ end
773
+ end
774
+ ```
775
+
776
+ ```ruby
777
+ # app/jobs/rename_cloudinary_assets_job.rb
778
+ class RenameCloudinaryAssetsJob < ApplicationJob
779
+ queue_as :media
780
+
781
+ def perform(post_id)
782
+ post = Post.find_by(id: post_id)
783
+ return unless post
784
+
785
+ # 1. Rename the thumbnail on Cloudinary (if needed)
786
+ # 2. Scan ActionTextRichText to replace old URLs → new ones
787
+ I18n.available_locales.each do |locale|
788
+ rich_text = ActionText::RichText.find_by(
789
+ record_type: 'Post', record_id: post_id, name: "content_#{locale}"
790
+ )
791
+ next unless rich_text
792
+
793
+ # Replace all old image URLs with the new URL
794
+ # (The specific logic depends on the naming convention)
795
+ updated_body = rich_text.body.to_s.gsub(/old_public_id_pattern/, 'new_public_id')
796
+ rich_text.update!(body: updated_body) if updated_body != rich_text.body.to_s
797
+ end
798
+ end
799
+ end
800
+ ```
801
+
802
+ ### 2.4 Routes for multilingual frontend
803
+
804
+ ```ruby
805
+ # config/routes.rb
806
+ Rails.application.routes.draw do
807
+ # Locale scope for the web frontend (7 languages)
808
+ scope '/:locale', locale: /en|vi|ru|ja|ko|th|de/ do
809
+ resources :posts, param: :slug, only: [:index, :show]
810
+ resources :categories, param: :slug, only: [:index, :show]
811
+ resources :tags, param: :slug, only: [:index, :show]
812
+ end
813
+
814
+ # Admin namespace (en + vi only)
815
+ namespace :admin do
816
+ resources :posts do
817
+ member do
818
+ patch :publish
819
+ patch :schedule
820
+ end
821
+ end
822
+ resources :users
823
+ resources :categories
824
+ resources :tags
825
+ resource :settings, only: [:show, :update]
826
+ resources :audit_logs, only: [:index, :show]
827
+ end
828
+
829
+ # Devise routes
830
+ devise_for :users, path: 'auth', controllers: {
831
+ sessions: 'users/sessions',
832
+ registrations: 'users/registrations',
833
+ confirmations: 'users/confirmations',
834
+ passwords: 'users/passwords'
835
+ }
836
+
837
+ # API
838
+ namespace :api do
839
+ namespace :v1 do
840
+ # ... (see Phase 5)
841
+ end
842
+ end
843
+
844
+ root to: 'posts#index'
845
+ end
846
+ ```
847
+
848
+ ### 2.5 Admin UI — Language Tabs with Stimulus
849
+
850
+ ```javascript
851
+ // app/javascript/controllers/language_tabs_controller.js
852
+ import { Controller } from "@hotwired/stimulus"
853
+
854
+ export default class extends Controller {
855
+ static targets = ["tab", "panel"]
856
+ static values = { active: { type: String, default: "en" } }
857
+
858
+ connect() {
859
+ this.activate(this.activeValue)
860
+ }
861
+
862
+ switch(event) {
863
+ const locale = event.currentTarget.dataset.locale
864
+ this.activeValue = locale
865
+ this.activate(locale)
866
+ }
867
+
868
+ activate(locale) {
869
+ this.tabTargets.forEach(tab => {
870
+ tab.classList.toggle("active", tab.dataset.locale === locale)
871
+ })
872
+ this.panelTargets.forEach(panel => {
873
+ panel.hidden = panel.dataset.locale !== locale
874
+ })
875
+ }
876
+ }
877
+ ```
878
+
879
+ ```erb
880
+ <%# app/views/admin/posts/_language_tabs.html.erb %>
881
+ <div data-controller="language-tabs">
882
+ <div class="tab-list" role="tablist">
883
+ <% I18n.available_locales.each do |locale| %>
884
+ <button
885
+ data-language-tabs-target="tab"
886
+ data-locale="<%= locale %>"
887
+ data-action="click->language-tabs#switch"
888
+ role="tab"
889
+ class="tab-btn">
890
+ <%= t("locales.#{locale}") %>
891
+ </button>
892
+ <% end %>
893
+ </div>
894
+
895
+ <% I18n.available_locales.each do |locale| %>
896
+ <div data-language-tabs-target="panel" data-locale="<%= locale %>" hidden>
897
+ <%= f.text_field :title, data: { locale: locale },
898
+ placeholder: t('admin.posts.title_placeholder', locale: locale) %>
899
+ <%= render 'trix_editor', f: f, locale: locale %>
900
+ </div>
901
+ <% end %>
902
+ </div>
903
+ ```
904
+
905
+ ### ✅ Checklist Phase 2
906
+
907
+ - [x] Create posts with titles in 7 languages (via Language Tabs)
908
+ - [x] Slug is generated automatically from the title, unique per locale
909
+ - [x] URLs `/en/posts/hello-world` and `/vi/posts/xin-chao` both work
910
+ - [x] Full 4-step workflow: **Draft → Pending → Scheduled → Published**
911
+ - `draft`: Author is drafting, not submitted yet
912
+ - `pending`: Submitted, awaiting Admin approval
913
+ - `scheduled`: Approved by Admin, scheduled for publishing
914
+ - `published`: Publicly published
915
+ - [x] `PublishPostJob` runs at the scheduled time
916
+ - [x] Posts display in the correct language based on the URL locale
917
+ - [x] Author sees only their own posts, Admin sees everything
918
+
919
+ ---
920
+
921
+ ## 5. Phase 3: Cloudinary Integration {#phrase-3}
922
+
923
+ **Objective:** Direct upload, Media Library SDK, folder organization, and automatic transformations.
924
+
925
+ ### 3.1 Cloudinary Configuration
926
+
927
+ ```ruby
928
+ # config/initializers/cloudinary.rb
929
+ Cloudinary.config do |config|
930
+ config.cloud_name = ENV['CLOUDINARY_CLOUD_NAME']
931
+ config.api_key = ENV['CLOUDINARY_API_KEY']
932
+ config.api_secret = ENV['CLOUDINARY_API_SECRET']
933
+ config.secure = true
934
+ end
935
+ ```
936
+
937
+ ```ruby
938
+ # config/storage.yml
939
+ cloudinary:
940
+ service: Cloudinary
941
+ ```
942
+
943
+ ```ruby
944
+ # config/environments/production.rb
945
+ config.active_storage.service = :cloudinary
946
+ ```
947
+
948
+ ### 3.2 Controller to create an Upload Signature (Direct Signed Upload)
949
+
950
+ ```ruby
951
+ # app/controllers/uploads_controller.rb
952
+ class UploadsController < ApplicationController
953
+ before_action :authenticate_user!
954
+
955
+ # GET /uploads/signature?folder=thumb/2025-01&public_id=hello-world
956
+ def signature
957
+ folder = params.require(:folder)
958
+ public_id = params[:public_id]
959
+
960
+ timestamp = Time.now.to_i
961
+ params_to_sign = {
962
+ timestamp: timestamp,
963
+ folder: folder,
964
+ public_id: public_id
965
+ }.compact
966
+
967
+ signature = Cloudinary::Utils.api_sign_request(params_to_sign, ENV['CLOUDINARY_API_SECRET'])
968
+
969
+ render json: {
970
+ signature: signature,
971
+ timestamp: timestamp,
972
+ api_key: ENV['CLOUDINARY_API_KEY'],
973
+ cloud_name: ENV['CLOUDINARY_CLOUD_NAME'],
974
+ folder: folder,
975
+ public_id: public_id
976
+ }
977
+ end
978
+ end
979
+ ```
980
+ Need to add the Cloudinary Media Widget script to the admin layout and a Stimulus controller to trigger the widget, then map the returned public_id back into the form.
981
+
982
+ ### 3.3 Stimulus Controller — Direct Upload
983
+
984
+ ```javascript
985
+ // app/javascript/controllers/cloudinary_upload_controller.js
986
+ import { Controller } from "@hotwired/stimulus"
987
+
988
+ export default class extends Controller {
989
+ static targets = ["input", "preview", "publicIdField", "progress"]
990
+ static values = { folder: String, publicId: String }
991
+
992
+ async upload(event) {
993
+ const file = event.target.files[0]
994
+ if (!file) return
995
+
996
+ // 1. Get the signature from the Rails server
997
+ const sigRes = await fetch(`/uploads/signature?folder=${this.folderValue}&public_id=${this.publicIdValue}`)
998
+ const sig = await sigRes.json()
999
+
1000
+ // 2. Upload directly to Cloudinary
1001
+ const formData = new FormData()
1002
+ formData.append('file', file)
1003
+ formData.append('api_key', sig.api_key)
1004
+ formData.append('timestamp', sig.timestamp)
1005
+ formData.append('signature', sig.signature)
1006
+ formData.append('folder', sig.folder)
1007
+ if (sig.public_id) formData.append('public_id', sig.public_id)
1008
+
1009
+ const uploadRes = await fetch(
1010
+ `https://api.cloudinary.com/v1_1/${sig.cloud_name}/image/upload`,
1011
+ { method: 'POST', body: formData }
1012
+ )
1013
+
1014
+ const result = await uploadRes.json()
1015
+
1016
+ // 3. Send the public_id back to Rails to store in the DB
1017
+ this.publicIdFieldTarget.value = result.public_id
1018
+ this.previewTarget.src = result.secure_url
1019
+ this.previewTarget.hidden = false
1020
+ }
1021
+ }
1022
+ ```
1023
+
1024
+ ### 3.4 Cloudinary Media Library SDK (Choose images from the library)
1025
+
1026
+ > Allows Admin to open a popup and choose images already uploaded to Cloudinary instead of uploading again.
1027
+
1028
+ ```erb
1029
+ <%# app/views/layouts/admin.html.erb — add to <head> %>
1030
+ <script src="https://media-library.cloudinary.com/global/all.js" type="text/javascript"></script>
1031
+ ```
1032
+
1033
+ ```javascript
1034
+ // app/javascript/controllers/cloudinary_media_library_controller.js
1035
+ import { Controller } from "@hotwired/stimulus"
1036
+
1037
+ export default class extends Controller {
1038
+ static targets = ["publicIdField", "preview"]
1039
+ static values = { cloudName: String, apiKey: String }
1040
+
1041
+ open() {
1042
+ const widget = cloudinary.createMediaLibrary(
1043
+ {
1044
+ cloud_name: this.cloudNameValue,
1045
+ api_key: this.apiKeyValue,
1046
+ multiple: false,
1047
+ max_files: 1
1048
+ },
1049
+ {
1050
+ insertHandler: (data) => {
1051
+ const asset = data.assets[0]
1052
+ this.publicIdFieldTarget.value = asset.public_id
1053
+ this.previewTarget.src = asset.secure_url
1054
+ this.previewTarget.hidden = false
1055
+ }
1056
+ }
1057
+ )
1058
+ widget.show()
1059
+ }
1060
+ }
1061
+ ```
1062
+
1063
+ ```erb
1064
+ <%# Use in the Admin form %>
1065
+ <div data-controller="cloudinary-media-library"
1066
+ data-cloudinary-media-library-cloud-name-value="<%= ENV['CLOUDINARY_CLOUD_NAME'] %>"
1067
+ data-cloudinary-media-library-api-key-value="<%= ENV['CLOUDINARY_API_KEY'] %>">
1068
+
1069
+ <%= f.hidden_field :cloudinary_public_id,
1070
+ data: { cloudinary_media_library_target: 'publicIdField' } %>
1071
+
1072
+ <img data-cloudinary-media-library-target="preview"
1073
+ src="" alt="Preview" hidden style="max-width:300px" />
1074
+
1075
+ <button type="button"
1076
+ data-action="click->cloudinary-media-library#open"
1077
+ class="btn btn-secondary">
1078
+ 📷 Choose from Media Library
1079
+ </button>
1080
+ </div>
1081
+ ```
1082
+
1083
+ ### 3.6 Helper — Cloudinary Transformation URLs
1084
+
1085
+ ```ruby
1086
+ # app/helpers/cloudinary_helper.rb
1087
+ module CloudinaryHelper
1088
+ # Thumbnail for posts (f_auto + q_auto)
1089
+ def post_thumbnail_url(public_id, width: 800, height: 450)
1090
+ return '' unless public_id.present?
1091
+ Cloudinary::Utils.cloudinary_url(public_id,
1092
+ width: width, height: height, crop: :fill,
1093
+ fetch_format: :auto, quality: :auto)
1094
+ end
1095
+
1096
+ # Avatar user (face crop + round)
1097
+ def user_avatar_url(public_id, size: 80)
1098
+ return '' unless public_id.present?
1099
+ Cloudinary::Utils.cloudinary_url(public_id,
1100
+ width: size, height: size,
1101
+ crop: :fill, gravity: :face,
1102
+ fetch_format: :auto, quality: :auto,
1103
+ radius: :max)
1104
+ end
1105
+
1106
+ # Gallery image in the slideshow
1107
+ def slideshow_url(public_id, width: 1200)
1108
+ return '' unless public_id.present?
1109
+ Cloudinary::Utils.cloudinary_url(public_id,
1110
+ width: width, crop: :limit,
1111
+ fetch_format: :auto, quality: :auto)
1112
+ end
1113
+
1114
+ # Folder convention for thumbnails
1115
+ def thumbnail_folder(post)
1116
+ "thumb/#{Date.today.strftime('%Y-%m')}/#{post.id}"
1117
+ end
1118
+
1119
+ # Folder convention for gallery
1120
+ def gallery_folder(post)
1121
+ "gallery/#{Date.today.strftime('%Y-%m')}/#{post.id}"
1122
+ end
1123
+ end
1124
+ ```
1125
+
1126
+ ### 3.7 Sidekiq Job — Clean up orphaned images
1127
+
1128
+ ```ruby
1129
+ # app/jobs/cloudinary_housekeeping_job.rb
1130
+ class CloudinaryHousekeepingJob < ApplicationJob
1131
+ queue_as :media
1132
+
1133
+ def perform
1134
+ used_ids = Post.pluck(:cloudinary_public_id).compact
1135
+ used_ids += SlideshowAsset.pluck(:cloudinary_public_id).compact
1136
+ used_ids += User.pluck(:avatar_public_id).compact
1137
+
1138
+ # Fetch all images in the app folder from Cloudinary
1139
+ result = Cloudinary::Api.resources(type: :upload, prefix: 'thumb/', max_results: 500)
1140
+ result['resources'].each do |resource|
1141
+ unless used_ids.include?(resource['public_id'])
1142
+ Cloudinary::Api.delete_resources([resource['public_id']])
1143
+ Rails.logger.info "Deleted orphan: #{resource['public_id']}"
1144
+ end
1145
+ end
1146
+ end
1147
+ end
1148
+ ```
1149
+
1150
+ ```yaml
1151
+ # config/sidekiq.yml — add schedule
1152
+ :schedule:
1153
+ cloudinary_housekeeping:
1154
+ cron: "0 3 * * 0" # Runs at 3AM every Sunday
1155
+ class: CloudinaryHousekeepingJob
1156
+ ```
1157
+
1158
+ ### ✅ Checklist Phase 3
1159
+
1160
+ - [ ] Images upload without going through the Rails server (check that server RAM does not increase during upload)
1161
+ - [ ] `public_id` is saved in the DB after a successful upload
1162
+ - [ ] Image URLs automatically return WebP on Chrome
1163
+ - [ ] Thumbnail shows the correct `f_auto,q_auto`
1164
+ - [ ] Cloudinary Media Library popup opens in Admin, select image → `public_id` is filled into the form
1165
+ - [ ] `RenameCloudinaryAssetsJob` replaces URLs in ActionText when the slug changes
1166
+ - [ ] `CloudinaryHousekeepingJob` runs and deletes orphaned images
1167
+
1168
+ ---
1169
+
1170
+ ## 6. Phase 4: Multi-layer Security & Rate Limiting {#phrase-4}
1171
+
1172
+ **Objective:** Rack::Attack + Rails 8 RateLimiting + IP Whitelist/Blacklist, all dynamically configured through Settings.
1173
+
1174
+ ### 4.1 Rack::Attack
1175
+
1176
+ ```ruby
1177
+ # config/initializers/rack_attack.rb
1178
+ class Rack::Attack
1179
+ # Helper: Get limits from the Setting DB (Redis cache)
1180
+ def self.setting(key, default)
1181
+ Rails.cache.fetch("setting:#{key}", expires_in: 5.minutes) do
1182
+ Setting.find_by(key: key)&.value || default
1183
+ end
1184
+ end
1185
+
1186
+ ### Layer 0: Throttle brute-force login
1187
+ throttle('login/ip', limit: -> { setting('rack_login_limit', 5) },
1188
+ period: -> { setting('rack_login_period', 60).seconds }) do |req|
1189
+ req.ip if req.path == '/auth/sign_in' && req.post?
1190
+ end
1191
+
1192
+ throttle('login/email', limit: -> { setting('rack_login_limit', 5) },
1193
+ period: -> { setting('rack_login_period', 60).seconds }) do |req|
1194
+ if req.path == '/auth/sign_in' && req.post?
1195
+ req.params.dig('user', 'email')&.downcase&.gsub(/\s+/, '')
1196
+ end
1197
+ end
1198
+
1199
+ ### IP Blacklist (from the Setting DB)
1200
+ blocklist('blocked_ips') do |req|
1201
+ blocked = Rails.cache.fetch('blocked_ips', expires_in: 5.minutes) do
1202
+ Setting.find_by(key: 'blocked_ips')&.value || []
1203
+ end
1204
+ blocked.include?(req.ip)
1205
+ end
1206
+
1207
+ ### IP Whitelist (bypass all throttling)
1208
+ safelist('whitelist_ips') do |req|
1209
+ allowed = Rails.cache.fetch('whitelist_ips', expires_in: 5.minutes) do
1210
+ Setting.find_by(key: 'whitelist_ips')&.value || []
1211
+ end
1212
+ allowed.include?(req.ip)
1213
+ end
1214
+
1215
+ ### Callback when blocked
1216
+ self.throttled_responder = lambda do |env|
1217
+ req = Rack::Request.new(env)
1218
+ # Log and notify Admin
1219
+ BlockedRequestLog.create!(ip: req.ip, path: req.path, reason: 'throttled')
1220
+ AdminNotificationJob.perform_later("IP #{req.ip} was throttled on #{req.path}")
1221
+
1222
+ [429, { 'Content-Type' => 'application/json' },
1223
+ [{ error: 'Too Many Requests', retry_after: 60 }.to_json]]
1224
+ end
1225
+ end
1226
+ ```
1227
+
1228
+ ### 4.4 BlockedRequestLog — Model & Migration
1229
+
1230
+ > **Important note:** This model must be created *before* writing `rack_attack.rb` because the initializer will call `BlockedRequestLog.create!`.
1231
+
1232
+ ```bash
1233
+ rails generate migration CreateBlockedRequestLogs ip:string path:string reason:string user_agent:string
1234
+ ```
1235
+
1236
+ ```ruby
1237
+ # app/models/blocked_request_log.rb
1238
+ class BlockedRequestLog < ApplicationRecord
1239
+ validates :ip, presence: true
1240
+ validates :reason, presence: true
1241
+
1242
+ scope :recent, -> { order(created_at: :desc) }
1243
+ scope :by_ip, ->(ip) { where(ip: ip) }
1244
+ end
1245
+ ```
1246
+
1247
+ ### 4.5 AdminNotificationJob
1248
+
1249
+ ```ruby
1250
+ # app/jobs/admin_notification_job.rb
1251
+ class AdminNotificationJob < ApplicationJob
1252
+ queue_as :critical
1253
+
1254
+ def perform(message)
1255
+ admin_emails = User.admins.pluck(:email)
1256
+ return if admin_emails.empty?
1257
+
1258
+ admin_emails.each do |email|
1259
+ AdminMailer.security_alert(email, message).deliver_later
1260
+ end
1261
+
1262
+ Rails.logger.warn "[SECURITY ALERT] #{message}"
1263
+ end
1264
+ end
1265
+ ```
1266
+
1267
+ ```ruby
1268
+ # app/mailers/admin_mailer.rb
1269
+ class AdminMailer < ApplicationMailer
1270
+ def security_alert(email, message)
1271
+ @message = message
1272
+ mail(to: email, subject: "[Security Alert] #{message.truncate(60)}")
1273
+ end
1274
+ end
1275
+ ```
1276
+
1277
+ ```ruby
1278
+ # app/controllers/comments_controller.rb
1279
+ class CommentsController < ApplicationController
1280
+ # Layer 1: Limit behavior per specific user
1281
+ rate_limit to: 10, within: 1.minute,
1282
+ by: -> { current_user&.id || request.ip },
1283
+ with: -> {
1284
+ flash[:alert] = I18n.t('errors.rate_limited')
1285
+ redirect_back fallback_location: root_path
1286
+ },
1287
+ only: :create
1288
+
1289
+ def create
1290
+ # ...
1291
+ end
1292
+ end
1293
+ ```
1294
+
1295
+ ```ruby
1296
+ # app/controllers/reactions_controller.rb
1297
+ class ReactionsController < ApplicationController
1298
+ rate_limit to: 30, within: 1.minute,
1299
+ by: -> { current_user&.id || request.ip },
1300
+ only: [:create, :destroy]
1301
+ end
1302
+ ```
1303
+
1304
+ ### 4.3 Maintenance Mode Middleware
1305
+
1306
+ ```ruby
1307
+ # app/middleware/maintenance_mode.rb
1308
+ class MaintenanceMode
1309
+ def initialize(app)
1310
+ @app = app
1311
+ end
1312
+
1313
+ def call(env)
1314
+ req = Rack::Request.new(env)
1315
+
1316
+ # Check maintenance mode from cache (avoid a DB query on every request)
1317
+ maintenance = Rails.cache.fetch('setting:maintenance_mode', expires_in: 1.minute) do
1318
+ Setting.find_by(key: 'maintenance_mode')&.value == true
1319
+ end
1320
+
1321
+ if maintenance
1322
+ # Admin paths are bypassed
1323
+ return @app.call(env) if req.path.start_with?('/admin', '/auth')
1324
+
1325
+ locale = req.path.split('/')[1] || 'en'
1326
+ message = I18n.t('maintenance.message', locale: locale)
1327
+ [503, { 'Content-Type' => 'text/html; charset=utf-8' },
1328
+ [maintenance_html(message)]]
1329
+ else
1330
+ @app.call(env)
1331
+ end
1332
+ end
1333
+
1334
+ private
1335
+
1336
+ def maintenance_html(message)
1337
+ "<html><body style='text-align:center;padding:100px;font-family:sans-serif'>
1338
+ <h1>🔧 Maintenance</h1><p>#{CGI.escapeHTML(message)}</p>
1339
+ </body></html>"
1340
+ end
1341
+ end
1342
+ ```
1343
+
1344
+ ```ruby
1345
+ # config/application.rb
1346
+ config.middleware.insert_before ActionDispatch::Static, MaintenanceMode
1347
+ ```
1348
+
1349
+ ### ✅ Checklist Phase 4
1350
+
1351
+ - [x] Wrong password 5 times → HTTP 429 returned
1352
+ - [x] IP in the `blocked_ips` setting → blocked immediately
1353
+ - [x] IP in the `whitelist_ips` setting → not throttled even with many requests
1354
+ - [x] More than 10 comments per minute → flash message, redirect
1355
+ - [x] Set `maintenance_mode = true` → users see 503, admins can still enter
1356
+ - [x] `BlockedRequestLog` records the blocked IPs correctly (check in `/admin/audit_logs` or Rails console)
1357
+ - [x] `AdminNotificationJob` is enqueued when an IP is throttled
1358
+
1359
+ ---
1360
+
1361
+ ## 7. Phase 5: API v1 {#phrase-5}
1362
+
1363
+ **Objective:** RESTful JSON API with JWT auth, locale-aware responses, and Blueprinter serializers.
1364
+
1365
+ ### 5.1 Base API Controller
1366
+
1367
+ ```ruby
1368
+ # app/controllers/api/v1/base_controller.rb
1369
+ module Api
1370
+ module V1
1371
+ class BaseController < ActionController::API
1372
+ include Pundit::Authorization
1373
+ include Pagy::Method
1374
+
1375
+ before_action :authenticate_user_from_token!
1376
+ before_action :set_locale
1377
+
1378
+ rescue_from Pundit::NotAuthorizedError do
1379
+ render json: { error: 'Forbidden' }, status: :forbidden
1380
+ end
1381
+
1382
+ rescue_from ActiveRecord::RecordNotFound do
1383
+ render json: { error: 'Not Found' }, status: :not_found
1384
+ end
1385
+
1386
+ rescue_from ActiveRecord::RecordInvalid do |e|
1387
+ render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
1388
+ end
1389
+
1390
+ private
1391
+
1392
+ def authenticate_user_from_token!
1393
+ # devise-jwt is handled automatically through warden
1394
+ unless current_user
1395
+ render json: { error: 'Unauthorized' }, status: :unauthorized
1396
+ end
1397
+ end
1398
+
1399
+ def set_locale
1400
+ locale = request.headers['Accept-Language'] || params[:locale] || 'en'
1401
+ I18n.locale = I18n.available_locales.include?(locale.to_sym) ? locale : :en
1402
+ end
1403
+ end
1404
+ end
1405
+ end
1406
+ ```
1407
+
1408
+ ### 5.2 API Routes
1409
+
1410
+ ```ruby
1411
+ # config/routes.rb (API section)
1412
+ namespace :api do
1413
+ namespace :v1 do
1414
+ # Auth
1415
+ devise_for :users, path: 'auth',
1416
+ controllers: { sessions: 'api/v1/auth/sessions' },
1417
+ defaults: { format: :json }
1418
+
1419
+ # Resources
1420
+ resources :posts, param: :slug, only: [:index, :show] do
1421
+ resources :comments, only: [:index, :create]
1422
+ resources :reactions, only: [:create, :destroy]
1423
+ end
1424
+ resources :categories, only: [:index, :show]
1425
+ resources :tags, only: [:index, :show]
1426
+
1427
+ # User profile
1428
+ resource :profile, only: [:show, :update]
1429
+
1430
+ # Health check
1431
+ get '/health', to: 'health#show'
1432
+ end
1433
+ end
1434
+ ```
1435
+
1436
+ ### 5.3 Blueprinter Serializers
1437
+
1438
+ ```ruby
1439
+ # app/blueprints/post_blueprint.rb
1440
+ class PostBlueprint < Blueprinter::Base
1441
+ identifier :id
1442
+
1443
+ view :default do
1444
+ fields :status, :published_at, :impressions_count, :comments_count
1445
+ field :title { |post| post.title } # Mobility: automatically uses I18n.locale
1446
+ field :slug { |post| post.slug }
1447
+ field :thumbnail_url do |post|
1448
+ post.thumbnail_url(width: 800, height: 450)
1449
+ end
1450
+ association :category, blueprint: CategoryBlueprint
1451
+ association :tags, blueprint: TagBlueprint
1452
+ association :user, blueprint: UserBlueprint, view: :compact
1453
+ end
1454
+
1455
+ view :detail do
1456
+ include_view :default
1457
+ field :content do |post|
1458
+ post.content_for(I18n.locale).to_s
1459
+ end
1460
+ association :slideshow_assets, blueprint: SlideshowAssetBlueprint
1461
+ end
1462
+ end
1463
+ ```
1464
+
1465
+ ```ruby
1466
+ # app/controllers/api/v1/posts_controller.rb
1467
+ module Api
1468
+ module V1
1469
+ class PostsController < BaseController
1470
+ skip_before_action :authenticate_user_from_token!, only: [:index, :show]
1471
+
1472
+ def index
1473
+ posts = policy_scope(Post).published
1474
+ .includes(:category, :tags, :user, :post_translations)
1475
+ .order(published_at: :desc)
1476
+ posts = posts.where(category_id: params[:category_id]) if params[:category_id].present?
1477
+ @pagy, posts = pagy(posts, items: 20)
1478
+
1479
+ render json: PostBlueprint.render(posts, view: :default,
1480
+ meta: { locale: I18n.locale.to_s, **pagy_metadata(@pagy) })
1481
+ end
1482
+
1483
+ def show
1484
+ post = Post.friendly.find(params[:slug])
1485
+ authorize post
1486
+
1487
+ impressionist(post, nil, unique: [:ip_address]) # Count unique views
1488
+
1489
+ render json: PostBlueprint.render(post, view: :detail)
1490
+ end
1491
+ end
1492
+ end
1493
+ end
1494
+ ```
1495
+
1496
+ ### 5.4 Health Check Endpoint
1497
+
1498
+ ```ruby
1499
+ # app/controllers/api/v1/health_controller.rb
1500
+ module Api
1501
+ module V1
1502
+ class HealthController < BaseController
1503
+ skip_before_action :authenticate_user_from_token!
1504
+
1505
+ def show
1506
+ render json: {
1507
+ status: 'ok',
1508
+ timestamp: Time.current.iso8601,
1509
+ services: {
1510
+ database: database_ok?,
1511
+ redis: redis_ok?,
1512
+ sidekiq: sidekiq_ok?
1513
+ }
1514
+ }
1515
+ end
1516
+
1517
+ private
1518
+
1519
+ def database_ok?
1520
+ ActiveRecord::Base.connection.active?
1521
+ rescue
1522
+ false
1523
+ end
1524
+
1525
+ def redis_ok?
1526
+ Redis.new(url: ENV['REDIS_URL']).ping == 'PONG'
1527
+ rescue
1528
+ false
1529
+ end
1530
+
1531
+ def sidekiq_ok?
1532
+ Sidekiq::Stats.new.processed > 0
1533
+ rescue
1534
+ false
1535
+ end
1536
+ end
1537
+ end
1538
+ end
1539
+ ```
1540
+
1541
+ ### ✅ Checklist Phase 5
1542
+
1543
+ - [ ] `POST /api/v1/auth/sign_in` returns a JWT token
1544
+ - [ ] `GET /api/v1/posts?locale=vi` returns Vietnamese title/slug
1545
+ - [ ] `GET /api/v1/posts?locale=ja` returns Japanese title/slug
1546
+ - [ ] Request without a token → 401 Unauthorized
1547
+ - [ ] Request with an expired token → 401 Unauthorized
1548
+ - [ ] `GET /api/v1/health` returns DB/Redis/Sidekiq status
1549
+
1550
+ ---
1551
+
1552
+ ## 8. Phase 6: Admin Dashboard & System Settings {#phrase-6}
1553
+
1554
+ **Objective:** A dynamic Settings page — change rate limit, media size, SMTP, and maintenance mode without redeploying.
1555
+
1556
+ ### 8.1 Migration Settings
1557
+
1558
+ ```ruby
1559
+ # db/migrate/XXXXXX_create_settings.rb
1560
+ class CreateSettings < ActiveRecord::Migration[8.0]
1561
+ def change
1562
+ create_table :settings do |t|
1563
+ t.string :key, null: false
1564
+ t.jsonb :value
1565
+ t.string :value_type, null: false, default: 'string'
1566
+ t.string :category, null: false, default: 'general'
1567
+ t.text :description
1568
+
1569
+ t.timestamps
1570
+ end
1571
+ add_index :settings, :key, unique: true
1572
+ add_index :settings, :category
1573
+ end
1574
+ end
1575
+ ```
1576
+
1577
+ ### 8.2 Model Setting
1578
+
1579
+ ```ruby
1580
+ # app/models/setting.rb
1581
+ class Setting < ApplicationRecord
1582
+ CATEGORIES = %w[general security media email rate_limit].freeze
1583
+ VALUE_TYPES = %w[string integer boolean array json].freeze
1584
+
1585
+ validates :key, presence: true, uniqueness: true
1586
+ validates :category, inclusion: { in: CATEGORIES }
1587
+ validates :value_type, inclusion: { in: VALUE_TYPES }
1588
+
1589
+ after_save :clear_cache
1590
+
1591
+ # Class methods for easy get/set
1592
+ def self.get(key, default = nil)
1593
+ Rails.cache.fetch("setting:#{key}", expires_in: 5.minutes) do
1594
+ record = find_by(key: key)
1595
+ record ? record.typed_value : default
1596
+ end
1597
+ end
1598
+
1599
+ def self.set(key, value)
1600
+ record = find_or_initialize_by(key: key)
1601
+ record.value = value
1602
+ record.save!
1603
+ Rails.cache.delete("setting:#{key}")
1604
+ end
1605
+
1606
+ def typed_value
1607
+ case value_type
1608
+ when 'integer' then value.to_i
1609
+ when 'boolean' then value == true || value == 'true'
1610
+ when 'array' then Array(value)
1611
+ when 'json' then value.is_a?(Hash) ? value : JSON.parse(value.to_s)
1612
+ else value.to_s
1613
+ end
1614
+ end
1615
+
1616
+ private
1617
+
1618
+ def clear_cache
1619
+ Rails.cache.delete("setting:#{key}")
1620
+ # Clear related caches (e.g. blocked_ips, whitelist_ips)
1621
+ Rails.cache.delete(key)
1622
+ end
1623
+ end
1624
+ ```
1625
+
1626
+ ### 8.3 Seed default Settings data
1627
+
1628
+ ```ruby
1629
+ # db/seeds/settings.rb
1630
+ settings = [
1631
+ # Security
1632
+ { key: 'rack_login_limit', value: 5, value_type: 'integer', category: 'security', description: 'Max login attempts per period' },
1633
+ { key: 'rack_login_period', value: 60, value_type: 'integer', category: 'security', description: 'Period in seconds for login throttle' },
1634
+ { key: 'devise_lock_attempts', value: 5, value_type: 'integer', category: 'security', description: 'Max failed attempts before lock' },
1635
+ { key: 'blocked_ips', value: [], value_type: 'array', category: 'security', description: 'Blacklisted IP addresses' },
1636
+ { key: 'whitelist_ips', value: [], value_type: 'array', category: 'security', description: 'Whitelisted IP addresses' },
1637
+ { key: 'maintenance_mode', value: false, value_type: 'boolean', category: 'general', description: 'Enable maintenance mode' },
1638
+
1639
+ # Media
1640
+ { key: 'thumbnail_width', value: 800, value_type: 'integer', category: 'media', description: 'Post thumbnail width (px)' },
1641
+ { key: 'thumbnail_height', value: 450, value_type: 'integer', category: 'media', description: 'Post thumbnail height (px)' },
1642
+ { key: 'slideshow_max_size', value: 5, value_type: 'integer', category: 'media', description: 'Max images in slideshow' },
1643
+ { key: 'max_upload_size_mb', value: 10, value_type: 'integer', category: 'media', description: 'Max upload size in MB' },
1644
+
1645
+ # Email — SMTP providers as a JSON array
1646
+ { key: 'smtp_providers', value: [
1647
+ { name: 'Postmark', host: 'smtp.postmarkapp.com', port: 587, username: '', password: '', active: true },
1648
+ { name: 'SendPulse', host: 'smtp-pulse.com', port: 465, username: '', password: '', active: false }
1649
+ ],
1650
+ value_type: 'array', category: 'email', description: 'SMTP provider list for load balancing' },
1651
+ { key: 'smtp_strategy', value: 'round_robin', value_type: 'string', category: 'email',
1652
+ description: 'Email delivery strategy: round_robin | random | manual' },
1653
+ { key: 'smtp_force_provider', value: nil, value_type: 'string', category: 'email',
1654
+ description: 'Force specific provider name (overrides strategy)' },
1655
+ ]
1656
+
1657
+ settings.each do |s|
1658
+ Setting.find_or_create_by!(key: s[:key]) do |setting|
1659
+ setting.value = s[:value]
1660
+ setting.value_type = s[:value_type]
1661
+ setting.category = s[:category]
1662
+ setting.description = s[:description]
1663
+ end
1664
+ end
1665
+ ```
1666
+
1667
+ ### 8.4 Admin Settings Controller & View
1668
+
1669
+ ```ruby
1670
+ # app/controllers/admin/settings_controller.rb
1671
+ module Admin
1672
+ class SettingsController < AdminController
1673
+ def show
1674
+ @settings_by_category = Setting.all.group_by(&:category)
1675
+ end
1676
+
1677
+ def update
1678
+ params[:settings].each do |key, value|
1679
+ setting = Setting.find_by(key: key)
1680
+ next unless setting
1681
+
1682
+ # Cast value theo value_type
1683
+ cast_value = case setting.value_type
1684
+ when 'integer' then value.to_i
1685
+ when 'boolean' then value == '1' || value == 'true'
1686
+ when 'array' then value.is_a?(Array) ? value : JSON.parse(value)
1687
+ when 'json' then value.is_a?(Hash) ? value : JSON.parse(value)
1688
+ else value.to_s
1689
+ end
1690
+
1691
+ setting.update!(value: cast_value)
1692
+ end
1693
+
1694
+ redirect_to admin_settings_path, notice: t('admin.settings.updated')
1695
+ rescue JSON::ParserError => e
1696
+ redirect_to admin_settings_path, alert: "Invalid JSON: #{e.message}"
1697
+ end
1698
+ end
1699
+ end
1700
+ ```
1701
+
1702
+ ```ruby
1703
+ # app/controllers/admin/admin_controller.rb
1704
+ module Admin
1705
+ class AdminController < ApplicationController
1706
+ include Pagy::Method
1707
+
1708
+ before_action :authenticate_user!
1709
+ before_action :require_admin!
1710
+
1711
+ layout 'admin'
1712
+
1713
+ private
1714
+
1715
+ def require_admin!
1716
+ redirect_to root_path, alert: t('errors.not_authorized') unless current_user&.admin?
1717
+ end
1718
+ end
1719
+ end
1720
+ ```
1721
+
1722
+ ```erb
1723
+ <%# app/views/admin/settings/show.html.erb — overall layout %>
1724
+ <h1><%= t('admin.settings.title') %></h1>
1725
+
1726
+ <%= form_with url: admin_settings_path, method: :patch do |f| %>
1727
+ <% @settings_by_category.each do |category, settings| %>
1728
+ <section class="settings-group">
1729
+ <h2><%= t("admin.settings.categories.#{category}") %></h2>
1730
+
1731
+ <% settings.each do |setting| %>
1732
+ <div class="form-field">
1733
+ <label><%= setting.key %></label>
1734
+ <small class="hint"><%= setting.description %></small>
1735
+
1736
+ <% case setting.value_type %>
1737
+ <% when 'boolean' %>
1738
+ <%= check_box_tag "settings[#{setting.key}]", '1', setting.typed_value %>
1739
+ <% when 'array', 'json' %>
1740
+ <%= text_area_tag "settings[#{setting.key}]", setting.value.to_json, rows: 4 %>
1741
+ <% when 'integer' %>
1742
+ <%= number_field_tag "settings[#{setting.key}]", setting.typed_value, min: 0 %>
1743
+ <% else %>
1744
+ <%= text_field_tag "settings[#{setting.key}]", setting.typed_value %>
1745
+ <% end %>
1746
+ </div>
1747
+ <% end %>
1748
+ </section>
1749
+ <% end %>
1750
+
1751
+ <%= f.submit t('admin.settings.save'), class: 'btn btn-primary' %>
1752
+ <% end %>
1753
+ ```
1754
+
1755
+ ### 8.5 Multi-Provider SMTP — ActionMailer Interceptor
1756
+
1757
+ ```ruby
1758
+ # app/mailers/interceptors/smtp_selector_interceptor.rb
1759
+ module Interceptors
1760
+ class SmtpSelectorInterceptor
1761
+ def self.delivering_email(message)
1762
+ providers = Setting.get('smtp_providers', []).select { |p| p['active'] }
1763
+ return if providers.empty?
1764
+
1765
+ strategy = Setting.get('smtp_strategy', 'round_robin')
1766
+ force_name = Setting.get('smtp_force_provider')
1767
+
1768
+ provider = if force_name.present?
1769
+ providers.find { |p| p['name'] == force_name } || providers.first
1770
+ elsif strategy == 'random'
1771
+ providers.sample
1772
+ else # round_robin
1773
+ idx = (Rails.cache.increment('smtp_round_robin_index') - 1) % providers.size
1774
+ providers[idx]
1775
+ end
1776
+
1777
+ return unless provider
1778
+
1779
+ message.delivery_method.settings.merge!(
1780
+ address: provider['host'],
1781
+ port: provider['port'].to_i,
1782
+ user_name: provider['username'],
1783
+ password: provider['password'],
1784
+ authentication: :plain,
1785
+ enable_starttls_auto: true
1786
+ )
1787
+
1788
+ Rails.logger.info "[SMTP] Using provider: #{provider['name']}"
1789
+ end
1790
+ end
1791
+ end
1792
+ ```
1793
+
1794
+ ```ruby
1795
+ # config/initializers/action_mailer.rb
1796
+ ActionMailer::Base.register_interceptor(Interceptors::SmtpSelectorInterceptor)
1797
+ ```
1798
+
1799
+ ### ✅ Checklist Phase 6
1800
+
1801
+ - [ ] The `/admin/settings` page shows all settings by category
1802
+ - [ ] Change `rack_login_limit` → Rack::Attack applies immediately (within 5 minutes)
1803
+ - [ ] Enable `maintenance_mode` → the site returns 503 immediately
1804
+ - [ ] Add a second SMTP provider and verify round-robin via logs
1805
+ - [ ] `smtp_force_provider = 'Postmark'` → all mail goes through Postmark
1806
+ - [ ] Change `thumbnail_width` → the Cloudinary URL is updated
1807
+
1808
+ ---
1809
+
1810
+ ## 9. Phase 7: Audit Log & Soft Delete {#phrase-7}
1811
+
1812
+ **Objective:** Record all changes on sensitive models, with soft delete for Post and Comment.
1813
+ Add actions such as trash and restore to the Admin namespace in routes.rb and Admin Controllers.
1814
+
1815
+ ### 9.1 Set up PaperTrail
1816
+
1817
+ ```ruby
1818
+ # db/migrate/XXXXXX_create_versions.rb
1819
+ # Run: rails generate paper_trail:install
1820
+ # PaperTrail automatically creates the migration for the versions table
1821
+
1822
+ # Add whodunnit (user_id) and metadata
1823
+ class AddMetadataToVersions < ActiveRecord::Migration[8.0]
1824
+ def change
1825
+ add_column :versions, :request_ip, :string
1826
+ add_column :versions, :request_path, :string
1827
+ end
1828
+ end
1829
+ ```
1830
+
1831
+ ```ruby
1832
+ # app/models/concerns/auditable.rb
1833
+ module Auditable
1834
+ extend ActiveSupport::Concern
1835
+
1836
+ included do
1837
+ has_paper_trail(
1838
+ meta: {
1839
+ request_ip: -> { PaperTrail.request.controller_info[:ip] },
1840
+ request_path: -> { PaperTrail.request.controller_info[:path] }
1841
+ }
1842
+ )
1843
+ end
1844
+ end
1845
+ ```
1846
+
1847
+ ```ruby
1848
+ # app/controllers/application_controller.rb — add to before_action
1849
+ before_action :set_paper_trail_whodunnit
1850
+
1851
+ def info_for_paper_trail
1852
+ { ip: request.remote_ip, path: request.path }
1853
+ end
1854
+ ```
1855
+
1856
+ ```ruby
1857
+ # app/models/post.rb — add
1858
+ include Auditable
1859
+ ```
1860
+
1861
+ ```ruby
1862
+ # app/models/setting.rb — add
1863
+ include Auditable
1864
+ ```
1865
+
1866
+ ### 9.2 Soft Delete with Discard
1867
+
1868
+ ```ruby
1869
+ # app/models/post.rb — already includes Discard::Model
1870
+ # app/models/comment.rb
1871
+ class Comment < ApplicationRecord
1872
+ include Discard::Model
1873
+
1874
+ belongs_to :user
1875
+ belongs_to :post, counter_cache: true
1876
+
1877
+ validates :body, presence: true, length: { minimum: 2, maximum: 2000 }
1878
+
1879
+ default_scope -> { kept } # Only fetch comments that have not been soft-deleted
1880
+
1881
+ # Display "Comment has been hidden"
1882
+ def display_body
1883
+ discarded? ? I18n.t('comments.deleted_placeholder') : body
1884
+ end
1885
+ end
1886
+ ```
1887
+
1888
+ ### 9.3 Admin Audit Log UI
1889
+
1890
+ ```ruby
1891
+ # app/controllers/admin/audit_logs_controller.rb
1892
+ module Admin
1893
+ class AuditLogsController < AdminController
1894
+ def index
1895
+ @pagy, @versions = pagy(
1896
+ PaperTrail::Version.includes(:item).order(created_at: :desc),
1897
+ items: 50
1898
+ )
1899
+ @versions = @versions.where(whodunnit: params[:user_id]) if params[:user_id].present?
1900
+ @versions = @versions.where(item_type: params[:item_type]) if params[:item_type].present?
1901
+ end
1902
+
1903
+ def show
1904
+ @version = PaperTrail::Version.find(params[:id])
1905
+ end
1906
+ end
1907
+ end
1908
+ ```
1909
+
1910
+ ### ✅ Checklist Phase 7
1911
+
1912
+ - [ ] Edit a post → the `versions` table gets a new record with `object_changes`
1913
+ - [ ] Edit Setting → a version is created with IP and path
1914
+ - [ ] Delete a comment → `discarded_at` is set, the comment remains in the DB
1915
+ - [ ] Frontend displays "Comment has been hidden" instead of the actual content
1916
+ - [ ] Admin visits `/admin/audit_logs` and sees the full history
1917
+ - [ ] Admin can filter by user and model type
1918
+
1919
+ ---
1920
+
1921
+ ## 10. Phase 8: Slideshow Engine {#phrase-8}
1922
+
1923
+ **Objective:** Upload multiple images, drag-and-drop ordering, and display a carousel on the frontend.
1924
+
1925
+ ### 10.1 Migration SlideshowAssets
1926
+
1927
+ ```ruby
1928
+ class CreateSlideshowAssets < ActiveRecord::Migration[8.0]
1929
+ def change
1930
+ create_table :slideshow_assets do |t|
1931
+ t.references :post, null: false, foreign_key: true
1932
+ t.string :cloudinary_public_id, null: false
1933
+ t.integer :position, null: false, default: 0
1934
+ t.string :caption
1935
+
1936
+ t.timestamps
1937
+ end
1938
+ add_index :slideshow_assets, [:post_id, :position]
1939
+ end
1940
+ end
1941
+ ```
1942
+
1943
+ ### 10.2 Model SlideshowAsset
1944
+
1945
+ ```ruby
1946
+ # app/models/slideshow_asset.rb
1947
+ class SlideshowAsset < ApplicationRecord
1948
+ belongs_to :post
1949
+
1950
+ validates :cloudinary_public_id, presence: true
1951
+ validates :position, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
1952
+
1953
+ default_scope -> { order(:position) }
1954
+
1955
+ def image_url(width: 1200)
1956
+ Cloudinary::Utils.cloudinary_url(cloudinary_public_id,
1957
+ width: width, crop: :limit, fetch_format: :auto, quality: :auto)
1958
+ end
1959
+ end
1960
+ ```
1961
+
1962
+ ### 10.3 Admin Controller
1963
+
1964
+ ```ruby
1965
+ # app/controllers/admin/slideshow_assets_controller.rb
1966
+ module Admin
1967
+ class SlideshowAssetsController < AdminController
1968
+ before_action :set_post
1969
+
1970
+ def create
1971
+ @asset = @post.slideshow_assets.build(asset_params)
1972
+ @asset.position = @post.slideshow_assets.count
1973
+
1974
+ if @asset.save
1975
+ render turbo_stream: turbo_stream.append('slideshow-assets',
1976
+ partial: 'admin/slideshow_assets/asset', locals: { asset: @asset })
1977
+ else
1978
+ render turbo_stream: turbo_stream.replace('slideshow-error',
1979
+ partial: 'admin/shared/error', locals: { errors: @asset.errors })
1980
+ end
1981
+ end
1982
+
1983
+ def destroy
1984
+ @asset = @post.slideshow_assets.find(params[:id])
1985
+ @asset.destroy
1986
+ render turbo_stream: turbo_stream.remove("slideshow-asset-#{@asset.id}")
1987
+ end
1988
+
1989
+ # PATCH /admin/posts/:post_id/slideshow_assets/reorder
1990
+ def reorder
1991
+ params[:order].each_with_index do |id, index|
1992
+ @post.slideshow_assets.find(id).update!(position: index)
1993
+ end
1994
+ head :ok
1995
+ end
1996
+
1997
+ private
1998
+
1999
+ def set_post
2000
+ @post = Post.find(params[:post_id])
2001
+ end
2002
+
2003
+ def asset_params
2004
+ params.require(:slideshow_asset).permit(:cloudinary_public_id, :caption)
2005
+ end
2006
+ end
2007
+ end
2008
+ ```
2009
+
2010
+ ### 10.4 Stimulus Sortable Controller
2011
+
2012
+ ```javascript
2013
+ // app/javascript/controllers/sortable_controller.js
2014
+ import { Controller } from "@hotwired/stimulus"
2015
+ import Sortable from "sortablejs"
2016
+
2017
+ export default class extends Controller {
2018
+ static values = { url: String }
2019
+
2020
+ connect() {
2021
+ this.sortable = Sortable.create(this.element, {
2022
+ animation: 150,
2023
+ ghostClass: "sortable-ghost",
2024
+ onEnd: this.save.bind(this)
2025
+ })
2026
+ }
2027
+
2028
+ disconnect() {
2029
+ this.sortable.destroy()
2030
+ }
2031
+
2032
+ async save() {
2033
+ const order = [...this.element.children].map(el => el.dataset.id)
2034
+
2035
+ await fetch(this.urlValue, {
2036
+ method: 'PATCH',
2037
+ headers: {
2038
+ 'Content-Type': 'application/json',
2039
+ 'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content
2040
+ },
2041
+ body: JSON.stringify({ order })
2042
+ })
2043
+ }
2044
+ }
2045
+ ```
2046
+
2047
+ ### ✅ Checklist Phase 8
2048
+
2049
+ - [ ] Upload 3 images for one post, all shown in the grid
2050
+ - [ ] Drag and drop to change the order → position is saved in the DB immediately without reloading
2051
+ - [ ] Delete 1 image → it disappears via Turbo Stream without reloading the page
2052
+ - [ ] The frontend carousel displays images in the correct `position` order
2053
+ - [ ] The `slideshow_max_size` limit from Settings is enforced
2054
+
2055
+ ---
2056
+
2057
+ ## 11. Phase 9: Multi-layer Caching {#phrase-9}
2058
+
2059
+ **Objective:** Locale-aware fragment caching, Russian Doll caching, and proper Eager Loading.
2060
+
2061
+ ### 9.1 Fragment Caching with Locale
2062
+
2063
+ ```erb
2064
+ <%# app/views/posts/_post_card.html.erb %>
2065
+ <%# Cache key includes locale to avoid cross-locale contamination %>
2066
+ <% cache [post, I18n.locale, 'card_v1'] do %>
2067
+ <article class="post-card">
2068
+ <h2><%= post.title %></h2>
2069
+ <%# ... %>
2070
+ </article>
2071
+ <% end %>
2072
+ ```
2073
+
2074
+ ### 9.2 Russian Doll Caching
2075
+
2076
+ ```erb
2077
+ <%# app/views/posts/show.html.erb %>
2078
+ <% cache [@post, I18n.locale, 'show_v1'] do %>
2079
+ <%# Post header %>
2080
+ <h1><%= @post.title %></h1>
2081
+
2082
+ <%# Slideshow (nested cache) %>
2083
+ <% cache [@post, 'slideshow_v1'] do %>
2084
+ <%= render @post.slideshow_assets %>
2085
+ <% end %>
2086
+
2087
+ <%# Comments (nested cache with counter) %>
2088
+ <% cache [@post, @post.comments_count, 'comments_v1'] do %>
2089
+ <%= render @post.comments.kept %>
2090
+ <% end %>
2091
+ <% end %>
2092
+ ```
2093
+
2094
+ ### 9.3 Eager Loading — N+1 Prevention
2095
+
2096
+ ```ruby
2097
+ # app/controllers/posts_controller.rb
2098
+ def index
2099
+ @posts = Post.published
2100
+ .includes(:user, :category, :tags, :post_translations)
2101
+ .order(published_at: :desc)
2102
+ @pagy, @posts = pagy(@posts)
2103
+ end
2104
+
2105
+ def show
2106
+ @post = Post.includes(:user, :category, :tags,
2107
+ :slideshow_assets,
2108
+ comments: :user)
2109
+ .friendly.find(params[:slug])
2110
+ end
2111
+ ```
2112
+
2113
+ ### 9.4 Low-level Cache for Settings
2114
+
2115
+ ```ruby
2116
+ # Implemented in the Setting model (see Phase 6)
2117
+ # Use: Setting.get('key') instead of Setting.find_by(key:)
2118
+ ```
2119
+
2120
+ ### ✅ Checklist Phase 9
2121
+
2122
+ - [ ] `EXPLAIN ANALYZE` on the index page shows no N+1 queries
2123
+ - [ ] Cache hit on the post/show page after the first load (check `cache read` vs `cache miss` logs)
2124
+ - [ ] Change locale → cache key changes, so the wrong-language cache is not served
2125
+ - [ ] Update a post → cache expires automatically (Rails cache_key_with_version)
2126
+
2127
+ ---
2128
+
2129
+ ## 12. Phase 10: Testing & Health Checks {#phrase-10}
2130
+
2131
+ **Objective:** Coverage ≥ 90%, mock Cloudinary, RSpec + FactoryBot for all models and APIs.
2132
+
2133
+ ### 10.1 RSpec Configuration
2134
+
2135
+ ```ruby
2136
+ # spec/rails_helper.rb
2137
+ require 'simplecov'
2138
+ SimpleCov.start 'rails' do
2139
+ add_filter '/bin/'
2140
+ add_filter '/db/'
2141
+ add_filter '/spec/'
2142
+ minimum_coverage 90
2143
+ end
2144
+
2145
+ # ... (require rails, rspec-rails, etc.)
2146
+
2147
+ RSpec.configure do |config|
2148
+ config.include FactoryBot::Syntax::Methods
2149
+ config.include Devise::Test::IntegrationHelpers, type: :request
2150
+
2151
+ config.before(:each) do
2152
+ WebMock.disable_net_connect!(allow_localhost: true)
2153
+ stub_cloudinary_requests
2154
+ end
2155
+ end
2156
+ ```
2157
+
2158
+ ```ruby
2159
+ # spec/support/cloudinary_helpers.rb
2160
+ module CloudinaryHelpers
2161
+ def stub_cloudinary_requests
2162
+ stub_request(:post, /cloudinary\.com.*upload/)
2163
+ .to_return(status: 200, body: {
2164
+ public_id: 'thumb/2025-01/test-post',
2165
+ secure_url: 'https://res.cloudinary.com/test/image/upload/test.jpg',
2166
+ width: 800, height: 450
2167
+ }.to_json, headers: { 'Content-Type' => 'application/json' })
2168
+
2169
+ stub_request(:delete, /cloudinary\.com.*resources/)
2170
+ .to_return(status: 200, body: { deleted: {} }.to_json)
2171
+
2172
+ stub_request(:post, /cloudinary\.com.*rename/)
2173
+ .to_return(status: 200, body: { public_id: 'new_id' }.to_json)
2174
+ end
2175
+ end
2176
+
2177
+ RSpec.configure { |c| c.include CloudinaryHelpers }
2178
+ ```
2179
+
2180
+ ### 10.2 Factories
2181
+
2182
+ ```ruby
2183
+ # spec/factories/users.rb
2184
+ FactoryBot.define do
2185
+ factory :user do
2186
+ sequence(:email) { |n| "user#{n}@example.com" }
2187
+ password { 'Password123!' }
2188
+ password_confirmation { 'Password123!' }
2189
+ full_name { Faker::Name.full_name }
2190
+ confirmed_at { Time.current }
2191
+ role { 'reader' }
2192
+
2193
+ trait :admin { role { 'admin' } }
2194
+ trait :author { role { 'author' } }
2195
+ trait :unconfirmed { confirmed_at { nil } }
2196
+ end
2197
+ end
2198
+ ```
2199
+
2200
+ ```ruby
2201
+ # spec/factories/posts.rb
2202
+ FactoryBot.define do
2203
+ factory :post do
2204
+ association :user, factory: [:user, :author]
2205
+ association :category
2206
+ status { 'draft' }
2207
+
2208
+ # Mobility translatable attributes
2209
+ trait :with_translations do
2210
+ after(:build) do |post|
2211
+ I18n.available_locales.each do |locale|
2212
+ Mobility.with_locale(locale) do
2213
+ post.title = Faker::Lorem.sentence(word_count: 4)
2214
+ post.slug = post.title.parameterize
2215
+ end
2216
+ end
2217
+ end
2218
+ end
2219
+
2220
+ trait :published do
2221
+ status { 'published' }
2222
+ published_at { 1.hour.ago }
2223
+ end
2224
+ end
2225
+ end
2226
+ ```
2227
+
2228
+ ### 10.3 Request Specs — API
2229
+
2230
+ ```ruby
2231
+ # spec/requests/api/v1/posts_spec.rb
2232
+ RSpec.describe 'API v1 Posts', type: :request do
2233
+ let(:user) { create(:user, :author) }
2234
+ let(:posts) { create_list(:post, 3, :published, :with_translations, user: user) }
2235
+
2236
+ describe 'GET /api/v1/posts' do
2237
+ it 'returns published posts in default locale (en)' do
2238
+ posts
2239
+ get '/api/v1/posts', headers: { 'Accept-Language' => 'en' }
2240
+
2241
+ expect(response).to have_http_status(:ok)
2242
+ json = JSON.parse(response.body)
2243
+ expect(json.length).to eq(3)
2244
+ end
2245
+
2246
+ it 'returns Vietnamese titles when locale=vi' do
2247
+ post_vi = create(:post, :published, :with_translations, user: user)
2248
+ get '/api/v1/posts', params: { locale: 'vi' }
2249
+
2250
+ json = JSON.parse(response.body)
2251
+ # Check that the title is Vietnamese (not English)
2252
+ expect(json.first['title']).to be_present
2253
+ end
2254
+ end
2255
+
2256
+ describe 'POST /api/v1/auth/sign_in' do
2257
+ it 'returns JWT token on valid credentials' do
2258
+ post '/api/v1/auth/sign_in',
2259
+ params: { user: { email: user.email, password: 'Password123!' } }
2260
+
2261
+ expect(response).to have_http_status(:ok)
2262
+ expect(response.headers['Authorization']).to match(/Bearer .+/)
2263
+ end
2264
+
2265
+ it 'returns 401 on invalid credentials' do
2266
+ post '/api/v1/auth/sign_in',
2267
+ params: { user: { email: user.email, password: 'wrong' } }
2268
+
2269
+ expect(response).to have_http_status(:unauthorized)
2270
+ end
2271
+ end
2272
+ end
2273
+ ```
2274
+
2275
+ ### 10.4 Model Specs
2276
+
2277
+ ```ruby
2278
+ # spec/models/post_spec.rb
2279
+ RSpec.describe Post, type: :model do
2280
+ it { is_expected.to belong_to(:user) }
2281
+ it { is_expected.to belong_to(:category) }
2282
+ it { is_expected.to have_many(:tags).through(:post_tags) }
2283
+ it { is_expected.to validate_inclusion_of(:status).in_array(Post::STATUSES) }
2284
+
2285
+ describe 'scopes' do
2286
+ it '.published returns only published posts with published_at in the past' do
2287
+ create(:post, :published)
2288
+ create(:post, status: 'draft')
2289
+
2290
+ expect(Post.published.count).to eq(1)
2291
+ end
2292
+ end
2293
+
2294
+ describe 'callbacks' do
2295
+ it 'enqueues PublishPostJob when scheduled_at changes' do
2296
+ post = create(:post, status: 'scheduled', scheduled_at: 1.hour.from_now)
2297
+ expect(PublishPostJob).to have_been_enqueued.with(post.id)
2298
+ end
2299
+ end
2300
+ end
2301
+ ```
2302
+
2303
+ ### ✅ Checklist Phase 10
2304
+
2305
+ - [ ] `bundle exec rspec` passes completely
2306
+ - [ ] `SimpleCov` reports coverage ≥ 90%
2307
+ - [ ] No real outbound HTTP calls in tests (WebMock enforced)
2308
+ - [ ] `GET /api/v1/health` returns `status: ok` in production
2309
+ - [ ] CI pipeline runs automatically when code is pushed (GitHub Actions / GitLab CI)
2310
+
2311
+ ---
2312
+
2313
+ ---
2314
+
2315
+ ## 13. GitHub Actions CI/CD {#ci-cd}
2316
+
2317
+ **Objective:** Run tests automatically on each push, enforcing coverage ≥ 90%.
2318
+
2319
+ ```yaml
2320
+ # .github/workflows/ci.yml
2321
+ name: CI
2322
+
2323
+ on:
2324
+ push:
2325
+ branches: [main, develop]
2326
+ pull_request:
2327
+ branches: [main]
2328
+
2329
+ jobs:
2330
+ test:
2331
+ runs-on: ubuntu-latest
2332
+
2333
+ services:
2334
+ redis:
2335
+ image: redis:7-alpine
2336
+ ports: ['6379:6379']
2337
+ options: >-
2338
+ --health-cmd "redis-cli ping"
2339
+ --health-interval 10s
2340
+ --health-timeout 5s
2341
+ --health-retries 5
2342
+
2343
+ env:
2344
+ RAILS_ENV: test
2345
+ REDIS_URL: redis://localhost:6379/0
2346
+ DEVISE_JWT_SECRET_KEY: test_secret_key_for_ci_only
2347
+ CLOUDINARY_CLOUD_NAME: test
2348
+ CLOUDINARY_API_KEY: test
2349
+ CLOUDINARY_API_SECRET: test
2350
+
2351
+ steps:
2352
+ - name: Checkout code
2353
+ uses: actions/checkout@v4
2354
+
2355
+ - name: Set up Ruby
2356
+ uses: ruby/setup-ruby@v1
2357
+ with:
2358
+ ruby-version: .ruby-version
2359
+ bundler-cache: true
2360
+
2361
+ - name: Setup database
2362
+ run: |
2363
+ bundle exec rails db:create
2364
+ bundle exec rails db:schema:load
2365
+
2366
+ - name: Run RuboCop
2367
+ run: bundle exec rubocop --parallel
2368
+
2369
+ - name: Run tests
2370
+ run: bundle exec rspec --format progress
2371
+
2372
+ - name: Check coverage
2373
+ run: |
2374
+ cat coverage/.last_run.json
2375
+ ruby -e "
2376
+ require 'json'
2377
+ result = JSON.parse(File.read('coverage/.last_run.json'))
2378
+ coverage = result['result']['line']
2379
+ abort('Coverage #{coverage}% < 90%!') if coverage < 90
2380
+ "
2381
+
2382
+ - name: Upload coverage report
2383
+ uses: actions/upload-artifact@v4
2384
+ if: always()
2385
+ with:
2386
+ name: coverage-report
2387
+ path: coverage/
2388
+ ```
2389
+
2390
+ > **Add `.ruby-version` to the project root:**
2391
+ > ```
2392
+ > 3.3.0
2393
+ > ```
2394
+
2395
+ ### ✅ Checklist CI/CD
2396
+
2397
+ - [ ] `.github/workflows/ci.yml` exists and is valid YAML
2398
+ - [ ] Push to a branch → GitHub Actions runs automatically
2399
+ - [ ] Test fails → CI fails, cannot merge
2400
+ - [ ] Coverage < 90% → CI fail
2401
+ - [ ] RuboCop offense → CI fail
2402
+
2403
+ ---
2404
+
2405
+ ## 14. Appendix {#phu-luc}
2406
+
2407
+ ### Summary ERD
2408
+
2409
+ ```
2410
+ User ──── Post ──── PostTranslation (locale, title, slug)
2411
+ │ └─── ActionTextRichText (content_en, content_vi, ...)
2412
+ │ └─── SlideshowAsset (cloudinary_public_id, position)
2413
+ │ └─── Comment (body, deleted_at)
2414
+ │ └─── Reaction (kind, user_id)
2415
+ │ └─── PostTag ── Tag
2416
+ └─── Category
2417
+ Setting (key, value JSONB, category)
2418
+ JwtDenylist (jti, expired_at)
2419
+ PaperTrail::Version (audit log)
2420
+ ```
2421
+
2422
+ ### Dependency Map — Important File Order
2423
+
2424
+ ```
2425
+ config/initializers/
2426
+ ├── cloudinary.rb ← requires ENV vars
2427
+ ├── devise.rb ← requires devise-jwt
2428
+ ├── rack_attack.rb ← requires Redis + Setting model + BlockedRequestLog model
2429
+ ├── mobility.rb ← required before loading models
2430
+ └── action_mailer.rb ← requires Setting model
2431
+
2432
+ app/models/
2433
+ ├── setting.rb ← required before the rack_attack.rb initializer
2434
+ ├── blocked_request_log.rb ← required before the rack_attack.rb initializer
2435
+ ├── user.rb ← requires devise + jwt_denylist
2436
+ ├── post.rb ← requires mobility + friendly_id + discard
2437
+ ├── category.rb ← requires friendly_id
2438
+ ├── tag.rb ← requires friendly_id
2439
+ └── comment.rb ← requires discard
2440
+
2441
+ app/jobs/
2442
+ ├── publish_post_job.rb
2443
+ ├── rename_cloudinary_assets_job.rb
2444
+ ├── cloudinary_housekeeping_job.rb
2445
+ └── admin_notification_job.rb
2446
+
2447
+ app/mailers/
2448
+ ├── admin_mailer.rb
2449
+ └── interceptors/smtp_selector_interceptor.rb ← requires the Setting model
2450
+
2451
+ app/middleware/
2452
+ └── maintenance_mode.rb ← requires the Setting model (via cache)
2453
+
2454
+ app/controllers/admin/
2455
+ ├── admin_controller.rb ← base controller for all admin controllers
2456
+ ├── settings_controller.rb
2457
+ ├── audit_logs_controller.rb
2458
+ └── slideshow_assets_controller.rb
2459
+ ```
2460
+
2461
+ ### Frequently Used Commands
2462
+
2463
+ ```bash
2464
+ # Run the dev server
2465
+ bundle exec rails s
2466
+ bundle exec sidekiq
2467
+
2468
+ # Migrations
2469
+ rails db:migrate
2470
+ rails db:seed
2471
+
2472
+ # View jobs in Sidekiq Web UI
2473
+ # Add to routes.rb:
2474
+ # require 'sidekiq/web'
2475
+ # mount Sidekiq::Web => '/sidekiq' # Remember to protect it with authenticate
2476
+
2477
+ # Test
2478
+ bundle exec rspec
2479
+ bundle exec rspec spec/models/
2480
+ bundle exec rspec spec/requests/api/
2481
+
2482
+ # Coverage report
2483
+ open coverage/index.html
2484
+
2485
+ # Rubocop
2486
+ bundle exec rubocop --autocorrect-all
2487
+ ```
docs/rails_blog_management_implementation_plan.vi.md ADDED
@@ -0,0 +1,2487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kế Hoạch Thực Hiện Chi Tiết: Rails Blog Management (Enterprise & API Ready)
2
+
3
+ > **Phiên bản:** 1.1 | **Stack:** Ruby on Rails 8, Hotwire, Cloudinary, Devise + JWT, Redis, Sidekiq, Mobility
4
+ > **Mục tiêu tài liệu:** Hướng dẫn từng bước đủ chi tiết để cả AI assistant và lập trình viên đều có thể thực thi độc lập.
5
+ >
6
+ > **Changelog v1.1:** Sửa `database.yml` cho SQLite3; thêm `dotenv-rails`; thêm `omniauthable`; thêm model `Category`, `Tag`; thêm `BlockedRequestLog` model + migration; thêm `AdminNotificationJob` + `AdminMailer`; thêm Cloudinary Media Library SDK; bổ sung `AdminController` base; thêm Settings UI controller + view; sửa Pagy usage trong API; làm rõ 4 bước workflow Post; thêm GitHub Actions CI config.
7
+
8
+ ---
9
+
10
+ ## 📊 Theo Dõi Tiến Độ
11
+
12
+ | Giai Đoạn | Trạng Thái | Mô Tả |
13
+ |-----------|------------|-------|
14
+ | Giai Đoạn 0 | ✅ Hoàn Thành | Khởi Tạo Dự Án & Cấu Hình Môi Trường |
15
+ | Giai Đoạn 1 | ✅ Hoàn Thành | Xác Thực & Phân Quyền (Devise + JWT) |
16
+ | Giai Đoạn 2 | ✅ Hoàn Thành | Quản Lý Bài Viết Đa Ngôn Ngữ |
17
+ | Giai Đoạn 3 | ⏳ Đang Chờ | Tích Hợp Cloudinary |
18
+ | Giai Đoạn 4 | ✅ Hoàn Thành | Bảo Mật Nhiều Lớp & Giới Hạn Tốc Độ |
19
+ | Giai Đoạn 5 | ✅ Hoàn Thành | API v1 |
20
+ | Giai Đoạn 6 | ✅ Hoàn Thành | Dashboard Admin & Cài Đặt Hệ Thống |
21
+ | Giai Đoạn 7 | ⏳ Đang Chờ | Audit Log & Xóa Mềm |
22
+ | Giai Đoạn 8 | ⏳ Đang Chờ | Slideshow Engine |
23
+ | Giai Đoạn 9 | ⏳ Đang Chờ | Multi-layer Caching |
24
+ | Giai Đoạn 10 | ⏳ Đang Chờ | Testing & Health Checks |
25
+
26
+ **Cập nhật lần cuối:** 13 tháng 5, 2026
27
+
28
+ ---
29
+
30
+ ## Mục Lục
31
+
32
+ 1. [Tổng Quan Kiến Trúc](#tong-quan)
33
+ 2. [Giai Đoạn 0: Khởi Tạo Dự Án & Cấu Hình Môi Trường](#giai-doan-0)
34
+ 3. [Giai Đoạn 1: Xác Thực & Phân Quyền (Devise + JWT)](#giai-doan-1)
35
+ 4. [Giai Đoạn 2: Quản Lý Bài Viết Đa Ngôn Ngữ](#giai-doan-2)
36
+ 5. [Giai Đoạn 3: Tích Hợp Cloudinary](#giai-doan-3)
37
+ 6. [Giai Đoạn 4: Bảo Mật Đa Tầng & Rate Limiting](#giai-doan-4)
38
+ 7. [Giai Đoạn 5: API v1](#giai-doan-5)
39
+ 8. [Giai Đoạn 6: Admin Dashboard & System Settings](#giai-doan-6)
40
+ 9. [Giai Đoạn 7: Audit Log & Soft Delete](#giai-doan-7)
41
+ 10. [Giai Đoạn 8: Slideshow Engine](#giai-doan-8)
42
+ 11. [Giai Đoạn 9: Caching Đa Tầng](#giai-doan-9)
43
+ 12. [Giai Đoạn 10: Kiểm Thử & Health Checks](#giai-doan-10)
44
+ 13. [GitHub Actions CI/CD](#ci-cd)
45
+ 14. [Phụ Lục: ERD & Dependency Map](#phu-luc)
46
+
47
+ ---
48
+
49
+ ## 1. Tổng Quan Kiến Trúc {#tong-quan}
50
+
51
+ ```
52
+ ┌─────────────────────────────────────────────────────────────┐
53
+ │ CLIENT LAYER │
54
+ │ Browser (Hotwire/Turbo/Stimulus) | Vue.js / Mobile App │
55
+ └──────────────────────┬──────────────────────────────────────┘
56
+ │ HTTP / WebSocket
57
+ ┌──────────────────────▼──────────────────────────────────────┐
58
+ │ RAILS 8 APP │
59
+ │ ┌──────────────┐ ┌──────────────┐ ┌───────────────────┐ │
60
+ │ │ Web Routes │ │ API v1 │ │ Admin Namespace │ │
61
+ │ │ /vi /en ... │ │ /api/v1/... │ │ /admin/... │ │
62
+ │ └──────────────┘ └──────────────┘ └───────────────────┘ │
63
+ │ ┌─────────────────────────────────────────────────────────┐│
64
+ │ │ Middleware Stack: Rack::Attack → RateLimiter → Devise ││
65
+ │ └─────────────────────────────────────────────────────────┘│
66
+ └──────────┬─────────────────┬───────────────────┬────────────┘
67
+ │ │ │
68
+ ┌──────▼──────┐ ┌───────▼──────┐ ┌────────▼───────┐
69
+ │ sqlite3 │ │ Redis │ │ Cloudinary │
70
+ │ (Primary) │ │ (Cache/Queue)│ │ (Media CDN) │
71
+ └─────────────┘ ��──────────────┘ └────────────────┘
72
+ │
73
+ ┌────────▼───────┐
74
+ │ Sidekiq │
75
+ │ (Background) │
76
+ └────────────────┘
77
+ ```
78
+
79
+ ### Ngôn ngữ hỗ trợ
80
+
81
+ | Layer | Ngôn ngữ |
82
+ |---|---|
83
+ | **Backend / Admin UI** | Tiếng Anh (en), Tiếng Việt (vi) |
84
+ | **Frontend / Nội dung bài viết** | en, vi, ru, ja, ko, th, de (7 ngôn ngữ) |
85
+
86
+ ### Thứ tự phụ thuộc (Build Order)
87
+
88
+ ```
89
+ Giai đoạn 0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10
90
+ (Mỗi giai đoạn phụ thuộc vào giai đoạn trước. Không bỏ qua thứ tự.)
91
+ ```
92
+
93
+ ---
94
+
95
+ ## 2. Giai Đoạn 0: Khởi Tạo Dự Án & Cấu Hình Môi Trường {#giai-doan-0}
96
+
97
+ **Mục tiêu:** Tạo nền tảng Rails 8 với đầy đủ dependencies, cấu hình DB, Redis, và CI.
98
+
99
+ ### 0.1 Tạo project mới
100
+
101
+ ```bash
102
+ rails new . --force \
103
+ --database=sqlite3 \
104
+ --asset-pipeline=propshaft \
105
+ --javascript=importmap \
106
+ --skip-test # sẽ thêm RSpec sau
107
+ cd .
108
+ ```
109
+
110
+ ### 0.2 Gemfile — Thêm tất cả dependencies từ đầu
111
+
112
+ ```ruby
113
+ # Gemfile
114
+
115
+ # === AUTH ===
116
+ gem 'devise'
117
+ gem 'devise-jwt'
118
+
119
+ # === AUTHORIZATION ===
120
+ gem 'pundit'
121
+
122
+ # === I18N / MULTILINGUAL DATA ===
123
+ gem 'mobility'
124
+ gem 'mobility-actiontext' # tích hợp ActionText + Mobility
125
+
126
+ # === MEDIA ===
127
+ gem 'cloudinary'
128
+ gem 'activestorage' # đã có sẵn trong Rails, khai báo để rõ ràng
129
+
130
+ # === RICH TEXT ===
131
+ # ActionText đã built-in Rails 8
132
+
133
+ # === BACKGROUND JOBS ===
134
+ gem 'sidekiq'
135
+ gem 'sidekiq-scheduler' # cho Publish Scheduling
136
+
137
+ # === CACHING / RATE LIMIT ===
138
+ gem 'redis'
139
+ gem 'rack-attack'
140
+
141
+ # === SLUG ===
142
+ gem 'friendly_id'
143
+
144
+ # === SOFT DELETE ===
145
+ gem 'discard' # hoặc paranoia
146
+
147
+ # === AUDIT ===
148
+ gem 'paper_trail'
149
+
150
+ # === PAGINATION ===
151
+ gem 'pagy'
152
+
153
+ # === SERIALIZER (API) ===
154
+ gem 'blueprinter' # hoặc fast_jsonapi
155
+
156
+ # === VIEW COMPONENTS ===
157
+ gem 'view_component'
158
+
159
+ # === COUNTER CACHE / UNIQUE VIEWS ===
160
+ gem 'impressionist'
161
+
162
+ group :development, :test do
163
+ gem 'rspec-rails'
164
+ gem 'factory_bot_rails'
165
+ gem 'faker'
166
+ gem 'webmock'
167
+ gem 'simplecov'
168
+ gem 'shoulda-matchers'
169
+ end
170
+
171
+ group :development do
172
+ gem 'letter_opener' # preview email locally
173
+ gem 'annotate'
174
+ gem 'rubocop-rails-omakase', require: false
175
+ gem 'dotenv-rails' # load .env trong development/test
176
+ end
177
+ ```
178
+
179
+ ```bash
180
+ bundle install
181
+ ```
182
+
183
+ ### 0.3 Cấu hình Database
184
+
185
+ ```yaml
186
+ # config/database.yml
187
+ default: &default
188
+ adapter: sqlite3
189
+ pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
190
+ timeout: 5000
191
+
192
+ development:
193
+ <<: *default
194
+ database: storage/rails_8_blog_development.sqlite3
195
+
196
+ test:
197
+ <<: *default
198
+ database: storage/rails_8_blog_test.sqlite3
199
+
200
+ production:
201
+ <<: *default
202
+ database: storage/rails_8_blog_production.sqlite3
203
+ # Nếu sau này chuyển sang PostgreSQL thì dùng DATABASE_URL:
204
+ # url: <%= ENV['DATABASE_URL'] %>
205
+ ```
206
+
207
+ > **Lưu ý:** SQLite3 không dùng `username/password/host`. Các field đó chỉ dành cho PostgreSQL/MySQL. Rails 8 mặc định lưu DB file vào thư mục `storage/`.
208
+
209
+ ```bash
210
+ rails db:create
211
+ ```
212
+
213
+ ### 0.4 Cấu hình Redis & Sidekiq
214
+
215
+ ```ruby
216
+ # config/initializers/sidekiq.rb
217
+ Sidekiq.configure_server do |config|
218
+ config.redis = { url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0') }
219
+ end
220
+
221
+ Sidekiq.configure_client do |config|
222
+ config.redis = { url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0') }
223
+ end
224
+ ```
225
+
226
+ ```ruby
227
+ # config/application.rb — thêm vào class Application
228
+ config.active_job.queue_adapter = :sidekiq
229
+ config.cache_store = :redis_cache_store, {
230
+ url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/1'),
231
+ namespace: 'blog_cache'
232
+ }
233
+ ```
234
+
235
+ ```yaml
236
+ # config/sidekiq.yml
237
+ :queues:
238
+ - default
239
+ - mailers
240
+ - media
241
+ - critical
242
+ ```
243
+
244
+ ### 0.5 Cấu hình I18n
245
+
246
+ ```ruby
247
+ # config/application.rb
248
+ config.i18n.available_locales = [:en, :vi, :ru, :ja, :ko, :th, :de]
249
+ config.i18n.default_locale = :en
250
+ config.i18n.fallbacks = true
251
+ ```
252
+
253
+ ```ruby
254
+ # config/initializers/mobility.rb
255
+ Mobility.configure do |config|
256
+ config.plugins do
257
+ backend :table # dùng bảng post_translations
258
+ active_record
259
+ reader
260
+ writer
261
+ fallbacks({ vi: :en, ru: :en, ja: :en, ko: :en, th: :en, de: :en })
262
+ presence
263
+ cache
264
+ dirty
265
+ column_fallback
266
+ end
267
+ end
268
+ ```
269
+
270
+ ### 0.6 Biến môi trường (.env)
271
+
272
+ ```bash
273
+ # .env (dùng với dotenv-rails trong development)
274
+ DATABASE_URL=sqlite3://...
275
+ REDIS_URL=redis://localhost:6379/0
276
+ CLOUDINARY_CLOUD_NAME=your_cloud_name
277
+ CLOUDINARY_API_KEY=your_api_key
278
+ CLOUDINARY_API_SECRET=your_api_secret
279
+ DEVISE_JWT_SECRET_KEY=<rake secret>
280
+ ```
281
+
282
+ ### ✅ Checklist Giai Đoạn 0
283
+
284
+ - [x] `rails new` thành công, server khởi động được
285
+ - [x] `bundle install` không có lỗi
286
+ - [x] `rails db:create` tạo được database
287
+ - [x] Redis kết nối được (kiểm tra: `redis-cli ping`)
288
+ - [x] Sidekiq worker chạy được: `bundle exec sidekiq`
289
+
290
+ ---
291
+
292
+ ## 3. Giai Đoạn 1: Xác Thực & Phân Quyền (Devise + JWT) {#giai-doan-1}
293
+
294
+ **Mục tiêu:** Hệ thống đăng nhập đầy đủ Devise modules, JWT cho API, phân quyền 3 vai trò.
295
+
296
+ ### 1.1 Cài đặt Devise
297
+
298
+ ```bash
299
+ rails generate devise:install
300
+ rails generate devise User
301
+ ```
302
+
303
+ ### 1.2 Migration User — Toàn bộ Devise modules + custom fields
304
+
305
+ ```ruby
306
+ # db/migrate/XXXXXX_devise_create_users.rb
307
+ class DeviseCreateUsers < ActiveRecord::Migration[8.0]
308
+ def change
309
+ create_table :users do |t|
310
+ ## Core
311
+ t.string :email, null: false, default: ""
312
+ t.string :encrypted_password, null: false, default: ""
313
+ t.string :full_name
314
+ t.string :role, null: false, default: "reader"
315
+
316
+ ## Cloudinary Avatar
317
+ t.string :avatar_public_id
318
+
319
+ ## Recoverable
320
+ t.string :reset_password_token
321
+ t.datetime :reset_password_sent_at
322
+
323
+ ## Rememberable
324
+ t.datetime :remember_created_at
325
+
326
+ ## Trackable
327
+ t.integer :sign_in_count, default: 0, null: false
328
+ t.datetime :current_sign_in_at
329
+ t.datetime :last_sign_in_at
330
+ t.string :current_sign_in_ip
331
+ t.string :last_sign_in_ip
332
+
333
+ ## Confirmable
334
+ t.string :confirmation_token
335
+ t.datetime :confirmed_at
336
+ t.datetime :confirmation_sent_at
337
+ t.string :unconfirmed_email
338
+
339
+ ## Lockable
340
+ t.integer :failed_attempts, default: 0, null: false
341
+ t.string :unlock_token
342
+ t.datetime :locked_at
343
+
344
+ ## JWT
345
+ t.string :jti, null: false
346
+
347
+ t.timestamps null: false
348
+ end
349
+
350
+ add_index :users, :email, unique: true
351
+ add_index :users, :reset_password_token, unique: true
352
+ add_index :users, :confirmation_token, unique: true
353
+ add_index :users, :unlock_token, unique: true
354
+ add_index :users, :jti, unique: true
355
+ end
356
+ end
357
+ ```
358
+
359
+ ### 1.3 JWT Denylist table
360
+
361
+ ```ruby
362
+ # rails generate migration CreateJwtDenylist
363
+ class CreateJwtDenylist < ActiveRecord::Migration[8.0]
364
+ def change
365
+ create_table :jwt_denylist do |t|
366
+ t.string :jti, null: false
367
+ t.datetime :exp, null: false
368
+ end
369
+ add_index :jwt_denylist, :jti
370
+ end
371
+ end
372
+ ```
373
+
374
+ ```ruby
375
+ # app/models/jwt_denylist.rb
376
+ class JwtDenylist < ApplicationRecord
377
+ include Devise::JWT::RevocationStrategies::Denylist
378
+ self.table_name = 'jwt_denylist'
379
+ end
380
+ ```
381
+
382
+ ### 1.4 Model User
383
+
384
+ ```ruby
385
+ # app/models/user.rb
386
+ class User < ApplicationRecord
387
+ include Devise::JWT::RevocationStrategies::JTIMatcher
388
+
389
+ devise :database_authenticatable,
390
+ :registerable,
391
+ :recoverable,
392
+ :rememberable,
393
+ :validatable,
394
+ :confirmable,
395
+ :lockable,
396
+ :timeoutable,
397
+ :trackable,
398
+ :omniauthable, omniauth_providers: [:google_oauth2], # Sẵn sàng cho OAuth tương lai
399
+ :jwt_authenticatable, jwt_revocation_strategy: JwtDenylist
400
+
401
+ ROLES = %w[admin author reader].freeze
402
+
403
+ validates :role, inclusion: { in: ROLES }
404
+ validates :full_name, presence: true, length: { maximum: 100 }
405
+
406
+ # Scopes
407
+ scope :admins, -> { where(role: 'admin') }
408
+ scope :authors, -> { where(role: 'author') }
409
+ scope :readers, -> { where(role: 'reader') }
410
+
411
+ # Role helpers
412
+ def admin?; role == 'admin'; end
413
+ def author?; role == 'author'; end
414
+ def reader?; role == 'reader'; end
415
+
416
+ # JWT payload mở rộng
417
+ def jwt_payload
418
+ super.merge('role' => role)
419
+ end
420
+
421
+ # Cloudinary avatar URL
422
+ def avatar_url(size: 200)
423
+ return nil unless avatar_public_id.present?
424
+ Cloudinary::Utils.cloudinary_url(avatar_public_id,
425
+ width: size, height: size, crop: :fill, gravity: :face, fetch_format: :auto)
426
+ end
427
+ end
428
+ ```
429
+
430
+ ### 1.5 Cấu hình Devise (config/initializers/devise.rb) — Các điểm quan trọng
431
+
432
+ ```ruby
433
+ Devise.setup do |config|
434
+ config.mailer_sender = ENV['MAILER_SENDER']
435
+ config.secret_key = ENV['DEVISE_JWT_SECRET_KEY']
436
+
437
+ # Confirmable
438
+ config.allow_unconfirmed_access_for = 24.hours
439
+ config.confirm_within = 24.hours
440
+
441
+ # Lockable — số lần thử được load từ Setting DB (xem Giai đoạn 6)
442
+ config.maximum_attempts = 5
443
+ config.lock_strategy = :failed_attempts
444
+ config.unlock_strategy = :email
445
+
446
+ # Timeoutable
447
+ config.timeout_in = 30.minutes
448
+
449
+ # JWT
450
+ config.jwt do |jwt|
451
+ jwt.secret = ENV['DEVISE_JWT_SECRET_KEY']
452
+ jwt.dispatch_requests = [
453
+ ['POST', %r{^/api/v1/auth/sign_in$}]
454
+ ]
455
+ jwt.revocation_requests = [
456
+ ['DELETE', %r{^/api/v1/auth/sign_out$}]
457
+ ]
458
+ jwt.expiration_time = 24.hours.to_i
459
+ end
460
+ end
461
+ ```
462
+
463
+ ### 1.6 Pundit — Policies
464
+
465
+ ```ruby
466
+ # app/policies/application_policy.rb
467
+ class ApplicationPolicy
468
+ attr_reader :user, :record
469
+
470
+ def initialize(user, record)
471
+ raise Pundit::NotAuthorizedError, "must be logged in" unless user
472
+ @user = user
473
+ @record = record
474
+ end
475
+
476
+ def index? = false
477
+ def show? = false
478
+ def create? = false
479
+ def update? = false
480
+ def destroy? = false
481
+ end
482
+ ```
483
+
484
+ ```ruby
485
+ # app/policies/post_policy.rb
486
+ class PostPolicy < ApplicationPolicy
487
+ def index? = true
488
+ def show? = true
489
+
490
+ def create? = user.author? || user.admin?
491
+
492
+ def update?
493
+ user.admin? || record.user == user
494
+ end
495
+
496
+ def destroy?
497
+ user.admin? || record.user == user
498
+ end
499
+
500
+ def publish?
501
+ user.admin? || record.user == user
502
+ end
503
+
504
+ class Scope < ApplicationPolicy::Scope
505
+ def resolve
506
+ if user.admin?
507
+ scope.all
508
+ elsif user.author?
509
+ scope.where(user: user).or(scope.published)
510
+ else
511
+ scope.published
512
+ end
513
+ end
514
+ end
515
+ end
516
+ ```
517
+
518
+ ```ruby
519
+ # app/policies/user_policy.rb
520
+ class UserPolicy < ApplicationPolicy
521
+ def index? = user.admin?
522
+ def show? = user.admin? || record == user
523
+ def update? = user.admin? || record == user
524
+ def destroy? = user.admin?
525
+ end
526
+ ```
527
+
528
+ ### 1.7 ApplicationController
529
+
530
+ ```ruby
531
+ # app/controllers/application_controller.rb
532
+ class ApplicationController < ActionController::Base
533
+ include Pundit::Authorization
534
+
535
+ before_action :set_locale
536
+ before_action :authenticate_user!, except: [:home, :show]
537
+
538
+ rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
539
+
540
+ private
541
+
542
+ def set_locale
543
+ locale = params[:locale] || session[:locale] || I18n.default_locale
544
+ I18n.locale = I18n.available_locales.include?(locale.to_sym) ? locale : I18n.default_locale
545
+ end
546
+
547
+ def user_not_authorized
548
+ flash[:alert] = t('errors.not_authorized')
549
+ redirect_back(fallback_location: root_path)
550
+ end
551
+ end
552
+ ```
553
+
554
+ ### ✅ Checklist Giai Đoạn 1
555
+
556
+ - [x] `rails db:migrate` thành công
557
+ - [x] Đăng ký / đăng nhập / logout hoạt động (web form)
558
+ - [x] Email xác nhận tài khoản gửi được (dùng letter_opener local)
559
+ - [x] Tài khoản bị khóa sau 5 lần sai mật khẩu
560
+ - [x] JWT token trả về khi POST `/api/v1/auth/sign_in`
561
+ - [x] JWT token bị đưa vào denylist khi DELETE `/api/v1/auth/sign_out`
562
+ - [x] Pundit raise `NotAuthorizedError` khi reader cố truy cập admin action
563
+
564
+ ---
565
+
566
+ ## 4. Giai Đoạn 2: Quản Lý Bài Viết Đa Ngôn Ngữ {#giai-doan-2}
567
+
568
+ **Mục tiêu:** Model Post với 7 ngôn ngữ, slug riêng từng ngôn ngữ, workflow trạng thái, ActionText đa ngôn ngữ.
569
+
570
+ ### 2.1 Migrations
571
+
572
+ ```bash
573
+ rails generate migration CreateCategories name:string slug:string
574
+ rails generate migration CreateTags name:string slug:string
575
+ rails generate migration CreatePosts
576
+ rails generate migration CreatePostTranslations
577
+ rails generate migration CreatePostTags post:references tag:references
578
+ rails generate migration CreateComments body:text discarded_at:datetime:index user:references post:references
579
+ rails generate migration CreateReactions kind:string user:references post:references
580
+ ```
581
+
582
+ ### 2.1b Models Category & Tag
583
+
584
+ ```ruby
585
+ # app/models/category.rb
586
+ class Category < ApplicationRecord
587
+ extend FriendlyId
588
+ friendly_id :name, use: :slugged
589
+
590
+ has_many :posts, dependent: :restrict_with_error
591
+
592
+ validates :name, presence: true, uniqueness: true
593
+ validates :slug, presence: true, uniqueness: true
594
+
595
+ before_validation :generate_slug, if: -> { slug.blank? && name.present? }
596
+
597
+ private
598
+
599
+ def generate_slug
600
+ self.slug = name.parameterize
601
+ end
602
+ end
603
+ ```
604
+
605
+ ```ruby
606
+ # app/models/tag.rb
607
+ class Tag < ApplicationRecord
608
+ extend FriendlyId
609
+ friendly_id :name, use: :slugged
610
+
611
+ has_many :post_tags, dependent: :destroy
612
+ has_many :posts, through: :post_tags
613
+
614
+ validates :name, presence: true, uniqueness: true
615
+ validates :slug, presence: true, uniqueness: true
616
+
617
+ before_validation :generate_slug, if: -> { slug.blank? && name.present? }
618
+
619
+ private
620
+
621
+ def generate_slug
622
+ self.slug = name.parameterize
623
+ end
624
+ end
625
+ ```
626
+
627
+ ```ruby
628
+ # db/migrate/XXXXXX_create_posts.rb
629
+ class CreatePosts < ActiveRecord::Migration[8.0]
630
+ def change
631
+ create_table :posts do |t|
632
+ t.references :user, null: false, foreign_key: true
633
+ t.references :category, null: false, foreign_key: true
634
+ t.string :cloudinary_public_id # thumbnail
635
+ t.string :status, null: false, default: 'draft'
636
+ t.integer :comments_count, default: 0 # counter cache
637
+ t.integer :impressions_count, default: 0 # unique views
638
+ t.datetime :published_at
639
+ t.datetime :scheduled_at
640
+
641
+ t.timestamps
642
+ end
643
+ add_index :posts, :status
644
+ add_index :posts, :published_at
645
+ end
646
+ end
647
+ ```
648
+
649
+ ```ruby
650
+ # db/migrate/XXXXXX_create_post_translations.rb
651
+ # (Mobility tạo tự động khi dùng migration generator, nhưng dưới đây là cấu trúc mong muốn)
652
+ class CreatePostTranslations < ActiveRecord::Migration[8.0]
653
+ def change
654
+ create_table :post_translations do |t|
655
+ t.references :post, null: false, foreign_key: true
656
+ t.string :locale, null: false
657
+ t.string :title
658
+ t.string :slug
659
+
660
+ t.timestamps
661
+ end
662
+ add_index :post_translations, [:post_id, :locale], unique: true
663
+ add_index :post_translations, :slug
664
+ end
665
+ end
666
+ ```
667
+
668
+ ### 2.2 Model Post
669
+
670
+ ```ruby
671
+ # app/models/post.rb
672
+ class Post < ApplicationRecord
673
+ # --- Associations ---
674
+ belongs_to :user
675
+ belongs_to :category
676
+ has_many :post_tags, dependent: :destroy
677
+ has_many :tags, through: :post_tags
678
+ has_many :comments, dependent: :destroy
679
+ has_many :reactions, dependent: :destroy
680
+ has_many :slideshow_assets, dependent: :destroy, -> { order(:position) }
681
+
682
+ # --- ActionText (đa ngôn ngữ qua tên field khác nhau) ---
683
+ has_rich_text :content_en
684
+ has_rich_text :content_vi
685
+ has_rich_text :content_ru
686
+ has_rich_text :content_ja
687
+ has_rich_text :content_ko
688
+ has_rich_text :content_th
689
+ has_rich_text :content_de
690
+
691
+ # --- Mobility (dịch title + slug) ---
692
+ extend Mobility
693
+ translates :title, :slug, backend: :table
694
+
695
+ # --- FriendlyId (tạo slug từ title) ---
696
+ extend FriendlyId
697
+ friendly_id :title, use: [:mobility, :history]
698
+
699
+ # --- Impressionist (unique views) ---
700
+ is_impressionable counter_cache: true, column_name: :impressions_count,
701
+ unique: :ip_address
702
+
703
+ # --- Discard (soft delete) ---
704
+ include Discard::Model
705
+
706
+ # --- Enums ---
707
+ STATUSES = %w[draft pending scheduled published].freeze
708
+ validates :status, inclusion: { in: STATUSES }
709
+
710
+ # --- Scopes ---
711
+ scope :published, -> { where(status: 'published').where('published_at <= ?', Time.current) }
712
+ scope :scheduled, -> { where(status: 'scheduled').where('scheduled_at > ?', Time.current) }
713
+ scope :by_locale, ->(locale) { joins(:post_translations).where(post_translations: { locale: locale }) }
714
+
715
+ # --- Validations ---
716
+ validates :status, presence: true
717
+ validate :scheduled_at_must_be_future, if: :scheduled?
718
+
719
+ # --- Callbacks ---
720
+ after_save :schedule_publish_job, if: :saved_change_to_scheduled_at?
721
+ after_update :rename_cloudinary_assets_job, if: :saved_change_to_slug?
722
+
723
+ # --- Helpers ---
724
+ def content_for(locale)
725
+ send(:"content_#{locale}")
726
+ end
727
+
728
+ def thumbnail_url(**options)
729
+ return nil unless cloudinary_public_id.present?
730
+ Cloudinary::Utils.cloudinary_url(cloudinary_public_id,
731
+ { fetch_format: :auto, quality: :auto }.merge(options))
732
+ end
733
+
734
+ def scheduled?
735
+ status == 'scheduled'
736
+ end
737
+
738
+ def published?
739
+ status == 'published'
740
+ end
741
+
742
+ private
743
+
744
+ def scheduled_at_must_be_future
745
+ errors.add(:scheduled_at, :must_be_future) if scheduled_at.present? && scheduled_at <= Time.current
746
+ end
747
+
748
+ def schedule_publish_job
749
+ PublishPostJob.set(wait_until: scheduled_at).perform_later(id) if scheduled?
750
+ end
751
+
752
+ def rename_cloudinary_assets_job
753
+ RenameCloudinaryAssetsJob.perform_later(id)
754
+ end
755
+ end
756
+ ```
757
+
758
+ ### 2.3 Sidekiq Jobs cho Workflow
759
+
760
+ ```ruby
761
+ # app/jobs/publish_post_job.rb
762
+ class PublishPostJob < ApplicationJob
763
+ queue_as :default
764
+
765
+ def perform(post_id)
766
+ post = Post.find_by(id: post_id)
767
+ return unless post&.scheduled?
768
+ return if post.scheduled_at > Time.current
769
+
770
+ post.update!(status: 'published', published_at: Time.current)
771
+ Rails.logger.info "Post ##{post_id} published at #{Time.current}"
772
+ end
773
+ end
774
+ ```
775
+
776
+ ```ruby
777
+ # app/jobs/rename_cloudinary_assets_job.rb
778
+ class RenameCloudinaryAssetsJob < ApplicationJob
779
+ queue_as :media
780
+
781
+ def perform(post_id)
782
+ post = Post.find_by(id: post_id)
783
+ return unless post
784
+
785
+ # 1. Đổi tên thumbnail trên Cloudinary (nếu cần)
786
+ # 2. Scan ActionTextRichText để replace URL cũ → mới
787
+ I18n.available_locales.each do |locale|
788
+ rich_text = ActionText::RichText.find_by(
789
+ record_type: 'Post', record_id: post_id, name: "content_#{locale}"
790
+ )
791
+ next unless rich_text
792
+
793
+ # Thay thế tất cả URL ảnh cũ bằng URL mới
794
+ # (Logic cụ thể phụ thuộc vào naming convention)
795
+ updated_body = rich_text.body.to_s.gsub(/old_public_id_pattern/, 'new_public_id')
796
+ rich_text.update!(body: updated_body) if updated_body != rich_text.body.to_s
797
+ end
798
+ end
799
+ end
800
+ ```
801
+
802
+ ### 2.4 Routes cho đa ngôn ngữ
803
+
804
+ ```ruby
805
+ # config/routes.rb
806
+ Rails.application.routes.draw do
807
+ # Locale scope cho web frontend (7 ngôn ngữ)
808
+ scope '/:locale', locale: /en|vi|ru|ja|ko|th|de/ do
809
+ resources :posts, param: :slug, only: [:index, :show]
810
+ resources :categories, param: :slug, only: [:index, :show]
811
+ resources :tags, param: :slug, only: [:index, :show]
812
+ end
813
+
814
+ # Admin namespace (chỉ en + vi)
815
+ namespace :admin do
816
+ resources :posts do
817
+ member do
818
+ patch :publish
819
+ patch :schedule
820
+ end
821
+ end
822
+ resources :users
823
+ resources :categories
824
+ resources :tags
825
+ resource :settings, only: [:show, :update]
826
+ resources :audit_logs, only: [:index, :show]
827
+ end
828
+
829
+ # Devise routes
830
+ devise_for :users, path: 'auth', controllers: {
831
+ sessions: 'users/sessions',
832
+ registrations: 'users/registrations',
833
+ confirmations: 'users/confirmations',
834
+ passwords: 'users/passwords'
835
+ }
836
+
837
+ # API
838
+ namespace :api do
839
+ namespace :v1 do
840
+ # ... (xem Giai đoạn 5)
841
+ end
842
+ end
843
+
844
+ root to: 'posts#index'
845
+ end
846
+ ```
847
+
848
+ ### 2.5 Giao diện Admin — Language Tabs với Stimulus
849
+
850
+ ```javascript
851
+ // app/javascript/controllers/language_tabs_controller.js
852
+ import { Controller } from "@hotwired/stimulus"
853
+
854
+ export default class extends Controller {
855
+ static targets = ["tab", "panel"]
856
+ static values = { active: { type: String, default: "en" } }
857
+
858
+ connect() {
859
+ this.activate(this.activeValue)
860
+ }
861
+
862
+ switch(event) {
863
+ const locale = event.currentTarget.dataset.locale
864
+ this.activeValue = locale
865
+ this.activate(locale)
866
+ }
867
+
868
+ activate(locale) {
869
+ this.tabTargets.forEach(tab => {
870
+ tab.classList.toggle("active", tab.dataset.locale === locale)
871
+ })
872
+ this.panelTargets.forEach(panel => {
873
+ panel.hidden = panel.dataset.locale !== locale
874
+ })
875
+ }
876
+ }
877
+ ```
878
+
879
+ ```erb
880
+ <%# app/views/admin/posts/_language_tabs.html.erb %>
881
+ <div data-controller="language-tabs">
882
+ <div class="tab-list" role="tablist">
883
+ <% I18n.available_locales.each do |locale| %>
884
+ <button
885
+ data-language-tabs-target="tab"
886
+ data-locale="<%= locale %>"
887
+ data-action="click->language-tabs#switch"
888
+ role="tab"
889
+ class="tab-btn">
890
+ <%= t("locales.#{locale}") %>
891
+ </button>
892
+ <% end %>
893
+ </div>
894
+
895
+ <% I18n.available_locales.each do |locale| %>
896
+ <div data-language-tabs-target="panel" data-locale="<%= locale %>" hidden>
897
+ <%= f.text_field :title, data: { locale: locale },
898
+ placeholder: t('admin.posts.title_placeholder', locale: locale) %>
899
+ <%= render 'trix_editor', f: f, locale: locale %>
900
+ </div>
901
+ <% end %>
902
+ </div>
903
+ ```
904
+
905
+ ### ✅ Checklist Giai Đoạn 2
906
+
907
+ - [x] Tạo bài viết với tiêu đề bằng 7 ngôn ngữ (qua Language Tabs)
908
+ - [x] Slug tự động generate từ tiêu đề, unique theo locale
909
+ - [x] URL `/en/posts/hello-world` và `/vi/posts/xin-chao` đều hoạt động
910
+ - [x] Workflow đầy đủ 4 bước: **Draft → Pending → Scheduled → Published**
911
+ - `draft`: Tác giả đang soạn, chưa submit
912
+ - `pending`: Đã submit, chờ Admin duyệt
913
+ - `scheduled`: Admin duyệt, set thời gian đăng
914
+ - `published`: Đã đăng công khai
915
+ - [x] `PublishPostJob` chạy đúng giờ đã schedule
916
+ - [x] Bài viết hiển thị đúng ngôn ngữ theo URL locale
917
+ - [x] Author chỉ thấy bài của mình, Admin thấy tất cả
918
+
919
+ ---
920
+
921
+ ## 5. Giai Đoạn 3: Tích Hợp Cloudinary {#giai-doan-3}
922
+
923
+ **Mục tiêu:** Direct upload, Media Library SDK, tổ chức thư mục, transformation tự động.
924
+
925
+ ### 3.1 Cấu hình Cloudinary
926
+
927
+ ```ruby
928
+ # config/initializers/cloudinary.rb
929
+ Cloudinary.config do |config|
930
+ config.cloud_name = ENV['CLOUDINARY_CLOUD_NAME']
931
+ config.api_key = ENV['CLOUDINARY_API_KEY']
932
+ config.api_secret = ENV['CLOUDINARY_API_SECRET']
933
+ config.secure = true
934
+ end
935
+ ```
936
+
937
+ ```ruby
938
+ # config/storage.yml
939
+ cloudinary:
940
+ service: Cloudinary
941
+ ```
942
+
943
+ ```ruby
944
+ # config/environments/production.rb
945
+ config.active_storage.service = :cloudinary
946
+ ```
947
+
948
+ ### 3.2 Controller tạo Upload Signature (Direct Signed Upload)
949
+
950
+ ```ruby
951
+ # app/controllers/uploads_controller.rb
952
+ class UploadsController < ApplicationController
953
+ before_action :authenticate_user!
954
+
955
+ # GET /uploads/signature?folder=thumb/2025-01&public_id=hello-world
956
+ def signature
957
+ folder = params.require(:folder)
958
+ public_id = params[:public_id]
959
+
960
+ timestamp = Time.now.to_i
961
+ params_to_sign = {
962
+ timestamp: timestamp,
963
+ folder: folder,
964
+ public_id: public_id
965
+ }.compact
966
+
967
+ signature = Cloudinary::Utils.api_sign_request(params_to_sign, ENV['CLOUDINARY_API_SECRET'])
968
+
969
+ render json: {
970
+ signature: signature,
971
+ timestamp: timestamp,
972
+ api_key: ENV['CLOUDINARY_API_KEY'],
973
+ cloud_name: ENV['CLOUDINARY_CLOUD_NAME'],
974
+ folder: folder,
975
+ public_id: public_id
976
+ }
977
+ end
978
+ end
979
+ ```
980
+ Cần bổ sung thêm script của Cloudinary Media Widget vào layout admin và một Stimulus controller để trigger widget này, sau đó map public_id trả về vào form.
981
+
982
+ ### 3.3 Stimulus Controller — Direct Upload
983
+
984
+ ```javascript
985
+ // app/javascript/controllers/cloudinary_upload_controller.js
986
+ import { Controller } from "@hotwired/stimulus"
987
+
988
+ export default class extends Controller {
989
+ static targets = ["input", "preview", "publicIdField", "progress"]
990
+ static values = { folder: String, publicId: String }
991
+
992
+ async upload(event) {
993
+ const file = event.target.files[0]
994
+ if (!file) return
995
+
996
+ // 1. Lấy signature từ server Rails
997
+ const sigRes = await fetch(`/uploads/signature?folder=${this.folderValue}&public_id=${this.publicIdValue}`)
998
+ const sig = await sigRes.json()
999
+
1000
+ // 2. Upload trực tiếp lên Cloudinary
1001
+ const formData = new FormData()
1002
+ formData.append('file', file)
1003
+ formData.append('api_key', sig.api_key)
1004
+ formData.append('timestamp', sig.timestamp)
1005
+ formData.append('signature', sig.signature)
1006
+ formData.append('folder', sig.folder)
1007
+ if (sig.public_id) formData.append('public_id', sig.public_id)
1008
+
1009
+ const uploadRes = await fetch(
1010
+ `https://api.cloudinary.com/v1_1/${sig.cloud_name}/image/upload`,
1011
+ { method: 'POST', body: formData }
1012
+ )
1013
+
1014
+ const result = await uploadRes.json()
1015
+
1016
+ // 3. Gửi public_id về Rails để lưu DB
1017
+ this.publicIdFieldTarget.value = result.public_id
1018
+ this.previewTarget.src = result.secure_url
1019
+ this.previewTarget.hidden = false
1020
+ }
1021
+ }
1022
+ ```
1023
+
1024
+ ### 3.4 Cloudinary Media Library SDK (Chọn ảnh từ thư viện)
1025
+
1026
+ > Cho phép Admin mở popup chọn ảnh đã upload sẵn trên Cloudinary thay vì phải upload lại.
1027
+
1028
+ ```erb
1029
+ <%# app/views/layouts/admin.html.erb — thêm vào <head> %>
1030
+ <script src="https://media-library.cloudinary.com/global/all.js" type="text/javascript"></script>
1031
+ ```
1032
+
1033
+ ```javascript
1034
+ // app/javascript/controllers/cloudinary_media_library_controller.js
1035
+ import { Controller } from "@hotwired/stimulus"
1036
+
1037
+ export default class extends Controller {
1038
+ static targets = ["publicIdField", "preview"]
1039
+ static values = { cloudName: String, apiKey: String }
1040
+
1041
+ open() {
1042
+ const widget = cloudinary.createMediaLibrary(
1043
+ {
1044
+ cloud_name: this.cloudNameValue,
1045
+ api_key: this.apiKeyValue,
1046
+ multiple: false,
1047
+ max_files: 1
1048
+ },
1049
+ {
1050
+ insertHandler: (data) => {
1051
+ const asset = data.assets[0]
1052
+ this.publicIdFieldTarget.value = asset.public_id
1053
+ this.previewTarget.src = asset.secure_url
1054
+ this.previewTarget.hidden = false
1055
+ }
1056
+ }
1057
+ )
1058
+ widget.show()
1059
+ }
1060
+ }
1061
+ ```
1062
+
1063
+ ```erb
1064
+ <%# Sử dụng trong form Admin %>
1065
+ <div data-controller="cloudinary-media-library"
1066
+ data-cloudinary-media-library-cloud-name-value="<%= ENV['CLOUDINARY_CLOUD_NAME'] %>"
1067
+ data-cloudinary-media-library-api-key-value="<%= ENV['CLOUDINARY_API_KEY'] %>">
1068
+
1069
+ <%= f.hidden_field :cloudinary_public_id,
1070
+ data: { cloudinary_media_library_target: 'publicIdField' } %>
1071
+
1072
+ <img data-cloudinary-media-library-target="preview"
1073
+ src="" alt="Preview" hidden style="max-width:300px" />
1074
+
1075
+ <button type="button"
1076
+ data-action="click->cloudinary-media-library#open"
1077
+ class="btn btn-secondary">
1078
+ 📷 Chọn từ Media Library
1079
+ </button>
1080
+ </div>
1081
+ ```
1082
+
1083
+ ### 3.6 Helper — Cloudinary Transformation URLs
1084
+
1085
+ ```ruby
1086
+ # app/helpers/cloudinary_helper.rb
1087
+ module CloudinaryHelper
1088
+ # Thumbnail cho bài viết (f_auto + q_auto)
1089
+ def post_thumbnail_url(public_id, width: 800, height: 450)
1090
+ return '' unless public_id.present?
1091
+ Cloudinary::Utils.cloudinary_url(public_id,
1092
+ width: width, height: height, crop: :fill,
1093
+ fetch_format: :auto, quality: :auto)
1094
+ end
1095
+
1096
+ # Avatar user (face crop + round)
1097
+ def user_avatar_url(public_id, size: 80)
1098
+ return '' unless public_id.present?
1099
+ Cloudinary::Utils.cloudinary_url(public_id,
1100
+ width: size, height: size,
1101
+ crop: :fill, gravity: :face,
1102
+ fetch_format: :auto, quality: :auto,
1103
+ radius: :max)
1104
+ end
1105
+
1106
+ # Gallery image trong slideshow
1107
+ def slideshow_url(public_id, width: 1200)
1108
+ return '' unless public_id.present?
1109
+ Cloudinary::Utils.cloudinary_url(public_id,
1110
+ width: width, crop: :limit,
1111
+ fetch_format: :auto, quality: :auto)
1112
+ end
1113
+
1114
+ # Công thức folder cho thumbnail
1115
+ def thumbnail_folder(post)
1116
+ "thumb/#{Date.today.strftime('%Y-%m')}/#{post.id}"
1117
+ end
1118
+
1119
+ # Công thức folder cho gallery
1120
+ def gallery_folder(post)
1121
+ "gallery/#{Date.today.strftime('%Y-%m')}/#{post.id}"
1122
+ end
1123
+ end
1124
+ ```
1125
+
1126
+ ### 3.7 Sidekiq Job — Dọn dẹp ảnh mồ côi
1127
+
1128
+ ```ruby
1129
+ # app/jobs/cloudinary_housekeeping_job.rb
1130
+ class CloudinaryHousekeepingJob < ApplicationJob
1131
+ queue_as :media
1132
+
1133
+ def perform
1134
+ used_ids = Post.pluck(:cloudinary_public_id).compact
1135
+ used_ids += SlideshowAsset.pluck(:cloudinary_public_id).compact
1136
+ used_ids += User.pluck(:avatar_public_id).compact
1137
+
1138
+ # Lấy tất cả ảnh trong folder của app từ Cloudinary
1139
+ result = Cloudinary::Api.resources(type: :upload, prefix: 'thumb/', max_results: 500)
1140
+ result['resources'].each do |resource|
1141
+ unless used_ids.include?(resource['public_id'])
1142
+ Cloudinary::Api.delete_resources([resource['public_id']])
1143
+ Rails.logger.info "Deleted orphan: #{resource['public_id']}"
1144
+ end
1145
+ end
1146
+ end
1147
+ end
1148
+ ```
1149
+
1150
+ ```yaml
1151
+ # config/sidekiq.yml — thêm schedule
1152
+ :schedule:
1153
+ cloudinary_housekeeping:
1154
+ cron: "0 3 * * 0" # Chạy 3AM mỗi Chủ nhật
1155
+ class: CloudinaryHousekeepingJob
1156
+ ```
1157
+
1158
+ ### ✅ Checklist Giai Đoạn 3
1159
+
1160
+ - [ ] Upload ảnh không qua server Rails (kiểm tra RAM server không tăng khi upload)
1161
+ - [ ] `public_id` được lưu vào DB sau upload thành công
1162
+ - [ ] URL ảnh tự động trả về WebP trên Chrome
1163
+ - [ ] Thumbnail hiển thị đúng `f_auto,q_auto`
1164
+ - [ ] Cloudinary Media Library popup mở được trong Admin, chọn ảnh �� `public_id` điền vào form
1165
+ - [ ] `RenameCloudinaryAssetsJob` thay thế URL trong ActionText khi slug thay đổi
1166
+ - [ ] `CloudinaryHousekeepingJob` chạy và xóa ảnh mồ côi
1167
+
1168
+ ---
1169
+
1170
+ ## 6. Giai Đoạn 4: Bảo Mật Đa Tầng & Rate Limiting {#giai-doan-4}
1171
+
1172
+ **Mục tiêu:** Rack::Attack + Rails 8 RateLimiting + IP Whitelist/Blacklist, tất cả đều cấu hình động qua Settings.
1173
+
1174
+ ### 4.1 Rack::Attack
1175
+
1176
+ ```ruby
1177
+ # config/initializers/rack_attack.rb
1178
+ class Rack::Attack
1179
+ # Helper: Lấy giới hạn từ Setting DB (cache Redis)
1180
+ def self.setting(key, default)
1181
+ Rails.cache.fetch("setting:#{key}", expires_in: 5.minutes) do
1182
+ Setting.find_by(key: key)&.value || default
1183
+ end
1184
+ end
1185
+
1186
+ ### Tầng 0: Throttle login brute-force
1187
+ throttle('login/ip', limit: -> { setting('rack_login_limit', 5) },
1188
+ period: -> { setting('rack_login_period', 60).seconds }) do |req|
1189
+ req.ip if req.path == '/auth/sign_in' && req.post?
1190
+ end
1191
+
1192
+ throttle('login/email', limit: -> { setting('rack_login_limit', 5) },
1193
+ period: -> { setting('rack_login_period', 60).seconds }) do |req|
1194
+ if req.path == '/auth/sign_in' && req.post?
1195
+ req.params.dig('user', 'email')&.downcase&.gsub(/\s+/, '')
1196
+ end
1197
+ end
1198
+
1199
+ ### IP Blacklist (từ Setting DB)
1200
+ blocklist('blocked_ips') do |req|
1201
+ blocked = Rails.cache.fetch('blocked_ips', expires_in: 5.minutes) do
1202
+ Setting.find_by(key: 'blocked_ips')&.value || []
1203
+ end
1204
+ blocked.include?(req.ip)
1205
+ end
1206
+
1207
+ ### IP Whitelist (bypass toàn bộ throttle)
1208
+ safelist('whitelist_ips') do |req|
1209
+ allowed = Rails.cache.fetch('whitelist_ips', expires_in: 5.minutes) do
1210
+ Setting.find_by(key: 'whitelist_ips')&.value || []
1211
+ end
1212
+ allowed.include?(req.ip)
1213
+ end
1214
+
1215
+ ### Callback khi bị block
1216
+ self.throttled_responder = lambda do |env|
1217
+ req = Rack::Request.new(env)
1218
+ # Ghi log và notify Admin
1219
+ BlockedRequestLog.create!(ip: req.ip, path: req.path, reason: 'throttled')
1220
+ AdminNotificationJob.perform_later("IP #{req.ip} bị throttle trên #{req.path}")
1221
+
1222
+ [429, { 'Content-Type' => 'application/json' },
1223
+ [{ error: 'Too Many Requests', retry_after: 60 }.to_json]]
1224
+ end
1225
+ end
1226
+ ```
1227
+
1228
+ ### 4.4 BlockedRequestLog — Model & Migration
1229
+
1230
+ > **Lưu ý quan trọng:** Model này cần phải tạo *trước* khi viết `rack_attack.rb` vì initializer sẽ gọi `BlockedRequestLog.create!`.
1231
+
1232
+ ```bash
1233
+ rails generate migration CreateBlockedRequestLogs ip:string path:string reason:string user_agent:string
1234
+ ```
1235
+
1236
+ ```ruby
1237
+ # app/models/blocked_request_log.rb
1238
+ class BlockedRequestLog < ApplicationRecord
1239
+ validates :ip, presence: true
1240
+ validates :reason, presence: true
1241
+
1242
+ scope :recent, -> { order(created_at: :desc) }
1243
+ scope :by_ip, ->(ip) { where(ip: ip) }
1244
+ end
1245
+ ```
1246
+
1247
+ ### 4.5 AdminNotificationJob
1248
+
1249
+ ```ruby
1250
+ # app/jobs/admin_notification_job.rb
1251
+ class AdminNotificationJob < ApplicationJob
1252
+ queue_as :critical
1253
+
1254
+ def perform(message)
1255
+ admin_emails = User.admins.pluck(:email)
1256
+ return if admin_emails.empty?
1257
+
1258
+ admin_emails.each do |email|
1259
+ AdminMailer.security_alert(email, message).deliver_later
1260
+ end
1261
+
1262
+ Rails.logger.warn "[SECURITY ALERT] #{message}"
1263
+ end
1264
+ end
1265
+ ```
1266
+
1267
+ ```ruby
1268
+ # app/mailers/admin_mailer.rb
1269
+ class AdminMailer < ApplicationMailer
1270
+ def security_alert(email, message)
1271
+ @message = message
1272
+ mail(to: email, subject: "[Security Alert] #{message.truncate(60)}")
1273
+ end
1274
+ end
1275
+ ```
1276
+
1277
+ ```ruby
1278
+ # app/controllers/comments_controller.rb
1279
+ class CommentsController < ApplicationController
1280
+ # Tầng 1: Giới hạn hành vi theo user cụ thể
1281
+ rate_limit to: 10, within: 1.minute,
1282
+ by: -> { current_user&.id || request.ip },
1283
+ with: -> {
1284
+ flash[:alert] = I18n.t('errors.rate_limited')
1285
+ redirect_back fallback_location: root_path
1286
+ },
1287
+ only: :create
1288
+
1289
+ def create
1290
+ # ...
1291
+ end
1292
+ end
1293
+ ```
1294
+
1295
+ ```ruby
1296
+ # app/controllers/reactions_controller.rb
1297
+ class ReactionsController < ApplicationController
1298
+ rate_limit to: 30, within: 1.minute,
1299
+ by: -> { current_user&.id || request.ip },
1300
+ only: [:create, :destroy]
1301
+ end
1302
+ ```
1303
+
1304
+ ### 4.3 Maintenance Mode Middleware
1305
+
1306
+ ```ruby
1307
+ # app/middleware/maintenance_mode.rb
1308
+ class MaintenanceMode
1309
+ def initialize(app)
1310
+ @app = app
1311
+ end
1312
+
1313
+ def call(env)
1314
+ req = Rack::Request.new(env)
1315
+
1316
+ # Kiểm tra maintenance mode từ cache (tránh DB query mỗi request)
1317
+ maintenance = Rails.cache.fetch('setting:maintenance_mode', expires_in: 1.minute) do
1318
+ Setting.find_by(key: 'maintenance_mode')&.value == true
1319
+ end
1320
+
1321
+ if maintenance
1322
+ # Admin path được bypass
1323
+ return @app.call(env) if req.path.start_with?('/admin', '/auth')
1324
+
1325
+ locale = req.path.split('/')[1] || 'en'
1326
+ message = I18n.t('maintenance.message', locale: locale)
1327
+ [503, { 'Content-Type' => 'text/html; charset=utf-8' },
1328
+ [maintenance_html(message)]]
1329
+ else
1330
+ @app.call(env)
1331
+ end
1332
+ end
1333
+
1334
+ private
1335
+
1336
+ def maintenance_html(message)
1337
+ "<html><body style='text-align:center;padding:100px;font-family:sans-serif'>
1338
+ <h1>🔧 Maintenance</h1><p>#{CGI.escapeHTML(message)}</p>
1339
+ </body></html>"
1340
+ end
1341
+ end
1342
+ ```
1343
+
1344
+ ```ruby
1345
+ # config/application.rb
1346
+ config.middleware.insert_before ActionDispatch::Static, MaintenanceMode
1347
+ ```
1348
+
1349
+ ### ✅ Checklist Giai Đoạn 4
1350
+
1351
+ - [x] Đăng nhập sai 5 lần → HTTP 429 trả về
1352
+ - [x] IP trong `blocked_ips` setting → bị block ngay lập tức
1353
+ - [x] IP trong `whitelist_ips` setting → không bị throttle dù request nhiều
1354
+ - [x] Comment quá 10 lần/phút → flash message, redirect
1355
+ - [x] Bật `maintenance_mode = true` → user thấy 503, admin vẫn vào được
1356
+ - [x] `BlockedRequestLog` ghi nhận đúng các IP bị block (kiểm tra trong `/admin/audit_logs` hoặc Rails console)
1357
+ - [x] `AdminNotificationJob` enqueue khi có IP bị throttle
1358
+
1359
+ ---
1360
+
1361
+ ## 7. Giai Đoạn 5: API v1 {#giai-doan-5}
1362
+
1363
+ **Mục tiêu:** RESTful JSON API với JWT auth, locale-aware response, Blueprinter serializers.
1364
+
1365
+ ### 5.1 Base API Controller
1366
+
1367
+ ```ruby
1368
+ # app/controllers/api/v1/base_controller.rb
1369
+ module Api
1370
+ module V1
1371
+ class BaseController < ActionController::API
1372
+ include Pundit::Authorization
1373
+ include Pagy::Method
1374
+
1375
+ before_action :authenticate_user_from_token!
1376
+ before_action :set_locale
1377
+
1378
+ rescue_from Pundit::NotAuthorizedError do
1379
+ render json: { error: 'Forbidden' }, status: :forbidden
1380
+ end
1381
+
1382
+ rescue_from ActiveRecord::RecordNotFound do
1383
+ render json: { error: 'Not Found' }, status: :not_found
1384
+ end
1385
+
1386
+ rescue_from ActiveRecord::RecordInvalid do |e|
1387
+ render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
1388
+ end
1389
+
1390
+ private
1391
+
1392
+ def authenticate_user_from_token!
1393
+ # devise-jwt xử lý tự động qua warden
1394
+ unless current_user
1395
+ render json: { error: 'Unauthorized' }, status: :unauthorized
1396
+ end
1397
+ end
1398
+
1399
+ def set_locale
1400
+ locale = request.headers['Accept-Language'] || params[:locale] || 'en'
1401
+ I18n.locale = I18n.available_locales.include?(locale.to_sym) ? locale : :en
1402
+ end
1403
+ end
1404
+ end
1405
+ end
1406
+ ```
1407
+
1408
+ ### 5.2 API Routes
1409
+
1410
+ ```ruby
1411
+ # config/routes.rb (phần API)
1412
+ namespace :api do
1413
+ namespace :v1 do
1414
+ # Auth
1415
+ devise_for :users, path: 'auth',
1416
+ controllers: { sessions: 'api/v1/auth/sessions' },
1417
+ defaults: { format: :json }
1418
+
1419
+ # Resources
1420
+ resources :posts, param: :slug, only: [:index, :show] do
1421
+ resources :comments, only: [:index, :create]
1422
+ resources :reactions, only: [:create, :destroy]
1423
+ end
1424
+ resources :categories, only: [:index, :show]
1425
+ resources :tags, only: [:index, :show]
1426
+
1427
+ # User profile
1428
+ resource :profile, only: [:show, :update]
1429
+
1430
+ # Health check
1431
+ get '/health', to: 'health#show'
1432
+ end
1433
+ end
1434
+ ```
1435
+
1436
+ ### 5.3 Blueprinter Serializers
1437
+
1438
+ ```ruby
1439
+ # app/blueprints/post_blueprint.rb
1440
+ class PostBlueprint < Blueprinter::Base
1441
+ identifier :id
1442
+
1443
+ view :default do
1444
+ fields :status, :published_at, :impressions_count, :comments_count
1445
+ field :title { |post| post.title } # Mobility: tự động dùng I18n.locale
1446
+ field :slug { |post| post.slug }
1447
+ field :thumbnail_url do |post|
1448
+ post.thumbnail_url(width: 800, height: 450)
1449
+ end
1450
+ association :category, blueprint: CategoryBlueprint
1451
+ association :tags, blueprint: TagBlueprint
1452
+ association :user, blueprint: UserBlueprint, view: :compact
1453
+ end
1454
+
1455
+ view :detail do
1456
+ include_view :default
1457
+ field :content do |post|
1458
+ post.content_for(I18n.locale).to_s
1459
+ end
1460
+ association :slideshow_assets, blueprint: SlideshowAssetBlueprint
1461
+ end
1462
+ end
1463
+ ```
1464
+
1465
+ ```ruby
1466
+ # app/controllers/api/v1/posts_controller.rb
1467
+ module Api
1468
+ module V1
1469
+ class PostsController < BaseController
1470
+ skip_before_action :authenticate_user_from_token!, only: [:index, :show]
1471
+
1472
+ def index
1473
+ posts = policy_scope(Post).published
1474
+ .includes(:category, :tags, :user, :post_translations)
1475
+ .order(published_at: :desc)
1476
+ posts = posts.where(category_id: params[:category_id]) if params[:category_id].present?
1477
+ @pagy, posts = pagy(posts, items: 20)
1478
+
1479
+ render json: PostBlueprint.render(posts, view: :default,
1480
+ meta: { locale: I18n.locale.to_s, **pagy_metadata(@pagy) })
1481
+ end
1482
+
1483
+ def show
1484
+ post = Post.friendly.find(params[:slug])
1485
+ authorize post
1486
+
1487
+ impressionist(post, nil, unique: [:ip_address]) # Đếm unique view
1488
+
1489
+ render json: PostBlueprint.render(post, view: :detail)
1490
+ end
1491
+ end
1492
+ end
1493
+ end
1494
+ ```
1495
+
1496
+ ### 5.4 Health Check Endpoint
1497
+
1498
+ ```ruby
1499
+ # app/controllers/api/v1/health_controller.rb
1500
+ module Api
1501
+ module V1
1502
+ class HealthController < BaseController
1503
+ skip_before_action :authenticate_user_from_token!
1504
+
1505
+ def show
1506
+ render json: {
1507
+ status: 'ok',
1508
+ timestamp: Time.current.iso8601,
1509
+ services: {
1510
+ database: database_ok?,
1511
+ redis: redis_ok?,
1512
+ sidekiq: sidekiq_ok?
1513
+ }
1514
+ }
1515
+ end
1516
+
1517
+ private
1518
+
1519
+ def database_ok?
1520
+ ActiveRecord::Base.connection.active?
1521
+ rescue
1522
+ false
1523
+ end
1524
+
1525
+ def redis_ok?
1526
+ Redis.new(url: ENV['REDIS_URL']).ping == 'PONG'
1527
+ rescue
1528
+ false
1529
+ end
1530
+
1531
+ def sidekiq_ok?
1532
+ Sidekiq::Stats.new.processed > 0
1533
+ rescue
1534
+ false
1535
+ end
1536
+ end
1537
+ end
1538
+ end
1539
+ ```
1540
+
1541
+ ### ✅ Checklist Giai Đoạn 5
1542
+
1543
+ - [ ] `POST /api/v1/auth/sign_in` trả về JWT token
1544
+ - [ ] `GET /api/v1/posts?locale=vi` trả về title/slug tiếng Việt
1545
+ - [ ] `GET /api/v1/posts?locale=ja` trả về title/slug tiếng Nhật
1546
+ - [ ] Request không có token → 401 Unauthorized
1547
+ - [ ] Request với token hết hạn → 401 Unauthorized
1548
+ - [ ] `GET /api/v1/health` trả về trạng thái DB/Redis/Sidekiq
1549
+
1550
+ ---
1551
+
1552
+ ## 8. Giai Đoạn 6: Admin Dashboard & System Settings {#giai-doan-6}
1553
+
1554
+ **Mục tiêu:** Trang Settings động — thay đổi rate limit, media size, SMTP, maintenance mode mà không cần deploy lại.
1555
+
1556
+ ### 8.1 Migration Settings
1557
+
1558
+ ```ruby
1559
+ # db/migrate/XXXXXX_create_settings.rb
1560
+ class CreateSettings < ActiveRecord::Migration[8.0]
1561
+ def change
1562
+ create_table :settings do |t|
1563
+ t.string :key, null: false
1564
+ t.jsonb :value
1565
+ t.string :value_type, null: false, default: 'string'
1566
+ t.string :category, null: false, default: 'general'
1567
+ t.text :description
1568
+
1569
+ t.timestamps
1570
+ end
1571
+ add_index :settings, :key, unique: true
1572
+ add_index :settings, :category
1573
+ end
1574
+ end
1575
+ ```
1576
+
1577
+ ### 8.2 Model Setting
1578
+
1579
+ ```ruby
1580
+ # app/models/setting.rb
1581
+ class Setting < ApplicationRecord
1582
+ CATEGORIES = %w[general security media email rate_limit].freeze
1583
+ VALUE_TYPES = %w[string integer boolean array json].freeze
1584
+
1585
+ validates :key, presence: true, uniqueness: true
1586
+ validates :category, inclusion: { in: CATEGORIES }
1587
+ validates :value_type, inclusion: { in: VALUE_TYPES }
1588
+
1589
+ after_save :clear_cache
1590
+
1591
+ # Class method để get/set dễ dàng
1592
+ def self.get(key, default = nil)
1593
+ Rails.cache.fetch("setting:#{key}", expires_in: 5.minutes) do
1594
+ record = find_by(key: key)
1595
+ record ? record.typed_value : default
1596
+ end
1597
+ end
1598
+
1599
+ def self.set(key, value)
1600
+ record = find_or_initialize_by(key: key)
1601
+ record.value = value
1602
+ record.save!
1603
+ Rails.cache.delete("setting:#{key}")
1604
+ end
1605
+
1606
+ def typed_value
1607
+ case value_type
1608
+ when 'integer' then value.to_i
1609
+ when 'boolean' then value == true || value == 'true'
1610
+ when 'array' then Array(value)
1611
+ when 'json' then value.is_a?(Hash) ? value : JSON.parse(value.to_s)
1612
+ else value.to_s
1613
+ end
1614
+ end
1615
+
1616
+ private
1617
+
1618
+ def clear_cache
1619
+ Rails.cache.delete("setting:#{key}")
1620
+ # Xóa các cache liên quan (vd: blocked_ips, whitelist_ips)
1621
+ Rails.cache.delete(key)
1622
+ end
1623
+ end
1624
+ ```
1625
+
1626
+ ### 8.3 Seed dữ liệu Settings mặc định
1627
+
1628
+ ```ruby
1629
+ # db/seeds/settings.rb
1630
+ settings = [
1631
+ # Security
1632
+ { key: 'rack_login_limit', value: 5, value_type: 'integer', category: 'security', description: 'Max login attempts per period' },
1633
+ { key: 'rack_login_period', value: 60, value_type: 'integer', category: 'security', description: 'Period in seconds for login throttle' },
1634
+ { key: 'devise_lock_attempts', value: 5, value_type: 'integer', category: 'security', description: 'Max failed attempts before lock' },
1635
+ { key: 'blocked_ips', value: [], value_type: 'array', category: 'security', description: 'Blacklisted IP addresses' },
1636
+ { key: 'whitelist_ips', value: [], value_type: 'array', category: 'security', description: 'Whitelisted IP addresses' },
1637
+ { key: 'maintenance_mode', value: false, value_type: 'boolean', category: 'general', description: 'Enable maintenance mode' },
1638
+
1639
+ # Media
1640
+ { key: 'thumbnail_width', value: 800, value_type: 'integer', category: 'media', description: 'Post thumbnail width (px)' },
1641
+ { key: 'thumbnail_height', value: 450, value_type: 'integer', category: 'media', description: 'Post thumbnail height (px)' },
1642
+ { key: 'slideshow_max_size', value: 5, value_type: 'integer', category: 'media', description: 'Max images in slideshow' },
1643
+ { key: 'max_upload_size_mb', value: 10, value_type: 'integer', category: 'media', description: 'Max upload size in MB' },
1644
+
1645
+ # Email — SMTP providers dạng JSON Array
1646
+ { key: 'smtp_providers', value: [
1647
+ { name: 'Postmark', host: 'smtp.postmarkapp.com', port: 587, username: '', password: '', active: true },
1648
+ { name: 'SendPulse', host: 'smtp-pulse.com', port: 465, username: '', password: '', active: false }
1649
+ ],
1650
+ value_type: 'array', category: 'email', description: 'SMTP provider list for load balancing' },
1651
+ { key: 'smtp_strategy', value: 'round_robin', value_type: 'string', category: 'email',
1652
+ description: 'Email delivery strategy: round_robin | random | manual' },
1653
+ { key: 'smtp_force_provider', value: nil, value_type: 'string', category: 'email',
1654
+ description: 'Force specific provider name (overrides strategy)' },
1655
+ ]
1656
+
1657
+ settings.each do |s|
1658
+ Setting.find_or_create_by!(key: s[:key]) do |setting|
1659
+ setting.value = s[:value]
1660
+ setting.value_type = s[:value_type]
1661
+ setting.category = s[:category]
1662
+ setting.description = s[:description]
1663
+ end
1664
+ end
1665
+ ```
1666
+
1667
+ ### 8.4 Admin Settings Controller & View
1668
+
1669
+ ```ruby
1670
+ # app/controllers/admin/settings_controller.rb
1671
+ module Admin
1672
+ class SettingsController < AdminController
1673
+ def show
1674
+ @settings_by_category = Setting.all.group_by(&:category)
1675
+ end
1676
+
1677
+ def update
1678
+ params[:settings].each do |key, value|
1679
+ setting = Setting.find_by(key: key)
1680
+ next unless setting
1681
+
1682
+ # Cast value theo value_type
1683
+ cast_value = case setting.value_type
1684
+ when 'integer' then value.to_i
1685
+ when 'boolean' then value == '1' || value == 'true'
1686
+ when 'array' then value.is_a?(Array) ? value : JSON.parse(value)
1687
+ when 'json' then value.is_a?(Hash) ? value : JSON.parse(value)
1688
+ else value.to_s
1689
+ end
1690
+
1691
+ setting.update!(value: cast_value)
1692
+ end
1693
+
1694
+ redirect_to admin_settings_path, notice: t('admin.settings.updated')
1695
+ rescue JSON::ParserError => e
1696
+ redirect_to admin_settings_path, alert: "Invalid JSON: #{e.message}"
1697
+ end
1698
+ end
1699
+ end
1700
+ ```
1701
+
1702
+ ```ruby
1703
+ # app/controllers/admin/admin_controller.rb
1704
+ module Admin
1705
+ class AdminController < ApplicationController
1706
+ include Pagy::Method
1707
+
1708
+ before_action :authenticate_user!
1709
+ before_action :require_admin!
1710
+
1711
+ layout 'admin'
1712
+
1713
+ private
1714
+
1715
+ def require_admin!
1716
+ redirect_to root_path, alert: t('errors.not_authorized') unless current_user&.admin?
1717
+ end
1718
+ end
1719
+ end
1720
+ ```
1721
+
1722
+ ```erb
1723
+ <%# app/views/admin/settings/show.html.erb — layout tổng quan %>
1724
+ <h1><%= t('admin.settings.title') %></h1>
1725
+
1726
+ <%= form_with url: admin_settings_path, method: :patch do |f| %>
1727
+ <% @settings_by_category.each do |category, settings| %>
1728
+ <section class="settings-group">
1729
+ <h2><%= t("admin.settings.categories.#{category}") %></h2>
1730
+
1731
+ <% settings.each do |setting| %>
1732
+ <div class="form-field">
1733
+ <label><%= setting.key %></label>
1734
+ <small class="hint"><%= setting.description %></small>
1735
+
1736
+ <% case setting.value_type %>
1737
+ <% when 'boolean' %>
1738
+ <%= check_box_tag "settings[#{setting.key}]", '1', setting.typed_value %>
1739
+ <% when 'array', 'json' %>
1740
+ <%= text_area_tag "settings[#{setting.key}]", setting.value.to_json, rows: 4 %>
1741
+ <% when 'integer' %>
1742
+ <%= number_field_tag "settings[#{setting.key}]", setting.typed_value, min: 0 %>
1743
+ <% else %>
1744
+ <%= text_field_tag "settings[#{setting.key}]", setting.typed_value %>
1745
+ <% end %>
1746
+ </div>
1747
+ <% end %>
1748
+ </section>
1749
+ <% end %>
1750
+
1751
+ <%= f.submit t('admin.settings.save'), class: 'btn btn-primary' %>
1752
+ <% end %>
1753
+ ```
1754
+
1755
+ ### 8.5 Multi-Provider SMTP — ActionMailer Interceptor
1756
+
1757
+ ```ruby
1758
+ # app/mailers/interceptors/smtp_selector_interceptor.rb
1759
+ module Interceptors
1760
+ class SmtpSelectorInterceptor
1761
+ def self.delivering_email(message)
1762
+ providers = Setting.get('smtp_providers', []).select { |p| p['active'] }
1763
+ return if providers.empty?
1764
+
1765
+ strategy = Setting.get('smtp_strategy', 'round_robin')
1766
+ force_name = Setting.get('smtp_force_provider')
1767
+
1768
+ provider = if force_name.present?
1769
+ providers.find { |p| p['name'] == force_name } || providers.first
1770
+ elsif strategy == 'random'
1771
+ providers.sample
1772
+ else # round_robin
1773
+ idx = (Rails.cache.increment('smtp_round_robin_index') - 1) % providers.size
1774
+ providers[idx]
1775
+ end
1776
+
1777
+ return unless provider
1778
+
1779
+ message.delivery_method.settings.merge!(
1780
+ address: provider['host'],
1781
+ port: provider['port'].to_i,
1782
+ user_name: provider['username'],
1783
+ password: provider['password'],
1784
+ authentication: :plain,
1785
+ enable_starttls_auto: true
1786
+ )
1787
+
1788
+ Rails.logger.info "[SMTP] Using provider: #{provider['name']}"
1789
+ end
1790
+ end
1791
+ end
1792
+ ```
1793
+
1794
+ ```ruby
1795
+ # config/initializers/action_mailer.rb
1796
+ ActionMailer::Base.register_interceptor(Interceptors::SmtpSelectorInterceptor)
1797
+ ```
1798
+
1799
+ ### ✅ Checklist Giai Đoạn 6
1800
+
1801
+ - [ ] Trang `/admin/settings` hiển thị tất cả settings theo category
1802
+ - [ ] Thay đổi `rack_login_limit` → Rack::Attack áp dụng ngay (trong 5 phút)
1803
+ - [ ] Bật `maintenance_mode` → site trả về 503 ngay
1804
+ - [ ] Thêm SMTP provider thứ 2 và kiểm tra round-robin bằng log
1805
+ - [ ] `smtp_force_provider = 'Postmark'` → tất cả mail đi qua Postmark
1806
+ - [ ] Thay đổi `thumbnail_width` → URL Cloudinary được cập nhật
1807
+
1808
+ ---
1809
+
1810
+ ## 9. Giai Đoạn 7: Audit Log & Soft Delete {#giai-doan-7}
1811
+
1812
+ **Mục tiêu:** Ghi lại toàn bộ thay đổi trên model nhạy cảm, soft delete cho Post và Comment.
1813
+ Bổ sung thêm các action như trash và restore vào Admin namespace trong routes.rb và Admin Controllers.
1814
+
1815
+ ### 9.1 Cài đặt PaperTrail
1816
+
1817
+ ```ruby
1818
+ # db/migrate/XXXXXX_create_versions.rb
1819
+ # Chạy: rails generate paper_trail:install
1820
+ # PaperTrail tự tạo migration cho bảng versions
1821
+
1822
+ # Thêm trường whodunnit (user_id) và metadata
1823
+ class AddMetadataToVersions < ActiveRecord::Migration[8.0]
1824
+ def change
1825
+ add_column :versions, :request_ip, :string
1826
+ add_column :versions, :request_path, :string
1827
+ end
1828
+ end
1829
+ ```
1830
+
1831
+ ```ruby
1832
+ # app/models/concerns/auditable.rb
1833
+ module Auditable
1834
+ extend ActiveSupport::Concern
1835
+
1836
+ included do
1837
+ has_paper_trail(
1838
+ meta: {
1839
+ request_ip: -> { PaperTrail.request.controller_info[:ip] },
1840
+ request_path: -> { PaperTrail.request.controller_info[:path] }
1841
+ }
1842
+ )
1843
+ end
1844
+ end
1845
+ ```
1846
+
1847
+ ```ruby
1848
+ # app/controllers/application_controller.rb — thêm vào before_action
1849
+ before_action :set_paper_trail_whodunnit
1850
+
1851
+ def info_for_paper_trail
1852
+ { ip: request.remote_ip, path: request.path }
1853
+ end
1854
+ ```
1855
+
1856
+ ```ruby
1857
+ # app/models/post.rb — thêm
1858
+ include Auditable
1859
+ ```
1860
+
1861
+ ```ruby
1862
+ # app/models/setting.rb — thêm
1863
+ include Auditable
1864
+ ```
1865
+
1866
+ ### 9.2 Soft Delete với Discard
1867
+
1868
+ ```ruby
1869
+ # app/models/post.rb — đã có include Discard::Model
1870
+ # app/models/comment.rb
1871
+ class Comment < ApplicationRecord
1872
+ include Discard::Model
1873
+
1874
+ belongs_to :user
1875
+ belongs_to :post, counter_cache: true
1876
+
1877
+ validates :body, presence: true, length: { minimum: 2, maximum: 2000 }
1878
+
1879
+ default_scope -> { kept } # Chỉ lấy comment chưa bị xóa mềm
1880
+
1881
+ # Hiển thị "Bình luận đã bị ẩn"
1882
+ def display_body
1883
+ discarded? ? I18n.t('comments.deleted_placeholder') : body
1884
+ end
1885
+ end
1886
+ ```
1887
+
1888
+ ### 9.3 Admin Audit Log UI
1889
+
1890
+ ```ruby
1891
+ # app/controllers/admin/audit_logs_controller.rb
1892
+ module Admin
1893
+ class AuditLogsController < AdminController
1894
+ def index
1895
+ @pagy, @versions = pagy(
1896
+ PaperTrail::Version.includes(:item).order(created_at: :desc),
1897
+ items: 50
1898
+ )
1899
+ @versions = @versions.where(whodunnit: params[:user_id]) if params[:user_id].present?
1900
+ @versions = @versions.where(item_type: params[:item_type]) if params[:item_type].present?
1901
+ end
1902
+
1903
+ def show
1904
+ @version = PaperTrail::Version.find(params[:id])
1905
+ end
1906
+ end
1907
+ end
1908
+ ```
1909
+
1910
+ ### ✅ Checklist Giai Đoạn 7
1911
+
1912
+ - [ ] Sửa bài viết → `versions` table có bản ghi mới với `object_changes`
1913
+ - [ ] Sửa Setting → version được tạo với IP và path
1914
+ - [ ] Xóa comment → `discarded_at` được set, comment vẫn trong DB
1915
+ - [ ] Frontend hiển thị "Bình luận đã bị ẩn" thay vì nội dung thực
1916
+ - [ ] Admin vào `/admin/audit_logs` thấy toàn bộ lịch sử
1917
+ - [ ] Admin có thể filter theo user và model type
1918
+
1919
+ ---
1920
+
1921
+ ## 10. Giai Đoạn 8: Slideshow Engine {#giai-doan-8}
1922
+
1923
+ **Mục tiêu:** Upload nhiều ảnh, kéo thả sắp xếp, hiển thị carousel trên frontend.
1924
+
1925
+ ### 10.1 Migration SlideshowAssets
1926
+
1927
+ ```ruby
1928
+ class CreateSlideshowAssets < ActiveRecord::Migration[8.0]
1929
+ def change
1930
+ create_table :slideshow_assets do |t|
1931
+ t.references :post, null: false, foreign_key: true
1932
+ t.string :cloudinary_public_id, null: false
1933
+ t.integer :position, null: false, default: 0
1934
+ t.string :caption
1935
+
1936
+ t.timestamps
1937
+ end
1938
+ add_index :slideshow_assets, [:post_id, :position]
1939
+ end
1940
+ end
1941
+ ```
1942
+
1943
+ ### 10.2 Model SlideshowAsset
1944
+
1945
+ ```ruby
1946
+ # app/models/slideshow_asset.rb
1947
+ class SlideshowAsset < ApplicationRecord
1948
+ belongs_to :post
1949
+
1950
+ validates :cloudinary_public_id, presence: true
1951
+ validates :position, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
1952
+
1953
+ default_scope -> { order(:position) }
1954
+
1955
+ def image_url(width: 1200)
1956
+ Cloudinary::Utils.cloudinary_url(cloudinary_public_id,
1957
+ width: width, crop: :limit, fetch_format: :auto, quality: :auto)
1958
+ end
1959
+ end
1960
+ ```
1961
+
1962
+ ### 10.3 Admin Controller
1963
+
1964
+ ```ruby
1965
+ # app/controllers/admin/slideshow_assets_controller.rb
1966
+ module Admin
1967
+ class SlideshowAssetsController < AdminController
1968
+ before_action :set_post
1969
+
1970
+ def create
1971
+ @asset = @post.slideshow_assets.build(asset_params)
1972
+ @asset.position = @post.slideshow_assets.count
1973
+
1974
+ if @asset.save
1975
+ render turbo_stream: turbo_stream.append('slideshow-assets',
1976
+ partial: 'admin/slideshow_assets/asset', locals: { asset: @asset })
1977
+ else
1978
+ render turbo_stream: turbo_stream.replace('slideshow-error',
1979
+ partial: 'admin/shared/error', locals: { errors: @asset.errors })
1980
+ end
1981
+ end
1982
+
1983
+ def destroy
1984
+ @asset = @post.slideshow_assets.find(params[:id])
1985
+ @asset.destroy
1986
+ render turbo_stream: turbo_stream.remove("slideshow-asset-#{@asset.id}")
1987
+ end
1988
+
1989
+ # PATCH /admin/posts/:post_id/slideshow_assets/reorder
1990
+ def reorder
1991
+ params[:order].each_with_index do |id, index|
1992
+ @post.slideshow_assets.find(id).update!(position: index)
1993
+ end
1994
+ head :ok
1995
+ end
1996
+
1997
+ private
1998
+
1999
+ def set_post
2000
+ @post = Post.find(params[:post_id])
2001
+ end
2002
+
2003
+ def asset_params
2004
+ params.require(:slideshow_asset).permit(:cloudinary_public_id, :caption)
2005
+ end
2006
+ end
2007
+ end
2008
+ ```
2009
+
2010
+ ### 10.4 Stimulus Sortable Controller
2011
+
2012
+ ```javascript
2013
+ // app/javascript/controllers/sortable_controller.js
2014
+ import { Controller } from "@hotwired/stimulus"
2015
+ import Sortable from "sortablejs"
2016
+
2017
+ export default class extends Controller {
2018
+ static values = { url: String }
2019
+
2020
+ connect() {
2021
+ this.sortable = Sortable.create(this.element, {
2022
+ animation: 150,
2023
+ ghostClass: "sortable-ghost",
2024
+ onEnd: this.save.bind(this)
2025
+ })
2026
+ }
2027
+
2028
+ disconnect() {
2029
+ this.sortable.destroy()
2030
+ }
2031
+
2032
+ async save() {
2033
+ const order = [...this.element.children].map(el => el.dataset.id)
2034
+
2035
+ await fetch(this.urlValue, {
2036
+ method: 'PATCH',
2037
+ headers: {
2038
+ 'Content-Type': 'application/json',
2039
+ 'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content
2040
+ },
2041
+ body: JSON.stringify({ order })
2042
+ })
2043
+ }
2044
+ }
2045
+ ```
2046
+
2047
+ ### ✅ Checklist Giai Đoạn 8
2048
+
2049
+ - [ ] Upload 3 ảnh cho 1 bài viết, đều hiển thị trong grid
2050
+ - [ ] Kéo thả thay đổi thứ tự → vị trí lưu trong DB ngay không cần reload
2051
+ - [ ] Xóa 1 ảnh → biến mất qua Turbo Stream không reload trang
2052
+ - [ ] Frontend carousel hiển thị ảnh đúng thứ tự position
2053
+ - [ ] Giới hạn `slideshow_max_size` từ Settings được enforce
2054
+
2055
+ ---
2056
+
2057
+ ## 11. Giai Đoạn 9: Caching Đa Tầng {#giai-doan-9}
2058
+
2059
+ **Mục tiêu:** Fragment caching locale-aware, Russian Doll, Eager Loading đúng chỗ.
2060
+
2061
+ ### 9.1 Fragment Caching với Locale
2062
+
2063
+ ```erb
2064
+ <%# app/views/posts/_post_card.html.erb %>
2065
+ <%# Cache key bao gồm locale để tránh cross-locale contamination %>
2066
+ <% cache [post, I18n.locale, 'card_v1'] do %>
2067
+ <article class="post-card">
2068
+ <h2><%= post.title %></h2>
2069
+ <%# ... %>
2070
+ </article>
2071
+ <% end %>
2072
+ ```
2073
+
2074
+ ### 9.2 Russian Doll Caching
2075
+
2076
+ ```erb
2077
+ <%# app/views/posts/show.html.erb %>
2078
+ <% cache [@post, I18n.locale, 'show_v1'] do %>
2079
+ <%# Header bài viết %>
2080
+ <h1><%= @post.title %></h1>
2081
+
2082
+ <%# Slideshow (nested cache) %>
2083
+ <% cache [@post, 'slideshow_v1'] do %>
2084
+ <%= render @post.slideshow_assets %>
2085
+ <% end %>
2086
+
2087
+ <%# Comments (nested cache với counter) %>
2088
+ <% cache [@post, @post.comments_count, 'comments_v1'] do %>
2089
+ <%= render @post.comments.kept %>
2090
+ <% end %>
2091
+ <% end %>
2092
+ ```
2093
+
2094
+ ### 9.3 Eager Loading — N+1 Prevention
2095
+
2096
+ ```ruby
2097
+ # app/controllers/posts_controller.rb
2098
+ def index
2099
+ @posts = Post.published
2100
+ .includes(:user, :category, :tags, :post_translations)
2101
+ .order(published_at: :desc)
2102
+ @pagy, @posts = pagy(@posts)
2103
+ end
2104
+
2105
+ def show
2106
+ @post = Post.includes(:user, :category, :tags,
2107
+ :slideshow_assets,
2108
+ comments: :user)
2109
+ .friendly.find(params[:slug])
2110
+ end
2111
+ ```
2112
+
2113
+ ### 9.4 Low-level Cache cho Settings
2114
+
2115
+ ```ruby
2116
+ # Đã implement trong model Setting (xem Giai đoạn 6)
2117
+ # Dùng: Setting.get('key') thay vì Setting.find_by(key:)
2118
+ ```
2119
+
2120
+ ### ✅ Checklist Giai Đoạn 9
2121
+
2122
+ - [ ] `EXPLAIN ANALYZE` trên trang index không có N+1 queries
2123
+ - [ ] Cache hit trên trang post/show sau lần load đầu (kiểm tra log `cache read` vs `cache miss`)
2124
+ - [ ] Thay đổi locale → cache key thay đổi, không phục vụ cache sai ngôn ngữ
2125
+ - [ ] Update bài viết → cache tự động expire (Rails cache_key_with_version)
2126
+
2127
+ ---
2128
+
2129
+ ## 12. Giai Đoạn 10: Kiểm Thử & Health Checks {#giai-doan-10}
2130
+
2131
+ **Mục tiêu:** Coverage ≥ 90%, mock Cloudinary, RSpec + FactoryBot cho tất cả models và APIs.
2132
+
2133
+ ### 10.1 Cấu hình RSpec
2134
+
2135
+ ```ruby
2136
+ # spec/rails_helper.rb
2137
+ require 'simplecov'
2138
+ SimpleCov.start 'rails' do
2139
+ add_filter '/bin/'
2140
+ add_filter '/db/'
2141
+ add_filter '/spec/'
2142
+ minimum_coverage 90
2143
+ end
2144
+
2145
+ # ... (require rails, rspec-rails, etc.)
2146
+
2147
+ RSpec.configure do |config|
2148
+ config.include FactoryBot::Syntax::Methods
2149
+ config.include Devise::Test::IntegrationHelpers, type: :request
2150
+
2151
+ config.before(:each) do
2152
+ WebMock.disable_net_connect!(allow_localhost: true)
2153
+ stub_cloudinary_requests
2154
+ end
2155
+ end
2156
+ ```
2157
+
2158
+ ```ruby
2159
+ # spec/support/cloudinary_helpers.rb
2160
+ module CloudinaryHelpers
2161
+ def stub_cloudinary_requests
2162
+ stub_request(:post, /cloudinary\.com.*upload/)
2163
+ .to_return(status: 200, body: {
2164
+ public_id: 'thumb/2025-01/test-post',
2165
+ secure_url: 'https://res.cloudinary.com/test/image/upload/test.jpg',
2166
+ width: 800, height: 450
2167
+ }.to_json, headers: { 'Content-Type' => 'application/json' })
2168
+
2169
+ stub_request(:delete, /cloudinary\.com.*resources/)
2170
+ .to_return(status: 200, body: { deleted: {} }.to_json)
2171
+
2172
+ stub_request(:post, /cloudinary\.com.*rename/)
2173
+ .to_return(status: 200, body: { public_id: 'new_id' }.to_json)
2174
+ end
2175
+ end
2176
+
2177
+ RSpec.configure { |c| c.include CloudinaryHelpers }
2178
+ ```
2179
+
2180
+ ### 10.2 Factories
2181
+
2182
+ ```ruby
2183
+ # spec/factories/users.rb
2184
+ FactoryBot.define do
2185
+ factory :user do
2186
+ sequence(:email) { |n| "user#{n}@example.com" }
2187
+ password { 'Password123!' }
2188
+ password_confirmation { 'Password123!' }
2189
+ full_name { Faker::Name.full_name }
2190
+ confirmed_at { Time.current }
2191
+ role { 'reader' }
2192
+
2193
+ trait :admin { role { 'admin' } }
2194
+ trait :author { role { 'author' } }
2195
+ trait :unconfirmed { confirmed_at { nil } }
2196
+ end
2197
+ end
2198
+ ```
2199
+
2200
+ ```ruby
2201
+ # spec/factories/posts.rb
2202
+ FactoryBot.define do
2203
+ factory :post do
2204
+ association :user, factory: [:user, :author]
2205
+ association :category
2206
+ status { 'draft' }
2207
+
2208
+ # Mobility translatable attributes
2209
+ trait :with_translations do
2210
+ after(:build) do |post|
2211
+ I18n.available_locales.each do |locale|
2212
+ Mobility.with_locale(locale) do
2213
+ post.title = Faker::Lorem.sentence(word_count: 4)
2214
+ post.slug = post.title.parameterize
2215
+ end
2216
+ end
2217
+ end
2218
+ end
2219
+
2220
+ trait :published do
2221
+ status { 'published' }
2222
+ published_at { 1.hour.ago }
2223
+ end
2224
+ end
2225
+ end
2226
+ ```
2227
+
2228
+ ### 10.3 Request Specs — API
2229
+
2230
+ ```ruby
2231
+ # spec/requests/api/v1/posts_spec.rb
2232
+ RSpec.describe 'API v1 Posts', type: :request do
2233
+ let(:user) { create(:user, :author) }
2234
+ let(:posts) { create_list(:post, 3, :published, :with_translations, user: user) }
2235
+
2236
+ describe 'GET /api/v1/posts' do
2237
+ it 'returns published posts in default locale (en)' do
2238
+ posts
2239
+ get '/api/v1/posts', headers: { 'Accept-Language' => 'en' }
2240
+
2241
+ expect(response).to have_http_status(:ok)
2242
+ json = JSON.parse(response.body)
2243
+ expect(json.length).to eq(3)
2244
+ end
2245
+
2246
+ it 'returns Vietnamese titles when locale=vi' do
2247
+ post_vi = create(:post, :published, :with_translations, user: user)
2248
+ get '/api/v1/posts', params: { locale: 'vi' }
2249
+
2250
+ json = JSON.parse(response.body)
2251
+ # Kiểm tra title là tiếng Việt (không phải tiếng Anh)
2252
+ expect(json.first['title']).to be_present
2253
+ end
2254
+ end
2255
+
2256
+ describe 'POST /api/v1/auth/sign_in' do
2257
+ it 'returns JWT token on valid credentials' do
2258
+ post '/api/v1/auth/sign_in',
2259
+ params: { user: { email: user.email, password: 'Password123!' } }
2260
+
2261
+ expect(response).to have_http_status(:ok)
2262
+ expect(response.headers['Authorization']).to match(/Bearer .+/)
2263
+ end
2264
+
2265
+ it 'returns 401 on invalid credentials' do
2266
+ post '/api/v1/auth/sign_in',
2267
+ params: { user: { email: user.email, password: 'wrong' } }
2268
+
2269
+ expect(response).to have_http_status(:unauthorized)
2270
+ end
2271
+ end
2272
+ end
2273
+ ```
2274
+
2275
+ ### 10.4 Model Specs
2276
+
2277
+ ```ruby
2278
+ # spec/models/post_spec.rb
2279
+ RSpec.describe Post, type: :model do
2280
+ it { is_expected.to belong_to(:user) }
2281
+ it { is_expected.to belong_to(:category) }
2282
+ it { is_expected.to have_many(:tags).through(:post_tags) }
2283
+ it { is_expected.to validate_inclusion_of(:status).in_array(Post::STATUSES) }
2284
+
2285
+ describe 'scopes' do
2286
+ it '.published returns only published posts with published_at in the past' do
2287
+ create(:post, :published)
2288
+ create(:post, status: 'draft')
2289
+
2290
+ expect(Post.published.count).to eq(1)
2291
+ end
2292
+ end
2293
+
2294
+ describe 'callbacks' do
2295
+ it 'enqueues PublishPostJob when scheduled_at changes' do
2296
+ post = create(:post, status: 'scheduled', scheduled_at: 1.hour.from_now)
2297
+ expect(PublishPostJob).to have_been_enqueued.with(post.id)
2298
+ end
2299
+ end
2300
+ end
2301
+ ```
2302
+
2303
+ ### ✅ Checklist Giai Đoạn 10
2304
+
2305
+ - [ ] `bundle exec rspec` passes toàn bộ
2306
+ - [ ] `SimpleCov` báo coverage ≥ 90%
2307
+ - [ ] Không có real HTTP call ra ngoài trong test (WebMock enforce)
2308
+ - [ ] `GET /api/v1/health` trả về `status: ok` trên production
2309
+ - [ ] CI pipeline chạy tự động khi push code (GitHub Actions / GitLab CI)
2310
+
2311
+ ---
2312
+
2313
+ ---
2314
+
2315
+ ## 13. GitHub Actions CI/CD {#ci-cd}
2316
+
2317
+ **Mục tiêu:** Chạy test tự động mỗi khi push, enforce coverage ≥ 90%.
2318
+
2319
+ ```yaml
2320
+ # .github/workflows/ci.yml
2321
+ name: CI
2322
+
2323
+ on:
2324
+ push:
2325
+ branches: [main, develop]
2326
+ pull_request:
2327
+ branches: [main]
2328
+
2329
+ jobs:
2330
+ test:
2331
+ runs-on: ubuntu-latest
2332
+
2333
+ services:
2334
+ redis:
2335
+ image: redis:7-alpine
2336
+ ports: ['6379:6379']
2337
+ options: >-
2338
+ --health-cmd "redis-cli ping"
2339
+ --health-interval 10s
2340
+ --health-timeout 5s
2341
+ --health-retries 5
2342
+
2343
+ env:
2344
+ RAILS_ENV: test
2345
+ REDIS_URL: redis://localhost:6379/0
2346
+ DEVISE_JWT_SECRET_KEY: test_secret_key_for_ci_only
2347
+ CLOUDINARY_CLOUD_NAME: test
2348
+ CLOUDINARY_API_KEY: test
2349
+ CLOUDINARY_API_SECRET: test
2350
+
2351
+ steps:
2352
+ - name: Checkout code
2353
+ uses: actions/checkout@v4
2354
+
2355
+ - name: Set up Ruby
2356
+ uses: ruby/setup-ruby@v1
2357
+ with:
2358
+ ruby-version: .ruby-version
2359
+ bundler-cache: true
2360
+
2361
+ - name: Setup database
2362
+ run: |
2363
+ bundle exec rails db:create
2364
+ bundle exec rails db:schema:load
2365
+
2366
+ - name: Run RuboCop
2367
+ run: bundle exec rubocop --parallel
2368
+
2369
+ - name: Run tests
2370
+ run: bundle exec rspec --format progress
2371
+
2372
+ - name: Check coverage
2373
+ run: |
2374
+ cat coverage/.last_run.json
2375
+ ruby -e "
2376
+ require 'json'
2377
+ result = JSON.parse(File.read('coverage/.last_run.json'))
2378
+ coverage = result['result']['line']
2379
+ abort('Coverage #{coverage}% < 90%!') if coverage < 90
2380
+ "
2381
+
2382
+ - name: Upload coverage report
2383
+ uses: actions/upload-artifact@v4
2384
+ if: always()
2385
+ with:
2386
+ name: coverage-report
2387
+ path: coverage/
2388
+ ```
2389
+
2390
+ > **Thêm `.ruby-version` vào root project:**
2391
+ > ```
2392
+ > 3.3.0
2393
+ > ```
2394
+
2395
+ ### ✅ Checklist CI/CD
2396
+
2397
+ - [ ] `.github/workflows/ci.yml` tồn tại và valid YAML
2398
+ - [ ] Push lên branch → GitHub Actions chạy tự động
2399
+ - [ ] Test fail → CI fail, không merge được
2400
+ - [ ] Coverage < 90% → CI fail
2401
+ - [ ] RuboCop offense → CI fail
2402
+
2403
+ ---
2404
+
2405
+ ## 14. Phụ Lục {#phu-luc}
2406
+
2407
+ ### ERD Tóm Tắt
2408
+
2409
+ ```
2410
+ User ──── Post ──── PostTranslation (locale, title, slug)
2411
+ │ └─── ActionTextRichText (content_en, content_vi, ...)
2412
+ │ └─── SlideshowAsset (cloudinary_public_id, position)
2413
+ │ └─── Comment (body, deleted_at)
2414
+ │ └─── Reaction (kind, user_id)
2415
+ │ └─── PostTag ── Tag
2416
+ └─── Category
2417
+ Setting (key, value JSONB, category)
2418
+ JwtDenylist (jti, expired_at)
2419
+ PaperTrail::Version (audit log)
2420
+ ```
2421
+
2422
+ ### Dependency Map — Thứ Tự File Quan Trọng
2423
+
2424
+ ```
2425
+ config/initializers/
2426
+ ├── cloudinary.rb ← cần ENV vars
2427
+ ├── devise.rb ← cần devise-jwt
2428
+ ├── rack_attack.rb ← cần Redis + Setting model + BlockedRequestLog model
2429
+ ├── mobility.rb ← cần trước khi load models
2430
+ └── action_mailer.rb ← cần Setting model
2431
+
2432
+ app/models/
2433
+ ├── setting.rb ← cần trước rack_attack.rb initializer
2434
+ ├── blocked_request_log.rb ← cần trước rack_attack.rb initializer
2435
+ ├── user.rb ← cần devise + jwt_denylist
2436
+ ├── post.rb ← cần mobility + friendly_id + discard
2437
+ ├── category.rb ← cần friendly_id
2438
+ ├── tag.rb ← cần friendly_id
2439
+ └── comment.rb ← cần discard
2440
+
2441
+ app/jobs/
2442
+ ├── publish_post_job.rb
2443
+ ├── rename_cloudinary_assets_job.rb
2444
+ ├── cloudinary_housekeeping_job.rb
2445
+ └── admin_notification_job.rb
2446
+
2447
+ app/mailers/
2448
+ ├── admin_mailer.rb
2449
+ └── interceptors/smtp_selector_interceptor.rb ← cần Setting model
2450
+
2451
+ app/middleware/
2452
+ └── maintenance_mode.rb ← cần Setting model (qua cache)
2453
+
2454
+ app/controllers/admin/
2455
+ ├── admin_controller.rb ← base controller cho mọi admin controllers
2456
+ ├── settings_controller.rb
2457
+ ├── audit_logs_controller.rb
2458
+ └── slideshow_assets_controller.rb
2459
+ ```
2460
+
2461
+ ### Lệnh Hay Dùng
2462
+
2463
+ ```bash
2464
+ # Chạy dev server
2465
+ bundle exec rails s
2466
+ bundle exec sidekiq
2467
+
2468
+ # Migrations
2469
+ rails db:migrate
2470
+ rails db:seed
2471
+
2472
+ # Xem jobs trong Sidekiq Web UI
2473
+ # Thêm vào routes.rb:
2474
+ # require 'sidekiq/web'
2475
+ # mount Sidekiq::Web => '/sidekiq' # Nhớ bảo vệ bằng authenticate
2476
+
2477
+ # Test
2478
+ bundle exec rspec
2479
+ bundle exec rspec spec/models/
2480
+ bundle exec rspec spec/requests/api/
2481
+
2482
+ # Coverage report
2483
+ open coverage/index.html
2484
+
2485
+ # Rubocop
2486
+ bundle exec rubocop --autocorrect-all
2487
+ ```
docs/rails_blog_management_requirement.en.md ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # **Rails Blog Management Project (Enterprise & API Ready)**
2
+
3
+ ## **Overview**
4
+
5
+ Plan to build a **Full-stack Rails 8** application integrated with an **API (initial version, URL set to** `**/api/v1**`**)**. The system supports professional content management, multi-layer security with a dual-defense strategy, and a comprehensive system configuration admin page (Settings).
6
+
7
+ The system provides deep multilingual support with a clear hierarchy: Backend (Admin/System) supports English and Vietnamese; while Content (Posts/Categories/Tags) and Frontend support 7 languages: English, Vietnamese, Russian, Japanese, Korean, Thai, German.
8
+
9
+ Main stack: **Ruby on Rails 8**, **Hotwire (Turbo/Stimulus)**, **Cloudinary**, **Devise + JWT**, **Redis (for Sidekiq & Caching)**, **Mobility (for i18n Data)**.
10
+
11
+ ## **Your Preferences & Advanced Features**
12
+
13
+ * **Auth:** Devise (use all modules) + JWT (for API/third-parties like Vue.js).
14
+ * **SEO & UX:** Multilingual post content, language-specific Slug URLs, advanced Image Slideshow/Carousel, Publish Scheduling.
15
+ * **Engagement:** Real-time Reactions, Soft-delete Comments, Unique View tracking.
16
+ * **System Control:** Settings page to dynamically configure Rate Limit, Media Size, and SMTP (supports multi-provider Load Balancing).
17
+
18
+ ## **Implementation Plan**
19
+
20
+ ### **Step 1: Authentication & Authorization (Full Devise & JWT)**
21
+
22
+ **Approach:** Implement a centralized identity system using **Devise** with maximum security configuration, combined with **JWT** to serve API connections from third-party apps.
23
+
24
+ #### **1. Details of Devise Modules to implement:**
25
+
26
+ | **Function Group** | **Module** | **Detailed Description & Business Logic** |
27
+ | --- | --- | --- |
28
+ | **Core** | `database_authenticatable` | Passwords encrypted with BCrypt. Securely stored in DB. |
29
+ | | `registerable` | Handles registration, editing information, and account cancellation. |
30
+ | | `validatable` | Validates email format, password strength (min 6-8 characters). |
31
+ | **Security** | `confirmable` | Sends activation email. Activation link expires after 24h. |
32
+ | | `lockable` | Automatically locks account after X failed attempts (X configurable in Settings). |
33
+ | | `timeoutable` | Expires session if user is inactive for 30–60 minutes. |
34
+ | **Experience** | `recoverable` | Secure password recovery via email. |
35
+ | | `rememberable` | Uses Token in Cookie to persist browser login. |
36
+ | | `trackable` | Records: `sign_in_count`, `current_sign_in_at`, `current_sign_in_ip`. |
37
+ | **Extensions** | `omniauthable` | Ready for future Google/Facebook login integration. |
38
+ | | `jwt_authenticatable` | Use `devise-jwt` to issue Bearer Tokens for API apps. |
39
+
40
+ #### **2. JWT Strategy & Token Revocation:**
41
+
42
+ * **Denylist Strategy:** Use a `jwt_denylist` table to store revoked tokens (when user logs out or changes password), preventing reuse of old tokens.
43
+ * **Payload:** Token contains `user_id` and expiration time (`exp`).
44
+
45
+ #### **3. Authorization (Authorization Layer):**
46
+
47
+ * **Admin:** Full system administration rights, access to **Settings** page, manage all Users and Posts.
48
+ * **Author:** Can create posts, manage their own posts, view their own view statistics.
49
+ * **Reader:** Default role. Can read, comment, and give reactions.
50
+ * **Mechanism:** Use `Pundit` or `CanCanCan` to precisely define permissions for each Model Action.
51
+
52
+ #### **4. Additional User Information:**
53
+
54
+ * Integrate **Active Storage** with **Cloudinary** to store Avatars.
55
+ * Automatically resize Avatar images to a standard size (e.g., 200x200) on upload.
56
+
57
+ ### **Step 2: Advanced Multilingual Post Management**
58
+
59
+ * **Multilingual Data:** Use the `mobility` gem to translate Title (`title`) and Content (`content`). Visitors can switch among 7 languages (EN, VI, RU, JA, KO, TH, DE) and read the corresponding content.
60
+ * **SEO Localization:** Language-specific Slug URLs (e.g., English: `/en/posts/hello`, Vietnamese: `/vi/posts/xin-chao`). Support `hreflang` tags for international SEO.
61
+ * **Workflow:** Draft -> Pending -> Scheduled -> Published.
62
+
63
+ ### **Step 3: Cloudinary Storage & Optimization (Detailed)**
64
+
65
+ **In-depth cloud storage solution analysis:**
66
+
67
+ 1. **Upload Architecture (Direct Signed Uploads):**
68
+ * **Process:** Client requests a "Signature" from the Rails Server -> Client uploads the image directly to Cloudinary -> Cloudinary returns Metadata -> Client sends Metadata back to Rails to persist.
69
+ * **Benefits:** Offloads Rails server entirely (no RAM/CPU for image bytes), avoids timeouts when uploading large files.
70
+ 2. **Integrate Cloudinary Media Library SDK:**
71
+ * Allow users to open a Cloudinary library window inside the Admin UI to pick previously uploaded images or images from other posts.
72
+ * Synchronize `public_id` into the Rails database for centralized asset management.
73
+ 3. **Resource Organization Strategy (Dynamic Resource Mapping):**
74
+ * **Folder hierarchy:** All assets are categorized by purpose and timeline to optimize management:
75
+ * **Thumbnail:** `thumb/{month-year}/{post-id}.{format}` (For post thumbnail).
76
+ * **Gallery/Slideshow:** `gallery/{month-year}/{post-id}/{position}.{format}` (e.g., `01.jpg`, `02.png`...).
77
+ * **SEO-Friendly Naming & Synchronization Rules:** Automatically rename files before upload based on the post title (slug) to improve SEO.
78
+ * **Handling risks when title changes:** Launch a Background Job (Sidekiq) when slug changes. This Job will: 1. Call Cloudinary API to rename images. 2. Scan `action_text_rich_texts` content to find/replace old image URLs with new ones to avoid broken images in posts.
79
+ * **Operational benefits:** This structure helps Admins easily bulk-delete all assets of a post via the Cloudinary API.
80
+ 4. **Dynamic Transformations Optimization:**
81
+ * **f_auto (Auto Format):** Automatically convert image format based on browser (WebP for Chrome, AVIF).
82
+ * **q_auto (Auto Quality):** Smartly compress images at optimal quality.
83
+ 5. **Housekeeping (Resource Cleanup):**
84
+ * Implement Sidekiq Jobs to periodically scan and delete "orphaned" images.
85
+
86
+ ### **Step 4: Multi-layer Security & Dynamic Rate Limiting**
87
+
88
+ **Dual-defense strategy against automated attacks (Bots) and resource abuse:**
89
+
90
+ 1. **Layer 0: Brute-force protection (Rack::Attack Middleware):**
91
+ * Block login brute-force, vulnerability scanning, and light DDoS using Redis. Return `429 Too Many Requests`.
92
+ 2. **Layer 1: User-level behavior limiting (Rails 8 RateLimiting):**
93
+ * Apply at controller level for sensitive actions (`create_comment`, etc.). Return friendly Flash Messages in the user's language.
94
+ 3. **API-specific security:**
95
+ * IP Throttling and Whitelisting via Database configuration.
96
+ 4. **Monitoring & Alerts:**
97
+ * Log blocked IPs and send automatic alerts to Admin.
98
+
99
+ ### **Step 5: API v1 & Webhooks for Third Parties**
100
+
101
+ * Provide JSON routes under `/api/v1/`. Support JWT Revocation. JSON responses must automatically adapt according to language parameter (e.g., `?locale=de` for German).
102
+
103
+ ### **Step 6: Admin Dashboard & System Settings (Detailed Analysis)**
104
+
105
+ **Dynamic system control center — allows operational changes without deploy:**
106
+
107
+ 1. **Key-Value Store Architecture:**
108
+ * **Database:** Use a `settings` table with columns: `key`, `value` (JSONB for array configs), `value_type`, and `category`. Cache on Redis.
109
+ 2. **Dynamic SMTP & Email Management (Dynamic SMTP Load Balancing):**
110
+ * **Optimize Email Sending (Avoid Rate Limits):** Allow configuring multiple providers simultaneously (Postmark, SendPulse, AWS SES) stored as a JSONB array in Setting.
111
+ * **Distribution algorithm:** Implement an Interceptor that randomly (Random/Round-robin) selects a provider each time an email is sent.
112
+ * **Manual override:** Admin UI has a checkbox to force using a specific provider when others fail.
113
+ 3. **Media & Bandwidth Configuration:**
114
+ * Edit `thumbnail_width`, `slideshow_max_size` passed to Cloudinary.
115
+ 4. **Maintenance Mode:**
116
+ * Block regular user access, return multilingual 503 message, Admin can still operate normally.
117
+
118
+ ### **Step 7: Audit Log & Soft Delete**
119
+
120
+ * **Audit Log System:** Capture create/update/delete events on sensitive models, store `changes` as JSONB so Admins can trace and restore configurations easily.
121
+ * **Soft Delete:** Instead of SQL `DELETE`, use a `deleted_at` column for Comments and Posts. Support displaying "Comment hidden" and a Trash area for restoration.
122
+
123
+ ### **Step 8: Slideshow Tab Engine**
124
+
125
+ 1. **Structure:** `Post` has `has_many :slideshow_assets`.
126
+ 2. **UI:** Turbo Frames for upload and management without reload.
127
+ 3. **Sorting:** SortableJS with Stimulus for drag-and-drop position saving (`position`).
128
+
129
+ ### **Step 9: Multi-layer Caching Strategy**
130
+
131
+ 1. **Fragment Caching:** Combine `cache_key_with_version` and `I18n.locale` to avoid serving Vietnamese readers the English cached render.
132
+ 2. **Russian Doll Caching:** Nest caches for optimal speed.
133
+ 3. **Database Query Caching:** Use Eager Loading (`.includes`).
134
+
135
+ ### **Step 10: Testing & Health Checks**
136
+
137
+ 1. Integrate `simplecov` to ensure Code Coverage.
138
+ 2. Mock Cloudinary requests using `WebMock`.
139
+ 3. `/health` API returns JSON status of Sidekiq, Redis, and Postgres.
140
+
141
+ ## **Architecture (Detailed Analysis)**
142
+
143
+ **Entity Relationship Diagram (ERD) and data storage strategy:**
144
+
145
+ 1. **User & Identity Layer (Full Devise Modules):**
146
+ * Full configuration with JWT (`jti`) and Avatar field (`avatar_public_id`).
147
+ 2. **Multilingual Content Layer (7 languages for Frontend/Content):**
148
+ * `PostTranslation` table: stores `title`, `slug` for 7 locales (en, vi, ru, ja, ko, th, de).
149
+ * **ActionText RichTexts:** Automatically support I18n to store `content` separately.
150
+ 3. **Interaction & System Layer:**
151
+ * Unique Index structure for Reactions.
152
+ * `value` column as JSON in Setting table to support array config for Multi-SMTP.
153
+
154
+ ```plaintext
155
+ erDiagram
156
+ User {
157
+ int id
158
+ string email
159
+ string encrypted_password
160
+ string role
161
+ string full_name
162
+ string avatar_public_id "Cloudinary Storage"
163
+ string reset_password_token
164
+ datetime reset_password_sent_at
165
+ datetime remember_created_at
166
+ int sign_in_count
167
+ datetime current_sign_in_at
168
+ datetime last_sign_in_at
169
+ string current_sign_in_ip
170
+ string last_sign_in_ip
171
+ string confirmation_token
172
+ datetime confirmed_at
173
+ datetime confirmation_sent_at
174
+ string unconfirmed_email
175
+ int failed_attempts
176
+ string unlock_token
177
+ datetime locked_at
178
+ string jti "JWT ID"
179
+ }
180
+ Post {
181
+ int id
182
+ string cloudinary_public_id "Main Thumbnail"
183
+ int user_id
184
+ int category_id
185
+ int comments_count "Counter Cache"
186
+ int impressions_count "Unique View tracking"
187
+ datetime published_at
188
+ }
189
+ PostTranslation {
190
+ int id
191
+ int post_id
192
+ string locale "7 Locales: en, vi, ru, ja, ko, th, de"
193
+ string title
194
+ string slug
195
+ }
196
+ ActionTextRichText {
197
+ int id
198
+ string record_type
199
+ int record_id
200
+ string name "content_en, content_vi, content_ja..."
201
+ text body
202
+ }
203
+ Category {
204
+ int id
205
+ string name
206
+ string slug
207
+ }
208
+ Tag {
209
+ int id
210
+ string name
211
+ string slug
212
+ }
213
+ PostTag {
214
+ int post_id
215
+ int tag_id
216
+ }
217
+ SlideshowAsset {
218
+ int id
219
+ string cloudinary_public_id
220
+ int position
221
+ int post_id
222
+ }
223
+ Comment {
224
+ int id
225
+ text body
226
+ datetime deleted_at "Soft Delete"
227
+ int user_id
228
+ int post_id
229
+ }
230
+ Reaction {
231
+ int id
232
+ string kind "like|heart|etc"
233
+ int user_id
234
+ int post_id
235
+ }
236
+ Setting {
237
+ int id
238
+ string key
239
+ jsonb value "Support Array for SMTP Configs"
240
+ string category
241
+ }
242
+ JwtDenylist {
243
+ int id
244
+ string jti
245
+ datetime expired_at
246
+ }
247
+
248
+ User ||--o{ Post : "writes"
249
+ User ||--o{ Comment : "writes"
250
+ User ||--o{ Reaction : "gives"
251
+ Category ||--o{ Post : "categorizes"
252
+ Post ||--o{ PostTranslation : "translates title & slug"
253
+ Post ||--o{ ActionTextRichText : "translates rich content"
254
+ Post ||--o{ SlideshowAsset : "has"
255
+ Post ||--o{ Comment : "has"
256
+ Post ||--o{ Reaction : "receives"
257
+ Post ||--o{ PostTag : "has"
258
+ Tag ||--o{ PostTag : "categorizes"
259
+
260
+ ```
261
+
262
+ ## **Optimization Checklist & Technical Analysis**
263
+
264
+ ### **1. Multilingual Engine (Mobility & I18n)**
265
+
266
+ * **Integrate Mobility Gem:**
267
+ * **Analysis:** Use Translation Table Backend for 7 content languages (EN, VI, RU, JA, KO, TH, DE). Mobility separates translatable strings (`title`, `slug`) into the `post_translations` table.
268
+ * **Backend vs Frontend language hierarchy:**
269
+ * **Analysis:** `I18n.available_locales = [:en, :vi, :ru, :ja, :ko, :th, :de]`. Admin UI only provides YAML translation files for `[:en, :vi]`. Frontend provides all 7 languages.
270
+ * **Admin language management UI:**
271
+ * **Analysis:** On the post create/edit page, design a "Tabs" component (with Stimulus). Admin enters Vietnamese in Tab 1, switches to English/Japanese/Korean tabs to enter without reloading the page.
272
+
273
+ ### **2. Cloudinary Integration**
274
+
275
+ * **Protect ActionText assets when renaming images (Slug change):**
276
+ * **Solution:** If a Cloudinary file is renamed, a Background Job must run regex `gsub` to replace old URL strings with new URL strings in the `ActionTextRichText` model to avoid 404 broken images.
277
+
278
+ ### **3. Multi-Provider SMTP (Enterprise Load Balancing)**
279
+
280
+ * **Email infrastructure design:**
281
+ * **Solution:** Store a JSON Array of providers in `Setting.smtp_providers`. Initialize an `ActionMailer::Interceptor`, hook into `before_deliver` to override `message.delivery_method.settings` based on the Random/Round-robin algorithm result.
docs/rails_blog_management_requirement.vi.md ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # **Dự án Rails Blog Management (Enterprise & API Ready)**
2
+
3
+ ## **Overview**
4
+
5
+ Kế hoạch xây dựng ứng dụng **Full-stack Rails 8** tích hợp **API (phiên bản đầu tiên, đặt url là** `**/api/v1**`**)**. Hệ thống hỗ trợ quản lý nội dung chuyên nghiệp, bảo mật đa lớp với chiến lược phòng thủ kép, và trang quản trị cấu hình hệ thống (Settings) toàn diện.
6
+
7
+ Hệ thống hỗ trợ đa ngôn ngữ chuyên sâu với phân cấp rõ rệt: Backend (Admin/System) hỗ trợ Tiếng Anh và Tiếng Việt; trong khi Nội dung (Bài viết/Danh mục/Tags) và Frontend hỗ trợ 7 ngôn ngữ: Anh, Việt, Nga, Nhật, Hàn, Thái, Đức.
8
+
9
+ Stack chính: **Ruby on Rails 8**, **Hotwire (Turbo/Stimulus)**, **Cloudinary**, **Devise + JWT**, **Redis (cho Sidekiq & Caching)**, **Mobility (cho i18n Data)**.
10
+
11
+ ## **Your Preferences & Advanced Features**
12
+
13
+ * **Auth:** Devise (Sử dụng đầy đủ các modules) + JWT (cho API/Bên thứ 3 như Vue.js).
14
+ * **SEO & UX:** Đa ngôn ngữ cho nội dung bài viết, Slug URL riêng cho từng ngôn ngữ, Image Slideshow/Carousel chuyên sâu, Publish Scheduling.
15
+ * **Engagement:** Real-time Reactions, Soft-delete Comments, Unique View tracking.
16
+ * **System Control:** Trang Setting tùy chỉnh động Rate Limit, Media Size, và SMTP (hỗ trợ Load Balancing đa nhà cung cấp).
17
+
18
+ ## **Implementation Plan**
19
+
20
+ ### **Step 1: Xác thực & Phân quyền người dùng (Full Devise & JWT)**
21
+
22
+ **Hướng xử lý:** Triển khai hệ thống định danh tập trung bằng **Devise** với cấu hình tối đa sức mạnh bảo mật, kết hợp cùng **JWT** để phục vụ các kết nối API từ bên thứ ba.
23
+
24
+ #### **1\. Chi tiết các Modules Devise triển khai:**
25
+
26
+ | **Nhóm chức năng** | **Module** | **Mô tả chi tiết & Nghiệp vụ** |
27
+ | --- | --- | --- |
28
+ | **Cơ bản** | `database_authenticatable` | Mã hóa mật khẩu bằng BCrypt. Lưu trữ an toàn trong DB. |
29
+ | | `registerable` | Xử lý đăng ký, sửa đổi thông tin và hủy tài khoản. |
30
+ | | `validatable` | Kiểm tra định dạng email, độ mạnh mật khẩu (min 6-8 ký tự). |
31
+ | **Bảo mật** | `confirmable` | Gửi email kích hoạt. Link kích hoạt hết hạn sau 24h. |
32
+ | | `lockable` | Tự động khóa tài khoản sau X lần nhập sai (X tùy chỉnh ở Settings). |
33
+ | | `timeoutable` | Hủy session nếu người dùng không tương tác trong 30-60 phút. |
34
+ | **Trải nghiệm** | `recoverable` | Cơ chế lấy lại mật khẩu qua email an toàn. |
35
+ | | `rememberable` | Sử dụng Token trong Cookie để duy trì đăng nhập qua trình duyệt. |
36
+ | | `trackable` | Ghi lại: `sign_in_count`, `current_sign_in_at`, `current_sign_in_ip`. |
37
+ | **Mở rộng** | `omniauthable` | Sẵn sàng cho tích hợp đăng nhập bằng Google/Facebook trong tương lai. |
38
+ | | `jwt_authenticatable` | Sử dụng `devise-jwt` để cấp phát Bearer Token cho các ứng dụng API. |
39
+
40
+ #### **2\. Chiến lược JWT & Token Revocation:**
41
+
42
+ * **Denylist Strategy:** Sử dụng bảng `jwt_denylist` để lưu trữ các token bị thu hồi (khi người dùng logout hoặc đổi mật khẩu), ngăn chặn việc tái sử dụng token cũ.
43
+ * **Payload:** Token chứa `user_id` và thời gian hết hạn (`exp`).
44
+
45
+ #### **3\. Phân quyền (Authorization Layer):**
46
+
47
+ * **Admin:** Toàn quyền quản trị hệ thống, truy cập trang **Settings**, quản lý mọi User và Bài viết.
48
+ * **Author:** Được tạo bài viết, quản lý bài viết của chính mình, xem thống kê lượt xem riêng.
49
+ * **Reader:** Quyền mặc định. Được đọc, bình luận, và thả cảm xúc (Reaction).
50
+ * **Cơ chế:** Sử dụng thư viện `Pundit` hoặc `CanCanCan` để định nghĩa chính xác quyền hạn cho từng Model Action.
51
+
52
+ #### **4\. Thông tin User bổ sung:**
53
+
54
+ * Tích hợp **Active Storage** with **Cloudinary** để lưu trữ Avatar.
55
+ * Tự động resize ảnh Avatar về kích thước tiêu chuẩn (ví dụ: 200x200) khi upload.
56
+
57
+ ### **Step 2: Quản lý bài viết Đa ngôn ngữ (Nâng cao)**
58
+
59
+ * **Multilingual Data:** Sử dụng gem `mobility` để dịch Tiêu đề (`title`) và Nội dung (`content`). Khách truy cập có thể chuyển đổi 7 ngôn ngữ (EN, VI, RU, JA, KO, TH, DE) và đọc nội dung tương ứng.
60
+ * **SEO Localization:** Slug URL độc lập cho từng ngôn ngữ (VD tiếng Anh: `/en/posts/hello`, tiếng Việt: `/vi/posts/xin-chao`). Hỗ trợ thẻ `hreflang` cho SEO quốc tế.
61
+ * **Workflow:** Draft -> Pending -> Scheduled -> Published.
62
+
63
+ ### **Step 3: Hệ thống lưu trữ & Tối ưu hóa Cloudinary (Chi tiết)**
64
+
65
+ **Phân tích giải pháp lưu trữ đám mây chuyên sâu:**
66
+
67
+ 1. **Kiến trúc Tải lên (Direct Signed Uploads):**
68
+ * **Quy trình:** Client yêu cầu một "Signature" từ Server Rails -> Client tải ảnh trực tiếp lên Cloudinary -> Cloudinary trả về Metadata -> Client gửi Metadata về Rails để lưu trữ.
69
+ * **Lợi ích:** Giảm tải hoàn toàn cho máy chủ Rails (không tốn RAM/CPU xử lý byte ảnh), tránh lỗi timeout khi upload file lớn.
70
+ 2. **Tích hợp Cloudinary Media Library SDK:**
71
+ * Cho phép người dùng mở một cửa sổ thư viện Cloudinary ngay trong giao diện Admin để chọn các ảnh đã tải lên từ trước hoặc từ các bài viết khác.
72
+ * Đồng bộ hóa `public_id` vào cơ sở dữ liệu Rails để quản lý tài nguyên tập trung.
73
+ 3. **Chiến lược tổ chức tài nguyên (Dynamic Resource Mapping):**
74
+ * **Phân cấp thư mục:** Toàn bộ tài nguyên được phân loại theo mục đích và dòng thời gian để tối ưu hóa việc quản lý:
75
+ * **Thumbnail:** `thumb/{tháng-năm}/{mã-bài-viết}.{định-dạng}` (Dành cho ảnh đại diện bài viết).
76
+ * **Gallery/Slideshow:** `gallery/{tháng-năm}/{mã-bài-viết}/{vị-trí-số}.{định-dạng}` (Ví dụ: `01.jpg`, `02.png`...).
77
+ * **Quy tắc đặt tên (SEO-Friendly Naming) & Synchronization:** Tự động đổi tên file (Rename) trước khi upload dựa trên tiêu đề bài viết (slug) để tăng điểm SEO.
78
+ * **Xử lý rủi ro khi đổi tiêu đề:** Cần khởi chạy một Background Job (Sidekiq) khi slug thay đổi. Job này sẽ: 1. Gọi API đổi tên ảnh trên Cloudinary. 2. Quét (Scan) qua nội dung `action_text_rich_texts` để tìm/thay thế (replace) các đường dẫn ảnh cũ thành đường dẫn ảnh mới, tránh hiện tượng vỡ ảnh trên bài viết.
79
+ * **Lợi ích vận hành:** Cấu trúc này giúp Admin dễ dàng dọn dẹp (Bulk delete) toàn bộ tài nguyên của một bài viết thông qua Cloudinary API.
80
+ 4. **Tối ưu hóa hiển thị động (Dynamic Transformations):**
81
+ * **f\_auto (Auto Format):** Tự động chuyển đổi định dạng ảnh dựa trên trình duyệt (WebP cho Chrome, AVIF).
82
+ * **q\_auto (Auto Quality):** Nén ảnh thông minh ở mức tối ưu nhất.
83
+ 5. **Quản lý Tài nguyên sạch (Housekeeping):**
84
+ * Triển khai Sidekiq Job để định kỳ quét và xóa các ảnh "mồ côi".
85
+
86
+ ### **Step 4: Bảo mật đa tầng & Dynamic Rate Limiting**
87
+
88
+ **Chiến lược phòng thủ kép chống tấn công tự động (Bots) và lạm dụng tài nguyên:**
89
+
90
+ 1. **Tầng 0: Chống tấn công thô bạo (Rack::Attack Middleware):**
91
+ * Chặn Brute-force đăng nhập, quét lỗ hổng và DDoS nhẹ bằng Redis. Trả về mã lỗi `429 Too Many Requests`.
92
+ 2. **Tầng 1: Giới hạn hành vi theo User (Rails 8 RateLimiting):**
93
+ * Áp dụng tại controller cho các hành động nhạy cảm (`create_comment`, v.v.). Trả về Flash Message thân thiện bằng ngôn ngữ của người dùng.
94
+ 3. **Bảo mật API chuyên sâu:**
95
+ * IP Throttling và Whitelisting thông qua cấu hình Database.
96
+ 4. **Giám sát & Cảnh báo:**
97
+ * Ghi log các IP bị chặn và gửi cảnh báo tự động cho Admin.
98
+
99
+ ### **Step 5: API v1 & Webhooks cho bên thứ ba**
100
+
101
+ * Cung cấp JSON định tuyến theo `/api/v1/`. Hỗ trợ JWT Revocation. Định dạng JSON trả về phải tự động điều chỉnh theo tham số ngôn ngữ (Ví dụ: `?locale=de` cho tiếng Đức).
102
+
103
+ ### **Step 6: Admin Dashboard & System Settings (Phân tích chi tiết)**
104
+
105
+ **Trung tâm điều khiển hệ thống động - Cho phép thay đổi vận hành không cần deploy:**
106
+
107
+ 1. **Kiến trúc Key-Value Store:**
108
+ * **Database:** Sử dụng bảng `settings` với các cột: `key`, `value` (dạng JSONB cho các config mảng), `value_type`, và `category`. Cache trên Redis.
109
+ 2. **Quản lý SMTP & Email động (Dynamic SMTP Load Balancing):**
110
+ * **Tối ưu gửi Email (Chống Rate Limit):** Cho phép cấu hình đồng thời đa nhà cung cấp (Postmark, SendPulse, AWS SES) được lưu trữ dưới dạng mảng JSONB trong Setting.
111
+ * **Thuật toán phân phối:** Triển khai một Interceptor chọn ngẫu nhiên (Random/Round-robin) nhà cung cấp mỗi khi gửi mail.
112
+ * **Điều khiển thủ công:** Giao diện Admin có checkbox để force (bắt buộc) sử dụng một nhà cung cấp cụ thể trong trường hợp các nhà cung cấp khác bị lỗi.
113
+ 3. **Cấu hình Media & Băng thông:**
114
+ * Chỉnh sửa `thumbnail_width`, `slideshow_max_size` truyền vào Cloudinary.
115
+ 4. **Maintenance Mode (Chế độ bảo trì):**
116
+ * Chặn truy cập user thường, trả về thông báo 503 đa ngôn ngữ, Admin vẫn thao tác bình thường.
117
+
118
+ ### **Step 7: Audit Log & Soft Delete**
119
+
120
+ * **Hệ thống Audit Log:** Bắt sự kiện tạo/sửa/xóa trên các model nhạy cảm, lưu lại `changes` bằng dạng JSONB để Admin dễ dàng truy vết và phục hồi cấu hình.
121
+ * **Soft Delete:** Thay vì `DELETE` SQL, sử dụng cột `deleted_at` cho Comments và Posts. Hỗ trợ hiển thị "Bình luận đã bị ẩn" và khu vực Thùng rác (Trash) để khôi phục.
122
+
123
+ ### **Step 8: Slideshow Tab Engine**
124
+
125
+ 1. **Cấu trúc:** `Post` có `has_many :slideshow_assets`.
126
+ 2. **Giao diện:** Turbo Frames để upload và quản lý không cần reload.
127
+ 3. **Sắp xếp:** SortableJS với Stimulus để kéo thả lưu vị trí (`position`).
128
+
129
+ ### **Step 9: Chiến lược Caching Đa tầng**
130
+
131
+ 1. **Fragment Caching:** Kết hợp `cache_key_with_version` và `I18n.locale` để tránh việc người dùng đọc tiếng Việt nhưng bị render cache của bản tiếng Anh.
132
+ 2. **Russian Doll Caching:** Lồng ghép cache cho tối ưu tốc độ.
133
+ 3. **Database Query Caching:** Sử dụng Eager Loading (`.includes`).
134
+
135
+ ### **Step 10: Kiểm thử & Health Checks**
136
+
137
+ 1. Tích hợp `simplecov` để đảm bảo độ phủ Code Coverage.
138
+ 2. Mocking Cloudinary request bằng `WebMock`.
139
+ 3. `/health` API trả về JSON trạng thái của Sidekiq, Redis và Postgres.
140
+
141
+ ## **Architecture (Phân tích chi tiết)**
142
+
143
+ **Mô hình quan hệ thực thể (ERD) và chiến lược lưu trữ dữ liệu:**
144
+
145
+ 1. **User & Identity Layer (Full Devise Modules):**
146
+ * Cấu hình đầy đủ với JWT (`jti`) và trường Avatar (`avatar_public_id`).
147
+ 2. **Content Layer Đa Ngôn Ngữ (7 ngôn ngữ cho Frontend/Nội dung):**
148
+ * Bảng `PostTranslation`: Lưu trữ `title`, `slug` cho 7 locale (en, vi, ru, ja, ko, th, de).
149
+ * **ActionText RichTexts**: Tự động hỗ trợ I18n để lưu trữ `content` riêng biệt.
150
+ 3. **Interaction & System Layer:**
151
+ * Cấu trúc Unique Index cho Reactions.
152
+ * Cột `value` dạng kiểu JSON trong bảng Setting để hỗ trợ config mảng cho Multi-SMTP.
153
+
154
+ ```plaintext
155
+ erDiagram
156
+ User {
157
+ int id
158
+ string email
159
+ string encrypted_password
160
+ string role
161
+ string full_name
162
+ string avatar_public_id "Cloudinary Storage"
163
+ string reset_password_token
164
+ datetime reset_password_sent_at
165
+ datetime remember_created_at
166
+ int sign_in_count
167
+ datetime current_sign_in_at
168
+ datetime last_sign_in_at
169
+ string current_sign_in_ip
170
+ string last_sign_in_ip
171
+ string confirmation_token
172
+ datetime confirmed_at
173
+ datetime confirmation_sent_at
174
+ string unconfirmed_email
175
+ int failed_attempts
176
+ string unlock_token
177
+ datetime locked_at
178
+ string jti "JWT ID"
179
+ }
180
+ Post {
181
+ int id
182
+ string cloudinary_public_id "Main Thumbnail"
183
+ int user_id
184
+ int category_id
185
+ int comments_count "Counter Cache"
186
+ int impressions_count "Unique View tracking"
187
+ datetime published_at
188
+ }
189
+ PostTranslation {
190
+ int id
191
+ int post_id
192
+ string locale "7 Locales: en, vi, ru, ja, ko, th, de"
193
+ string title
194
+ string slug
195
+ }
196
+ ActionTextRichText {
197
+ int id
198
+ string record_type
199
+ int record_id
200
+ string name "content_en, content_vi, content_ja..."
201
+ text body
202
+ }
203
+ Category {
204
+ int id
205
+ string name
206
+ string slug
207
+ }
208
+ Tag {
209
+ int id
210
+ string name
211
+ string slug
212
+ }
213
+ PostTag {
214
+ int post_id
215
+ int tag_id
216
+ }
217
+ SlideshowAsset {
218
+ int id
219
+ string cloudinary_public_id
220
+ int position
221
+ int post_id
222
+ }
223
+ Comment {
224
+ int id
225
+ text body
226
+ datetime deleted_at "Soft Delete"
227
+ int user_id
228
+ int post_id
229
+ }
230
+ Reaction {
231
+ int id
232
+ string kind "like|heart|etc"
233
+ int user_id
234
+ int post_id
235
+ }
236
+ Setting {
237
+ int id
238
+ string key
239
+ jsonb value "Support Array for SMTP Configs"
240
+ string category
241
+ }
242
+ JwtDenylist {
243
+ int id
244
+ string jti
245
+ datetime expired_at
246
+ }
247
+
248
+ User ||--o{ Post : "writes"
249
+ User ||--o{ Comment : "writes"
250
+ User ||--o{ Reaction : "gives"
251
+ Category ||--o{ Post : "categorizes"
252
+ Post ||--o{ PostTranslation : "translates title & slug"
253
+ Post ||--o{ ActionTextRichText : "translates rich content"
254
+ Post ||--o{ SlideshowAsset : "has"
255
+ Post ||--o{ Comment : "has"
256
+ Post ||--o{ Reaction : "receives"
257
+ Post ||--o{ PostTag : "has"
258
+ Tag ||--o{ PostTag : "categorizes"
259
+
260
+ ```
261
+
262
+ ## **Optimization Checklist & Technical Analysis**
263
+
264
+ ### **1\. Multilingual Engine (Mobility & I18n)**
265
+
266
+ * **Tích hợp Gem Mobility:**
267
+ * **Phân tích:** Sử dụng Translation Table Backend cho 7 ngôn ngữ nội dung (EN, VI, RU, JA, KO, TH, DE). Mobility tách biệt các chuỗi cần dịch (`title`, `slug`) sang bảng `post_translations`.
268
+ * **Phân cấp ngôn ngữ Backend vs Frontend:**
269
+ * **Phân tích:** `I18n.available_locales = [:en, :vi, :ru, :ja, :ko, :th, :de]`. Giao diện Admin chỉ cung cấp tệp translation YAML cho `[:en, :vi]`. Frontend thì cung cấp đủ cho 7 ngôn ngữ.
270
+ * **Giao diện quản trị ngôn ngữ (Admin UI):**
271
+ * **Phân tích:** Trong trang tạo/sửa Bài viết, thiết kế Component "Tabs" (bằng Stimulus). Admin nhập dữ liệu Tiếng Việt ở Tab 1, chuyển sang Tab Tiếng Anh/Nhật/Hàn tương ứng để nhập mà không cần load lại trang.
272
+
273
+ ### **2\. Cloudinary Integration**
274
+
275
+ * **Bảo vệ tài nguyên ActionText khi đổi tên Ảnh (Slug đổi):**
276
+ * **Giải pháp:** Nếu Cloudinary file đổi tên, Background Job bắt buộc phải thực thi regex `gsub` thay thế chuỗi URL cũ bằng chuỗi URL mới trong model `ActionTextRichText` để tránh lỗi vỡ hình 404.
277
+
278
+ ### **3\. Multi-Provider SMTP (Enterprise Load Balancing)**
279
+
280
+ * **Thiết kế hạ tầng Email:**
281
+ * **Giải pháp:** Lưu một JSON Array các nhà cung cấp vào `Setting.smtp_providers`. Khởi tạo một `ActionMailer::Interceptor`, hook vào `before_deliver` để override giá trị `message.delivery_method.settings` dựa trên kết quả thuật toán Random/Round-robin.
lib/coverage_baseline.rb ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "json"
5
+
6
+ module CoverageBaseline
7
+ Result = Data.define(:line, :branch)
8
+
9
+ def self.below?(current:, baseline:)
10
+ current.line < baseline.line || current.branch < baseline.branch
11
+ end
12
+
13
+ def self.load_baseline(path)
14
+ data = YAML.load_file(path, aliases: true)
15
+ unless data.is_a?(Hash) && data.key?("line") && data.key?("branch")
16
+ raise ArgumentError, "missing required coverage keys: 'line' and 'branch' in #{path}"
17
+ end
18
+
19
+ Result.new(line: data.fetch("line").to_f, branch: data.fetch("branch").to_f)
20
+ end
21
+
22
+ def self.load_last_run(path)
23
+ data = JSON.parse(File.read(path))
24
+ result = data["result"]
25
+ unless result.is_a?(Hash) && result.key?("line") && result.key?("branch")
26
+ raise ArgumentError, "missing result in coverage data: #{path}"
27
+ end
28
+
29
+ Result.new(line: result.fetch("line").to_f, branch: result.fetch("branch").to_f)
30
+ end
31
+ end
lib/jwt_encoder.rb ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class JwtEncoder
2
+ require "jwt"
3
+
4
+ def self.encode(payload)
5
+ JWT.encode(payload, ENV.fetch("DEVISE_JWT_SECRET_KEY", "fallback_secret"), "HS256")
6
+ end
7
+
8
+ def self.decode(token)
9
+ JWT.decode(token, ENV.fetch("DEVISE_JWT_SECRET_KEY", "fallback_secret"), true, algorithm: "HS256")
10
+ end
11
+ end
lib/tasks/.keep ADDED
File without changes
package.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "devDependencies": {
3
+ "@tailwindcss/typography": "^0.5.19"
4
+ }
5
+ }
public/400.html ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+
3
+ <html lang="en">
4
+
5
+ <head>
6
+
7
+ <title>The server cannot process the request due to a client error (400 Bad Request)</title>
8
+
9
+ <meta charset="utf-8">
10
+ <meta name="viewport" content="initial-scale=1, width=device-width">
11
+ <meta name="robots" content="noindex, nofollow">
12
+
13
+ <style>
14
+
15
+ *, *::before, *::after {
16
+ box-sizing: border-box;
17
+ }
18
+
19
+ * {
20
+ margin: 0;
21
+ }
22
+
23
+ html {
24
+ font-size: 16px;
25
+ }
26
+
27
+ body {
28
+ background: #FFF;
29
+ color: #261B23;
30
+ display: grid;
31
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Aptos, Roboto, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
32
+ font-size: clamp(1rem, 2.5vw, 2rem);
33
+ -webkit-font-smoothing: antialiased;
34
+ font-style: normal;
35
+ font-weight: 400;
36
+ letter-spacing: -0.0025em;
37
+ line-height: 1.4;
38
+ min-height: 100dvh;
39
+ place-items: center;
40
+ text-rendering: optimizeLegibility;
41
+ -webkit-text-size-adjust: 100%;
42
+ }
43
+
44
+ #error-description {
45
+ fill: #d30001;
46
+ }
47
+
48
+ #error-id {
49
+ fill: #f0eff0;
50
+ }
51
+
52
+ @media (prefers-color-scheme: dark) {
53
+ body {
54
+ background: #101010;
55
+ color: #e0e0e0;
56
+ }
57
+
58
+ #error-description {
59
+ fill: #FF6161;
60
+ }
61
+
62
+ #error-id {
63
+ fill: #2c2c2c;
64
+ }
65
+ }
66
+
67
+ a {
68
+ color: inherit;
69
+ font-weight: 700;
70
+ text-decoration: underline;
71
+ text-underline-offset: 0.0925em;
72
+ }
73
+
74
+ b, strong {
75
+ font-weight: 700;
76
+ }
77
+
78
+ i, em {
79
+ font-style: italic;
80
+ }
81
+
82
+ main {
83
+ display: grid;
84
+ gap: 1em;
85
+ padding: 2em;
86
+ place-items: center;
87
+ text-align: center;
88
+ }
89
+
90
+ main header {
91
+ width: min(100%, 12em);
92
+ }
93
+
94
+ main header svg {
95
+ height: auto;
96
+ max-width: 100%;
97
+ width: 100%;
98
+ }
99
+
100
+ main article {
101
+ width: min(100%, 30em);
102
+ }
103
+
104
+ main article p {
105
+ font-size: 75%;
106
+ }
107
+
108
+ main article br {
109
+ display: none;
110
+
111
+ @media(min-width: 48em) {
112
+ display: inline;
113
+ }
114
+ }
115
+
116
+ </style>
117
+
118
+ </head>
119
+
120
+ <body>
121
+
122
+ <!-- This file lives in public/400.html -->
123
+
124
+ <main>
125
+ <header>
126
+ <svg height="172" viewBox="0 0 480 172" width="480" xmlns="http://www.w3.org/2000/svg"><path d="m124.48 3.00509-45.6889 100.02991h26.2239v-28.1168h38.119v28.1168h21.628v35.145h-21.628v30.82h-37.308v-30.82h-72.1833v-31.901l50.2851-103.27391zm115.583 168.69891c-40.822 0-64.884-35.146-64.884-85.7015 0-50.5554 24.062-85.700907 64.884-85.700907 40.823 0 64.884 35.145507 64.884 85.700907 0 50.5555-24.061 85.7015-64.884 85.7015zm0-133.2831c-17.572 0-22.709 21.8984-22.709 47.5816 0 25.6835 5.137 47.5815 22.709 47.5815 17.303 0 22.71-21.898 22.71-47.5815 0-25.6832-5.407-47.5816-22.71-47.5816zm140.456 133.2831c-40.823 0-64.884-35.146-64.884-85.7015 0-50.5554 24.061-85.700907 64.884-85.700907 40.822 0 64.884 35.145507 64.884 85.700907 0 50.5555-24.062 85.7015-64.884 85.7015zm0-133.2831c-17.573 0-22.71 21.8984-22.71 47.5816 0 25.6835 5.137 47.5815 22.71 47.5815 17.302 0 22.709-21.898 22.709-47.5815 0-25.6832-5.407-47.5816-22.709-47.5816z" id="error-id"/><path d="m123.606 85.4445c3.212 1.0523 5.538 4.2089 5.538 8.0301 0 6.1472-4.209 9.5254-11.298 9.5254h-15.617v-34.0033h14.565c7.089 0 11.353 3.1566 11.353 9.2484 0 3.6551-2.049 6.3134-4.541 7.1994zm-12.904-2.9905h5.095c2.603 0 3.988-.9968 3.988-3.1013 0-2.1044-1.385-3.0459-3.988-3.0459h-5.095zm0 6.6456v6.5902h5.981c2.492 0 3.877-1.3291 3.877-3.2674 0-2.049-1.385-3.3228-3.877-3.3228zm43.786 13.9004h-8.362v-1.274c-.831.831-3.323 1.717-5.981 1.717-4.929 0-9.083-2.769-9.083-8.0301 0-4.818 4.154-7.9193 9.581-7.9193 2.049 0 4.486.6646 5.483 1.3845v-1.606c0-1.606-.942-2.9905-3.046-2.9905-1.606 0-2.548.7199-2.935 1.8275h-8.197c.72-4.8181 4.985-8.6393 11.409-8.6393 7.088 0 11.131 3.7659 11.131 10.2453zm-8.362-6.9779v-1.4399c-.554-1.0522-2.049-1.7167-3.655-1.7167-1.717 0-3.434.7199-3.434 2.3813 0 1.7168 1.717 2.4367 3.434 2.4367 1.606 0 3.101-.6645 3.655-1.6614zm27.996 6.9779v-1.994c-1.163 1.329-3.599 2.548-6.147 2.548-7.199 0-11.131-5.8151-11.131-13.0145s3.932-13.0143 11.131-13.0143c2.548 0 4.984 1.2184 6.147 2.5475v-13.0697h8.695v35.997zm0-9.1931v-6.5902c-.664-1.3291-2.159-2.326-3.821-2.326-2.99 0-4.763 2.4368-4.763 5.6488s1.773 5.5934 4.763 5.5934c1.717 0 3.157-.9415 3.821-2.326zm35.471-2.049h-3.101v11.2421h-8.806v-34.0033h15.285c7.31 0 12.35 4.1535 12.35 11.5744 0 5.1503-2.603 8.6947-6.757 10.2453l7.975 12.1836h-9.858zm-3.101-15.2849v8.1962h5.538c3.156 0 4.596-1.606 4.596-4.0981s-1.44-4.0981-4.596-4.0981zm36.957 17.8323h8.03c-.886 5.7597-5.206 9.2487-11.685 9.2487-7.643 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.316-13.0143 12.515-13.0143 7.643 0 11.962 5.095 11.962 12.5159v2.1598h-16.115c.277 2.9905 1.827 4.5965 4.32 4.5965 1.772 0 3.156-.7753 3.655-2.4921zm-3.822-10.0237c-2.049 0-3.433 1.2737-3.987 3.5997h7.532c-.111-2.0491-1.385-3.5997-3.545-3.5997zm30.98 27.5234v-10.799c-1.163 1.329-3.6 2.548-6.147 2.548-7.2 0-11.132-5.9259-11.132-13.0145 0-7.144 3.932-13.0143 11.132-13.0143 2.547 0 4.984 1.2184 6.147 2.5475v-1.9937h8.695v33.726zm0-17.9981v-6.5902c-.665-1.3291-2.105-2.326-3.821-2.326-2.991 0-4.763 2.4368-4.763 5.6488s1.772 5.5934 4.763 5.5934c1.661 0 3.156-.9415 3.821-2.326zm36.789-15.7279v24.921h-8.695v-2.16c-1.329 1.551-3.821 2.714-6.646 2.714-5.482 0-8.75-3.5999-8.75-9.1379v-16.3371h8.64v14.288c0 2.1045.996 3.5997 3.212 3.5997 1.606 0 3.101-1.0522 3.544-2.769v-15.1187zm19.084 16.2263h8.03c-.886 5.7597-5.206 9.2487-11.685 9.2487-7.643 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.316-13.0143 12.515-13.0143 7.643 0 11.963 5.095 11.963 12.5159v2.1598h-16.116c.277 2.9905 1.828 4.5965 4.32 4.5965 1.772 0 3.156-.7753 3.655-2.4921zm-3.822-10.0237c-2.049 0-3.433 1.2737-3.987 3.5997h7.532c-.111-2.0491-1.385-3.5997-3.545-3.5997zm13.428 11.0206h8.474c.387 1.3845 1.606 2.1598 3.156 2.1598 1.44 0 2.548-.5538 2.548-1.7168 0-.9414-.72-1.2737-1.939-1.5506l-4.873-.9969c-4.154-.886-6.867-2.8797-6.867-7.2547 0-5.3165 4.762-8.4178 10.633-8.4178 6.812 0 10.522 3.1567 11.297 8.0855h-8.03c-.277-1.0522-1.052-1.9937-3.046-1.9937-1.273 0-2.326.5538-2.326 1.6614 0 .7753.554 1.163 1.717 1.3845l4.929 1.163c4.541 1.0522 6.978 3.4335 6.978 7.4763 0 5.3168-4.818 8.2518-10.91 8.2518-6.369 0-10.965-2.88-11.741-8.2518zm27.538-.8861v-9.5807h-3.655v-6.7564h3.655v-6.8671h8.584v6.8671h5.205v6.7564h-5.205v8.307c0 1.9383.941 2.769 2.658 2.769.941 0 1.993-.2216 2.769-.5538v7.3654c-.997.443-2.88.775-4.818.775-5.871 0-9.193-2.769-9.193-9.0819z" id="error-description"/></svg>
127
+ </header>
128
+ <article>
129
+ <p><strong>The server cannot process the request due to a client error.</strong> Please check the request and try again. If you're the application owner check the logs for more information.</p>
130
+ </article>
131
+ </main>
132
+
133
+ </body>
134
+
135
+ </html>
public/404.html ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+
3
+ <html lang="en">
4
+
5
+ <head>
6
+
7
+ <title>The page you were looking for doesn't exist (404 Not found)</title>
8
+
9
+ <meta charset="utf-8">
10
+ <meta name="viewport" content="initial-scale=1, width=device-width">
11
+ <meta name="robots" content="noindex, nofollow">
12
+
13
+ <style>
14
+
15
+ *, *::before, *::after {
16
+ box-sizing: border-box;
17
+ }
18
+
19
+ * {
20
+ margin: 0;
21
+ }
22
+
23
+ html {
24
+ font-size: 16px;
25
+ }
26
+
27
+ body {
28
+ background: #FFF;
29
+ color: #261B23;
30
+ display: grid;
31
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Aptos, Roboto, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
32
+ font-size: clamp(1rem, 2.5vw, 2rem);
33
+ -webkit-font-smoothing: antialiased;
34
+ font-style: normal;
35
+ font-weight: 400;
36
+ letter-spacing: -0.0025em;
37
+ line-height: 1.4;
38
+ min-height: 100dvh;
39
+ place-items: center;
40
+ text-rendering: optimizeLegibility;
41
+ -webkit-text-size-adjust: 100%;
42
+ }
43
+
44
+ #error-description {
45
+ fill: #d30001;
46
+ }
47
+
48
+ #error-id {
49
+ fill: #f0eff0;
50
+ }
51
+
52
+ @media (prefers-color-scheme: dark) {
53
+ body {
54
+ background: #101010;
55
+ color: #e0e0e0;
56
+ }
57
+
58
+ #error-description {
59
+ fill: #FF6161;
60
+ }
61
+
62
+ #error-id {
63
+ fill: #2c2c2c;
64
+ }
65
+ }
66
+
67
+ a {
68
+ color: inherit;
69
+ font-weight: 700;
70
+ text-decoration: underline;
71
+ text-underline-offset: 0.0925em;
72
+ }
73
+
74
+ b, strong {
75
+ font-weight: 700;
76
+ }
77
+
78
+ i, em {
79
+ font-style: italic;
80
+ }
81
+
82
+ main {
83
+ display: grid;
84
+ gap: 1em;
85
+ padding: 2em;
86
+ place-items: center;
87
+ text-align: center;
88
+ }
89
+
90
+ main header {
91
+ width: min(100%, 12em);
92
+ }
93
+
94
+ main header svg {
95
+ height: auto;
96
+ max-width: 100%;
97
+ width: 100%;
98
+ }
99
+
100
+ main article {
101
+ width: min(100%, 30em);
102
+ }
103
+
104
+ main article p {
105
+ font-size: 75%;
106
+ }
107
+
108
+ main article br {
109
+ display: none;
110
+
111
+ @media(min-width: 48em) {
112
+ display: inline;
113
+ }
114
+ }
115
+
116
+ </style>
117
+
118
+ </head>
119
+
120
+ <body>
121
+
122
+ <!-- This file lives in public/404.html -->
123
+
124
+ <main>
125
+ <header>
126
+ <svg height="172" viewBox="0 0 480 172" width="480" xmlns="http://www.w3.org/2000/svg"><path d="m124.48 3.00509-45.6889 100.02991h26.2239v-28.1168h38.119v28.1168h21.628v35.145h-21.628v30.82h-37.308v-30.82h-72.1833v-31.901l50.2851-103.27391zm115.583 168.69891c-40.822 0-64.884-35.146-64.884-85.7015 0-50.5554 24.062-85.700907 64.884-85.700907 40.823 0 64.884 35.145507 64.884 85.700907 0 50.5555-24.061 85.7015-64.884 85.7015zm0-133.2831c-17.572 0-22.709 21.8984-22.709 47.5816 0 25.6835 5.137 47.5815 22.709 47.5815 17.303 0 22.71-21.898 22.71-47.5815 0-25.6832-5.407-47.5816-22.71-47.5816zm165.328-35.41581-45.689 100.02991h26.224v-28.1168h38.119v28.1168h21.628v35.145h-21.628v30.82h-37.308v-30.82h-72.184v-31.901l50.285-103.27391z" id="error-id"/><path d="m157.758 68.9967v34.0033h-7.199l-14.233-19.8814v19.8814h-8.584v-34.0033h8.307l13.125 18.7184v-18.7184zm28.454 21.5428c0 7.6978-5.15 13.0145-12.737 13.0145-7.532 0-12.738-5.3167-12.738-13.0145s5.206-13.0143 12.738-13.0143c7.587 0 12.737 5.3165 12.737 13.0143zm-8.528 0c0-3.4336-1.496-5.8703-4.209-5.8703-2.659 0-4.154 2.4367-4.154 5.8703s1.495 5.8149 4.154 5.8149c2.713 0 4.209-2.3813 4.209-5.8149zm13.184 3.8766v-9.5807h-3.655v-6.7564h3.655v-6.8671h8.584v6.8671h5.205v6.7564h-5.205v8.307c0 1.9383.941 2.769 2.658 2.769.941 0 1.994-.2216 2.769-.5538v7.3654c-.997.443-2.88.775-4.818.775-5.87 0-9.193-2.769-9.193-9.0819zm37.027 8.5839h-8.806v-34.0033h23.924v7.6978h-15.118v6.7564h13.9v7.5316h-13.9zm41.876-12.4605c0 7.6978-5.15 13.0145-12.737 13.0145-7.532 0-12.738-5.3167-12.738-13.0145s5.206-13.0143 12.738-13.0143c7.587 0 12.737 5.3165 12.737 13.0143zm-8.529 0c0-3.4336-1.495-5.8703-4.208-5.8703-2.659 0-4.154 2.4367-4.154 5.8703s1.495 5.8149 4.154 5.8149c2.713 0 4.208-2.3813 4.208-5.8149zm35.337-12.4605v24.921h-8.695v-2.16c-1.329 1.551-3.821 2.714-6.646 2.714-5.482 0-8.75-3.5999-8.75-9.1379v-16.3371h8.64v14.288c0 2.1045.997 3.5997 3.212 3.5997 1.606 0 3.101-1.0522 3.544-2.769v-15.1187zm4.076 24.921v-24.921h8.694v2.1598c1.385-1.5506 3.822-2.7136 6.701-2.7136 5.538 0 8.806 3.5997 8.806 9.1377v16.3371h-8.639v-14.2327c0-2.049-1.053-3.5443-3.268-3.5443-1.717 0-3.156.9969-3.6 2.7136v15.0634zm44.113 0v-1.994c-1.163 1.329-3.6 2.548-6.147 2.548-7.2 0-11.132-5.8151-11.132-13.0145s3.932-13.0143 11.132-13.0143c2.547 0 4.984 1.2184 6.147 2.5475v-13.0697h8.695v35.997zm0-9.1931v-6.5902c-.665-1.3291-2.16-2.326-3.821-2.326-2.991 0-4.763 2.4368-4.763 5.6488s1.772 5.5934 4.763 5.5934c1.717 0 3.156-.9415 3.821-2.326z" id="error-description"/></svg>
127
+ </header>
128
+ <article>
129
+ <p><strong>The page you were looking for doesn't exist.</strong> You may have mistyped the address or the page may have moved. If you're the application owner check the logs for more information.</p>
130
+ </article>
131
+ </main>
132
+
133
+ </body>
134
+
135
+ </html>
public/406-unsupported-browser.html ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+
3
+ <html lang="en">
4
+
5
+ <head>
6
+
7
+ <title>Your browser is not supported (406 Not Acceptable)</title>
8
+
9
+ <meta charset="utf-8">
10
+ <meta name="viewport" content="initial-scale=1, width=device-width">
11
+ <meta name="robots" content="noindex, nofollow">
12
+
13
+ <style>
14
+
15
+ *, *::before, *::after {
16
+ box-sizing: border-box;
17
+ }
18
+
19
+ * {
20
+ margin: 0;
21
+ }
22
+
23
+ html {
24
+ font-size: 16px;
25
+ }
26
+
27
+ body {
28
+ background: #FFF;
29
+ color: #261B23;
30
+ display: grid;
31
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Aptos, Roboto, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
32
+ font-size: clamp(1rem, 2.5vw, 2rem);
33
+ -webkit-font-smoothing: antialiased;
34
+ font-style: normal;
35
+ font-weight: 400;
36
+ letter-spacing: -0.0025em;
37
+ line-height: 1.4;
38
+ min-height: 100dvh;
39
+ place-items: center;
40
+ text-rendering: optimizeLegibility;
41
+ -webkit-text-size-adjust: 100%;
42
+ }
43
+
44
+ #error-description {
45
+ fill: #d30001;
46
+ }
47
+
48
+ #error-id {
49
+ fill: #f0eff0;
50
+ }
51
+
52
+ @media (prefers-color-scheme: dark) {
53
+ body {
54
+ background: #101010;
55
+ color: #e0e0e0;
56
+ }
57
+
58
+ #error-description {
59
+ fill: #FF6161;
60
+ }
61
+
62
+ #error-id {
63
+ fill: #2c2c2c;
64
+ }
65
+ }
66
+
67
+ a {
68
+ color: inherit;
69
+ font-weight: 700;
70
+ text-decoration: underline;
71
+ text-underline-offset: 0.0925em;
72
+ }
73
+
74
+ b, strong {
75
+ font-weight: 700;
76
+ }
77
+
78
+ i, em {
79
+ font-style: italic;
80
+ }
81
+
82
+ main {
83
+ display: grid;
84
+ gap: 1em;
85
+ padding: 2em;
86
+ place-items: center;
87
+ text-align: center;
88
+ }
89
+
90
+ main header {
91
+ width: min(100%, 12em);
92
+ }
93
+
94
+ main header svg {
95
+ height: auto;
96
+ max-width: 100%;
97
+ width: 100%;
98
+ }
99
+
100
+ main article {
101
+ width: min(100%, 30em);
102
+ }
103
+
104
+ main article p {
105
+ font-size: 75%;
106
+ }
107
+
108
+ main article br {
109
+ display: none;
110
+
111
+ @media(min-width: 48em) {
112
+ display: inline;
113
+ }
114
+ }
115
+
116
+ </style>
117
+
118
+ </head>
119
+
120
+ <body>
121
+
122
+ <!-- This file lives in public/406-unsupported-browser.html -->
123
+
124
+ <main>
125
+ <header>
126
+ <svg height="172" viewBox="0 0 480 172" width="480" xmlns="http://www.w3.org/2000/svg"><path d="m124.48 3.00509-45.6889 100.02991h26.2239v-28.1168h38.119v28.1168h21.628v35.145h-21.628v30.82h-37.308v-30.82h-72.1833v-31.901l50.2851-103.27391zm115.583 168.69891c-40.822 0-64.884-35.146-64.884-85.7015 0-50.5554 24.062-85.700907 64.884-85.700907 40.823 0 64.884 35.145507 64.884 85.700907 0 50.5555-24.061 85.7015-64.884 85.7015zm0-133.2831c-17.572 0-22.709 21.8984-22.709 47.5816 0 25.6835 5.137 47.5815 22.709 47.5815 17.303 0 22.71-21.898 22.71-47.5815 0-25.6832-5.407-47.5816-22.71-47.5816zm202.906 9.7326h-41.093c-2.433-7.2994-7.84-12.4361-17.302-12.4361-16.221 0-25.413 17.5728-25.954 34.8752v1.3517c5.137-7.0291 16.221-12.4361 30.82-12.4361 33.524 0 54.881 24.0612 54.881 53.7998 0 33.253-23.791 58.396-61.64 58.396-21.628 0-39.741-10.003-50.825-27.576-9.733-14.599-13.788-32.442-13.788-54.3406 0-51.9072 24.331-89.485807 66.236-89.485807 32.712 0 53.258 18.654107 58.665 47.851907zm-82.727 66.2355c0 13.247 9.463 22.439 22.71 22.439 12.977 0 22.439-9.192 22.439-22.439 0-13.517-9.462-22.7091-22.439-22.7091-13.247 0-22.71 9.1921-22.71 22.7091z" id="error-id"/><path d="m100.761 68.9967v34.0033h-7.1991l-14.2326-19.8814v19.8814h-8.5839v-34.0033h8.307l13.125 18.7184v-18.7184zm28.454 21.5428c0 7.6978-5.15 13.0145-12.737 13.0145-7.532 0-12.738-5.3167-12.738-13.0145s5.206-13.0143 12.738-13.0143c7.587 0 12.737 5.3165 12.737 13.0143zm-8.529 0c0-3.4336-1.495-5.8703-4.208-5.8703-2.659 0-4.154 2.4367-4.154 5.8703s1.495 5.8149 4.154 5.8149c2.713 0 4.208-2.3813 4.208-5.8149zm13.185 3.8766v-9.5807h-3.655v-6.7564h3.655v-6.8671h8.584v6.8671h5.205v6.7564h-5.205v8.307c0 1.9383.941 2.769 2.658 2.769.941 0 1.994-.2216 2.769-.5538v7.3654c-.997.443-2.88.775-4.818.775-5.87 0-9.193-2.769-9.193-9.0819zm39.02-25.4194h9.083l12.958 34.0033h-9.027l-2.436-6.5902h-12.35l-2.381 6.5902h-8.806zm4.431 10.5222-3.489 9.5807h6.978zm17.44 11.0206c0-7.6978 5.095-13.0143 12.572-13.0143 6.701 0 10.854 3.9874 11.574 9.8023h-8.418c-.221-1.4953-1.384-2.6029-3.156-2.6029-2.437 0-3.988 2.2706-3.988 5.8149s1.551 5.7595 3.988 5.7595c1.772 0 2.935-1.0522 3.156-2.5475h8.418c-.72 5.7596-4.873 9.8025-11.574 9.8025-7.477 0-12.572-5.3167-12.572-13.0145zm25.676 0c0-7.6978 5.095-13.0143 12.572-13.0143 6.701 0 10.854 3.9874 11.574 9.8023h-8.418c-.221-1.4953-1.384-2.6029-3.156-2.6029-2.437 0-3.988 2.2706-3.988 5.8149s1.551 5.7595 3.988 5.7595c1.772 0 2.935-1.0522 3.156-2.5475h8.418c-.72 5.7596-4.873 9.8025-11.574 9.8025-7.477 0-12.572-5.3167-12.572-13.0145zm42.013 3.7658h8.031c-.887 5.7597-5.206 9.2487-11.686 9.2487-7.642 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.317-13.0143 12.516-13.0143 7.643 0 11.962 5.095 11.962 12.5159v2.1598h-16.115c.277 2.9905 1.827 4.5965 4.319 4.5965 1.773 0 3.157-.7753 3.655-2.4921zm-3.821-10.0237c-2.049 0-3.433 1.2737-3.987 3.5997h7.532c-.111-2.0491-1.385-3.5997-3.545-3.5997zm23.4 16.7244v10.799h-8.694v-33.726h8.694v1.9937c1.163-1.3291 3.6-2.5475 6.148-2.5475 7.199 0 11.131 5.8703 11.131 13.0143 0 7.0886-3.932 13.0145-11.131 13.0145-2.548 0-4.985-1.219-6.148-2.548zm0-13.7893v6.5902c.665 1.3845 2.16 2.326 3.822 2.326 2.99 0 4.762-2.3814 4.762-5.5934s-1.772-5.6488-4.762-5.6488c-1.717 0-3.157.9969-3.822 2.326zm21.892 7.1994v-9.5807h-3.655v-6.7564h3.655v-6.8671h8.584v6.8671h5.206v6.7564h-5.206v8.307c0 1.9383.941 2.769 2.658 2.769.942 0 1.994-.2216 2.769-.5538v7.3654c-.997.443-2.88.775-4.818.775-5.87 0-9.193-2.769-9.193-9.0819zm39.458 8.5839h-8.363v-1.274c-.83.831-3.322 1.717-5.981 1.717-4.928 0-9.082-2.769-9.082-8.0301 0-4.818 4.154-7.9193 9.581-7.9193 2.049 0 4.486.6646 5.482 1.3845v-1.606c0-1.606-.941-2.9905-3.045-2.9905-1.606 0-2.548.7199-2.936 1.8275h-8.196c.72-4.8181 4.984-8.6393 11.408-8.6393 7.089 0 11.132 3.7659 11.132 10.2453zm-8.363-6.9779v-1.4399c-.553-1.0522-2.049-1.7167-3.655-1.7167-1.716 0-3.433.7199-3.433 2.3813 0 1.7168 1.717 2.4367 3.433 2.4367 1.606 0 3.102-.6645 3.655-1.6614zm20.742 4.9839v1.994h-8.694v-35.997h8.694v13.0697c1.163-1.3291 3.6-2.5475 6.148-2.5475 7.199 0 11.131 5.8149 11.131 13.0143s-3.932 13.0145-11.131 13.0145c-2.548 0-4.985-1.219-6.148-2.548zm0-13.7893v6.5902c.665 1.3845 2.105 2.326 3.822 2.326 2.99 0 4.762-2.3814 4.762-5.5934s-1.772-5.6488-4.762-5.6488c-1.662 0-3.157.9969-3.822 2.326zm28.759-20.2137v35.997h-8.695v-35.997zm19.172 27.3023h8.03c-.886 5.7597-5.206 9.2487-11.685 9.2487-7.643 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.316-13.0143 12.516-13.0143 7.642 0 11.962 5.095 11.962 12.5159v2.1598h-16.116c.277 2.9905 1.828 4.5965 4.32 4.5965 1.772 0 3.157-.7753 3.655-2.4921zm-3.821-10.0237c-2.049 0-3.434 1.2737-3.988 3.5997h7.532c-.111-2.0491-1.384-3.5997-3.544-3.5997z" id="error-description"/></svg>
127
+ </header>
128
+ <article>
129
+ <p><strong>Your browser is not supported.</strong><br> Please upgrade your browser to continue.</p>
130
+ </article>
131
+ </main>
132
+
133
+ </body>
134
+
135
+ </html>
public/422.html ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+
3
+ <html lang="en">
4
+
5
+ <head>
6
+
7
+ <title>The change you wanted was rejected (422 Unprocessable Entity)</title>
8
+
9
+ <meta charset="utf-8">
10
+ <meta name="viewport" content="initial-scale=1, width=device-width">
11
+ <meta name="robots" content="noindex, nofollow">
12
+
13
+ <style>
14
+
15
+ *, *::before, *::after {
16
+ box-sizing: border-box;
17
+ }
18
+
19
+ * {
20
+ margin: 0;
21
+ }
22
+
23
+ html {
24
+ font-size: 16px;
25
+ }
26
+
27
+ body {
28
+ background: #FFF;
29
+ color: #261B23;
30
+ display: grid;
31
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Aptos, Roboto, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
32
+ font-size: clamp(1rem, 2.5vw, 2rem);
33
+ -webkit-font-smoothing: antialiased;
34
+ font-style: normal;
35
+ font-weight: 400;
36
+ letter-spacing: -0.0025em;
37
+ line-height: 1.4;
38
+ min-height: 100dvh;
39
+ place-items: center;
40
+ text-rendering: optimizeLegibility;
41
+ -webkit-text-size-adjust: 100%;
42
+ }
43
+
44
+ #error-description {
45
+ fill: #d30001;
46
+ }
47
+
48
+ #error-id {
49
+ fill: #f0eff0;
50
+ }
51
+
52
+ @media (prefers-color-scheme: dark) {
53
+ body {
54
+ background: #101010;
55
+ color: #e0e0e0;
56
+ }
57
+
58
+ #error-description {
59
+ fill: #FF6161;
60
+ }
61
+
62
+ #error-id {
63
+ fill: #2c2c2c;
64
+ }
65
+ }
66
+
67
+ a {
68
+ color: inherit;
69
+ font-weight: 700;
70
+ text-decoration: underline;
71
+ text-underline-offset: 0.0925em;
72
+ }
73
+
74
+ b, strong {
75
+ font-weight: 700;
76
+ }
77
+
78
+ i, em {
79
+ font-style: italic;
80
+ }
81
+
82
+ main {
83
+ display: grid;
84
+ gap: 1em;
85
+ padding: 2em;
86
+ place-items: center;
87
+ text-align: center;
88
+ }
89
+
90
+ main header {
91
+ width: min(100%, 12em);
92
+ }
93
+
94
+ main header svg {
95
+ height: auto;
96
+ max-width: 100%;
97
+ width: 100%;
98
+ }
99
+
100
+ main article {
101
+ width: min(100%, 30em);
102
+ }
103
+
104
+ main article p {
105
+ font-size: 75%;
106
+ }
107
+
108
+ main article br {
109
+ display: none;
110
+
111
+ @media(min-width: 48em) {
112
+ display: inline;
113
+ }
114
+ }
115
+
116
+ </style>
117
+
118
+ </head>
119
+
120
+ <body>
121
+
122
+ <!-- This file lives in public/422.html -->
123
+
124
+ <main>
125
+ <header>
126
+ <svg height="172" viewBox="0 0 480 172" width="480" xmlns="http://www.w3.org/2000/svg"><path d="m124.48 3.00509-45.6889 100.02991h26.2239v-28.1168h38.119v28.1168h21.628v35.145h-21.628v30.82h-37.308v-30.82h-72.1833v-31.901l50.2851-103.27391zm130.453 51.63681c0-8.9215-6.218-15.4099-15.681-15.4099-10.273 0-15.95 7.5698-16.491 16.4913h-44.608c3.244-30.8199 25.683-55.421707 61.099-55.421707 36.498 0 59.477 20.816907 59.477 51.636807 0 21.3577-14.869 36.7676-31.901 52.7186l-27.305 27.035h59.747v37.308h-120.306v-27.846l57.044-56.7736c11.084-11.8954 18.925-20.0059 18.925-29.7385zm140.455 0c0-8.9215-6.218-15.4099-15.68-15.4099-10.274 0-15.951 7.5698-16.492 16.4913h-44.608c3.245-30.8199 25.684-55.421707 61.1-55.421707 36.497 0 59.477 20.816907 59.477 51.636807 0 21.3577-14.87 36.7676-31.902 52.7186l-27.305 27.035h59.747v37.308h-120.305v-27.846l57.043-56.7736c11.085-11.8954 18.925-20.0059 18.925-29.7385z" id="error-id"/><path d="m19.3936 103.554c-8.9715 0-14.84183-5.0952-14.84183-14.4544v-20.1029h8.86083v19.3276c0 4.8181 2.2706 7.3102 5.981 7.3102 3.6551 0 5.9257-2.4921 5.9257-7.3102v-19.3276h8.8608v20.1583c0 9.3038-5.8149 14.399-14.7865 14.399zm18.734-.554v-24.921h8.6947v2.1598c1.3845-1.5506 3.8212-2.7136 6.701-2.7136 5.538 0 8.8054 3.5997 8.8054 9.1377v16.3371h-8.6393v-14.2327c0-2.049-1.0522-3.5443-3.2674-3.5443-1.7168 0-3.1567.9969-3.5997 2.7136v15.0634zm36.8584-1.994v10.799h-8.6946v-33.726h8.6946v1.9937c1.163-1.3291 3.5997-2.5475 6.1472-2.5475 7.1994 0 11.1314 5.8703 11.1314 13.0143 0 7.0886-3.932 13.0145-11.1314 13.0145-2.5475 0-4.9842-1.219-6.1472-2.548zm0-13.7893v6.5902c.6646 1.3845 2.1599 2.326 3.8213 2.326 2.9905 0 4.7626-2.3814 4.7626-5.5934s-1.7721-5.6488-4.7626-5.6488c-1.7168 0-3.1567.9969-3.8213 2.326zm36.789-9.2485v8.3624c-1.052-.5538-2.215-.7753-3.6-.7753-2.381 0-3.987 1.0522-4.43 2.8244v14.6203h-8.6949v-24.921h8.6949v2.2152c1.218-1.6614 3.156-2.769 5.648-2.769 1.108 0 1.994.2215 2.382.443zm26.769 12.5713c0 7.6978-5.15 13.0145-12.737 13.0145-7.532 0-12.738-5.3167-12.738-13.0145s5.206-13.0143 12.738-13.0143c7.587 0 12.737 5.3165 12.737 13.0143zm-8.528 0c0-3.4336-1.496-5.8703-4.209-5.8703-2.659 0-4.154 2.4367-4.154 5.8703s1.495 5.8149 4.154 5.8149c2.713 0 4.209-2.3813 4.209-5.8149zm10.352 0c0-7.6978 5.095-13.0143 12.571-13.0143 6.701 0 10.855 3.9874 11.574 9.8023h-8.417c-.222-1.4953-1.385-2.6029-3.157-2.6029-2.437 0-3.987 2.2706-3.987 5.8149s1.55 5.7595 3.987 5.7595c1.772 0 2.935-1.0522 3.157-2.5475h8.417c-.719 5.7596-4.873 9.8025-11.574 9.8025-7.476 0-12.571-5.3167-12.571-13.0145zm42.013 3.7658h8.03c-.886 5.7597-5.206 9.2487-11.685 9.2487-7.643 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.316-13.0143 12.516-13.0143 7.642 0 11.962 5.095 11.962 12.5159v2.1598h-16.116c.277 2.9905 1.828 4.5965 4.32 4.5965 1.772 0 3.156-.7753 3.655-2.4921zm-3.821-10.0237c-2.049 0-3.434 1.2737-3.988 3.5997h7.532c-.111-2.0491-1.385-3.5997-3.544-3.5997zm13.428 11.0206h8.473c.387 1.3845 1.606 2.1598 3.156 2.1598 1.44 0 2.548-.5538 2.548-1.7168 0-.9414-.72-1.2737-1.938-1.5506l-4.874-.9969c-4.153-.886-6.867-2.8797-6.867-7.2547 0-5.3165 4.763-8.4178 10.633-8.4178 6.812 0 10.522 3.1567 11.297 8.0855h-8.03c-.277-1.0522-1.052-1.9937-3.046-1.9937-1.273 0-2.326.5538-2.326 1.6614 0 .7753.554 1.163 1.717 1.3845l4.929 1.163c4.541 1.0522 6.978 3.4335 6.978 7.4763 0 5.3168-4.818 8.2518-10.91 8.2518-6.369 0-10.965-2.88-11.74-8.2518zm24.269 0h8.474c.387 1.3845 1.606 2.1598 3.156 2.1598 1.44 0 2.548-.5538 2.548-1.7168 0-.9414-.72-1.2737-1.939-1.5506l-4.873-.9969c-4.154-.886-6.867-2.8797-6.867-7.2547 0-5.3165 4.763-8.4178 10.633-8.4178 6.812 0 10.522 3.1567 11.297 8.0855h-8.03c-.277-1.0522-1.052-1.9937-3.046-1.9937-1.273 0-2.326.5538-2.326 1.6614 0 .7753.554 1.163 1.717 1.3845l4.929 1.163c4.541 1.0522 6.978 3.4335 6.978 7.4763 0 5.3168-4.818 8.2518-10.91 8.2518-6.369 0-10.965-2.88-11.741-8.2518zm47.918 7.6978h-8.363v-1.274c-.831.831-3.323 1.717-5.981 1.717-4.929 0-9.082-2.769-9.082-8.0301 0-4.818 4.153-7.9193 9.581-7.9193 2.049 0 4.485.6646 5.482 1.3845v-1.606c0-1.606-.941-2.9905-3.046-2.9905-1.606 0-2.547.7199-2.935 1.8275h-8.196c.72-4.8181 4.984-8.6393 11.408-8.6393 7.089 0 11.132 3.7659 11.132 10.2453zm-8.363-6.9779v-1.4399c-.554-1.0522-2.049-1.7167-3.655-1.7167-1.717 0-3.434.7199-3.434 2.3813 0 1.7168 1.717 2.4367 3.434 2.4367 1.606 0 3.101-.6645 3.655-1.6614zm20.742 4.9839v1.994h-8.695v-35.997h8.695v13.0697c1.163-1.3291 3.6-2.5475 6.147-2.5475 7.2 0 11.132 5.8149 11.132 13.0143s-3.932 13.0145-11.132 13.0145c-2.547 0-4.984-1.219-6.147-2.548zm0-13.7893v6.5902c.665 1.3845 2.105 2.326 3.821 2.326 2.991 0 4.763-2.3814 4.763-5.5934s-1.772-5.6488-4.763-5.6488c-1.661 0-3.156.9969-3.821 2.326zm28.759-20.2137v35.997h-8.695v-35.997zm19.172 27.3023h8.03c-.886 5.7597-5.206 9.2487-11.685 9.2487-7.643 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.316-13.0143 12.515-13.0143 7.643 0 11.962 5.095 11.962 12.5159v2.1598h-16.115c.277 2.9905 1.827 4.5965 4.32 4.5965 1.772 0 3.156-.7753 3.655-2.4921zm-3.822-10.0237c-2.049 0-3.433 1.2737-3.987 3.5997h7.532c-.111-2.0491-1.385-3.5997-3.545-3.5997zm25.461-15.2849h24.311v7.6424h-15.561v5.3165h14.232v7.4763h-14.232v5.8703h15.561v7.6978h-24.311zm27.942 34.0033v-24.921h8.694v2.1598c1.385-1.5506 3.822-2.7136 6.701-2.7136 5.538 0 8.806 3.5997 8.806 9.1377v16.3371h-8.639v-14.2327c0-2.049-1.053-3.5443-3.268-3.5443-1.717 0-3.157.9969-3.6 2.7136v15.0634zm29.991-8.5839v-9.5807h-3.655v-6.7564h3.655v-6.8671h8.584v6.8671h5.206v6.7564h-5.206v8.307c0 1.9383.941 2.769 2.658 2.769.942 0 1.994-.2216 2.769-.5538v7.3654c-.997.443-2.88.775-4.818.775-5.87 0-9.193-2.769-9.193-9.0819zm26.161-16.3371v24.921h-8.694v-24.921zm.61-6.7564c0 2.8244-2.271 4.652-4.929 4.652s-4.929-1.8276-4.929-4.652c0-2.8797 2.271-4.7073 4.929-4.7073s4.929 1.8276 4.929 4.7073zm5.382 23.0935v-9.5807h-3.655v-6.7564h3.655v-6.8671h8.584v6.8671h5.206v6.7564h-5.206v8.307c0 1.9383.941 2.769 2.658 2.769.941 0 1.994-.2216 2.769-.5538v7.3654c-.997.443-2.88.775-4.818.775-5.87 0-9.193-2.769-9.193-9.0819zm29.22 17.3889h-8.584l3.655-9.414-9.303-24.312h9.026l4.763 14.1773 4.652-14.1773h8.639z" id="error-description"/></svg>
127
+ </header>
128
+ <article>
129
+ <p><strong>The change you wanted was rejected.</strong> Maybe you tried to change something you didn't have access to. If you're the application owner check the logs for more information.</p>
130
+ </article>
131
+ </main>
132
+
133
+ </body>
134
+
135
+ </html>
public/500.html ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+
3
+ <html lang="en">
4
+
5
+ <head>
6
+
7
+ <title>We're sorry, but something went wrong (500 Internal Server Error)</title>
8
+
9
+ <meta charset="utf-8">
10
+ <meta name="viewport" content="initial-scale=1, width=device-width">
11
+ <meta name="robots" content="noindex, nofollow">
12
+
13
+ <style>
14
+
15
+ *, *::before, *::after {
16
+ box-sizing: border-box;
17
+ }
18
+
19
+ * {
20
+ margin: 0;
21
+ }
22
+
23
+ html {
24
+ font-size: 16px;
25
+ }
26
+
27
+ body {
28
+ background: #FFF;
29
+ color: #261B23;
30
+ display: grid;
31
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Aptos, Roboto, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
32
+ font-size: clamp(1rem, 2.5vw, 2rem);
33
+ -webkit-font-smoothing: antialiased;
34
+ font-style: normal;
35
+ font-weight: 400;
36
+ letter-spacing: -0.0025em;
37
+ line-height: 1.4;
38
+ min-height: 100dvh;
39
+ place-items: center;
40
+ text-rendering: optimizeLegibility;
41
+ -webkit-text-size-adjust: 100%;
42
+ }
43
+
44
+ #error-description {
45
+ fill: #d30001;
46
+ }
47
+
48
+ #error-id {
49
+ fill: #f0eff0;
50
+ }
51
+
52
+ @media (prefers-color-scheme: dark) {
53
+ body {
54
+ background: #101010;
55
+ color: #e0e0e0;
56
+ }
57
+
58
+ #error-description {
59
+ fill: #FF6161;
60
+ }
61
+
62
+ #error-id {
63
+ fill: #2c2c2c;
64
+ }
65
+ }
66
+
67
+ a {
68
+ color: inherit;
69
+ font-weight: 700;
70
+ text-decoration: underline;
71
+ text-underline-offset: 0.0925em;
72
+ }
73
+
74
+ b, strong {
75
+ font-weight: 700;
76
+ }
77
+
78
+ i, em {
79
+ font-style: italic;
80
+ }
81
+
82
+ main {
83
+ display: grid;
84
+ gap: 1em;
85
+ padding: 2em;
86
+ place-items: center;
87
+ text-align: center;
88
+ }
89
+
90
+ main header {
91
+ width: min(100%, 12em);
92
+ }
93
+
94
+ main header svg {
95
+ height: auto;
96
+ max-width: 100%;
97
+ width: 100%;
98
+ }
99
+
100
+ main article {
101
+ width: min(100%, 30em);
102
+ }
103
+
104
+ main article p {
105
+ font-size: 75%;
106
+ }
107
+
108
+ main article br {
109
+ display: none;
110
+
111
+ @media(min-width: 48em) {
112
+ display: inline;
113
+ }
114
+ }
115
+
116
+ </style>
117
+
118
+ </head>
119
+
120
+ <body>
121
+
122
+ <!-- This file lives in public/500.html -->
123
+
124
+ <main>
125
+ <header>
126
+ <svg height="172" viewBox="0 0 480 172" width="480" xmlns="http://www.w3.org/2000/svg"><path d="m101.23 93.8427c-8.1103 0-15.4098 3.7849-19.7354 8.3813h-36.2269v-99.21891h103.8143v37.03791h-68.3984v24.8722c5.1366-2.7035 15.1396-5.9477 24.6014-5.9477 35.146 0 56.233 22.7094 56.233 55.4215 0 34.605-23.791 57.315-60.558 57.315-37.8492 0-61.64-22.169-63.8028-55.963h42.9857c1.0814 10.814 9.1919 19.195 21.6281 19.195 11.355 0 19.465-8.381 19.465-20.547 0-11.625-7.299-20.5463-20.006-20.5463zm138.833 77.8613c-40.822 0-64.884-35.146-64.884-85.7015 0-50.5554 24.062-85.700907 64.884-85.700907 40.823 0 64.884 35.145507 64.884 85.700907 0 50.5555-24.061 85.7015-64.884 85.7015zm0-133.2831c-17.572 0-22.709 21.8984-22.709 47.5816 0 25.6835 5.137 47.5815 22.709 47.5815 17.303 0 22.71-21.898 22.71-47.5815 0-25.6832-5.407-47.5816-22.71-47.5816zm140.456 133.2831c-40.823 0-64.884-35.146-64.884-85.7015 0-50.5554 24.061-85.700907 64.884-85.700907 40.822 0 64.884 35.145507 64.884 85.700907 0 50.5555-24.062 85.7015-64.884 85.7015zm0-133.2831c-17.573 0-22.71 21.8984-22.71 47.5816 0 25.6835 5.137 47.5815 22.71 47.5815 17.302 0 22.709-21.898 22.709-47.5815 0-25.6832-5.407-47.5816-22.709-47.5816z" id="error-id"/><path d="m23.1377 68.9967v34.0033h-8.9162v-34.0033zm4.3157 34.0033v-24.921h8.6947v2.1598c1.3845-1.5506 3.8212-2.7136 6.701-2.7136 5.538 0 8.8054 3.5997 8.8054 9.1377v16.3371h-8.6393v-14.2327c0-2.049-1.0522-3.5443-3.2674-3.5443-1.7168 0-3.1567.9969-3.5997 2.7136v15.0634zm29.9913-8.5839v-9.5807h-3.655v-6.7564h3.655v-6.8671h8.5839v6.8671h5.2058v6.7564h-5.2058v8.307c0 1.9383.9415 2.769 2.6583 2.769.9414 0 1.9937-.2216 2.769-.5538v7.3654c-.9969.443-2.8798.775-4.8181.775-5.8703 0-9.1931-2.769-9.1931-9.0819zm32.3666-.1108h8.0301c-.8861 5.7597-5.2057 9.2487-11.6852 9.2487-7.6424 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.3165-13.0143 12.5159-13.0143 7.6424 0 11.9621 5.095 11.9621 12.5159v2.1598h-16.1156c.2769 2.9905 1.8275 4.5965 4.3196 4.5965 1.7722 0 3.1567-.7753 3.6551-2.4921zm-3.8212-10.0237c-2.0491 0-3.4336 1.2737-3.9874 3.5997h7.5317c-.1107-2.0491-1.3845-3.5997-3.5443-3.5997zm31.4299-6.3134v8.3624c-1.052-.5538-2.215-.7753-3.599-.7753-2.382 0-3.988 1.0522-4.431 2.8244v14.6203h-8.694v-24.921h8.694v2.2152c1.219-1.6614 3.157-2.769 5.649-2.769 1.108 0 1.994.2215 2.381.443zm2.949 25.0318v-24.921h8.694v2.1598c1.385-1.5506 3.821-2.7136 6.701-2.7136 5.538 0 8.806 3.5997 8.806 9.1377v16.3371h-8.64v-14.2327c0-2.049-1.052-3.5443-3.267-3.5443-1.717 0-3.157.9969-3.6 2.7136v15.0634zm50.371 0h-8.363v-1.274c-.83.831-3.323 1.717-5.981 1.717-4.929 0-9.082-2.769-9.082-8.0301 0-4.818 4.153-7.9193 9.581-7.9193 2.049 0 4.485.6646 5.482 1.3845v-1.606c0-1.606-.941-2.9905-3.046-2.9905-1.606 0-2.547.7199-2.935 1.8275h-8.196c.72-4.8181 4.984-8.6393 11.408-8.6393 7.089 0 11.132 3.7659 11.132 10.2453zm-8.363-6.9779v-1.4399c-.554-1.0522-2.049-1.7167-3.655-1.7167-1.717 0-3.433.7199-3.433 2.3813 0 1.7168 1.716 2.4367 3.433 2.4367 1.606 0 3.101-.6645 3.655-1.6614zm20.742-29.0191v35.997h-8.694v-35.997zm13.036 25.9178h9.248c.72 2.326 2.714 3.489 5.483 3.489 2.713 0 4.596-1.163 4.596-3.2674 0-1.6061-1.052-2.326-3.212-2.8244l-6.534-1.3845c-4.985-1.1076-8.751-3.7105-8.751-9.47 0-6.6456 5.538-11.0206 13.07-11.0206 8.307 0 13.014 4.5411 13.956 10.4114h-8.695c-.72-1.8829-2.27-3.3228-5.205-3.3228-2.548 0-4.265 1.1076-4.265 2.9905 0 1.4953 1.052 2.326 2.825 2.7137l6.645 1.5506c5.815 1.3845 9.027 4.5412 9.027 9.8023 0 6.9778-5.87 10.9654-13.291 10.9654-8.141 0-13.679-3.9322-14.897-10.6332zm46.509 1.3845h8.031c-.887 5.7597-5.206 9.2487-11.686 9.2487-7.642 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.317-13.0143 12.516-13.0143 7.643 0 11.962 5.095 11.962 12.5159v2.1598h-16.115c.277 2.9905 1.827 4.5965 4.319 4.5965 1.773 0 3.157-.7753 3.655-2.4921zm-3.821-10.0237c-2.049 0-3.433 1.2737-3.987 3.5997h7.532c-.111-2.0491-1.385-3.5997-3.545-3.5997zm31.431-6.3134v8.3624c-1.053-.5538-2.216-.7753-3.6-.7753-2.381 0-3.988 1.0522-4.431 2.8244v14.6203h-8.694v-24.921h8.694v2.2152c1.219-1.6614 3.157-2.769 5.649-2.769 1.108 0 1.994.2215 2.382.443zm18.288 25.0318h-7.809l-9.47-24.921h8.861l4.763 14.288 4.652-14.288h8.528zm25.614-8.6947h8.03c-.886 5.7597-5.206 9.2487-11.685 9.2487-7.642 0-12.682-5.2613-12.682-13.0145 0-7.6978 5.316-13.0143 12.516-13.0143 7.642 0 11.962 5.095 11.962 12.5159v2.1598h-16.116c.277 2.9905 1.828 4.5965 4.32 4.5965 1.772 0 3.157-.7753 3.655-2.4921zm-3.821-10.0237c-2.049 0-3.434 1.2737-3.988 3.5997h7.532c-.111-2.0491-1.384-3.5997-3.544-3.5997zm31.43-6.3134v8.3624c-1.052-.5538-2.215-.7753-3.6-.7753-2.381 0-3.987 1.0522-4.43 2.8244v14.6203h-8.695v-24.921h8.695v2.2152c1.218-1.6614 3.157-2.769 5.649-2.769 1.107 0 1.993.2215 2.381.443zm13.703-8.9715h24.312v7.6424h-15.562v5.3165h14.232v7.4763h-14.232v5.8703h15.562v7.6978h-24.312zm44.667 8.9715v8.3624c-1.052-.5538-2.215-.7753-3.6-.7753-2.381 0-3.987 1.0522-4.43 2.8244v14.6203h-8.695v-24.921h8.695v2.2152c1.218-1.6614 3.156-2.769 5.648-2.769 1.108 0 1.994.2215 2.382.443zm19.673 0v8.3624c-1.053-.5538-2.216-.7753-3.6-.7753-2.381 0-3.987 1.0522-4.43 2.8244v14.6203h-8.695v-24.921h8.695v2.2152c1.218-1.6614 3.156-2.769 5.648-2.769 1.108 0 1.994.2215 2.382.443zm26.769 12.5713c0 7.6978-5.15 13.0145-12.737 13.0145-7.532 0-12.738-5.3167-12.738-13.0145s5.206-13.0143 12.738-13.0143c7.587 0 12.737 5.3165 12.737 13.0143zm-8.529 0c0-3.4336-1.495-5.8703-4.208-5.8703-2.659 0-4.154 2.4367-4.154 5.8703s1.495 5.8149 4.154 5.8149c2.713 0 4.208-2.3813 4.208-5.8149zm28.082-12.5713v8.3624c-1.052-.5538-2.215-.7753-3.6-.7753-2.381 0-3.987 1.0522-4.43 2.8244v14.6203h-8.695v-24.921h8.695v2.2152c1.218-1.6614 3.157-2.769 5.649-2.769 1.107 0 1.993.2215 2.381.443z" id="error-description"/></svg>
127
+ </header>
128
+ <article>
129
+ <p><strong>We're sorry, but something went wrong.</strong><br> If you're the application owner check the logs for more information.</p>
130
+ </article>
131
+ </main>
132
+
133
+ </body>
134
+
135
+ </html>
public/favicon.ico ADDED

Git LFS Details

  • SHA256: d9bd8fb4af8c9ac24c11b25afa6d0f592cda023e533cd0733040f474a9356452
  • Pointer size: 131 Bytes
  • Size of remote file: 370 kB
public/favicon.png ADDED
public/favicon.svg ADDED
public/robots.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
script/.keep ADDED
File without changes
script/check_coverage_baseline ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ $stdout.sync = true
5
+ $stderr.sync = true
6
+
7
+ require_relative "../lib/coverage_baseline"
8
+
9
+ root = File.expand_path("..", __dir__)
10
+ baseline_file = File.join(root, "config", "coverage_baseline.yml")
11
+ last_run_file = File.join(root, "coverage", ".last_run.json")
12
+
13
+ unless File.exist?(baseline_file)
14
+ warn "Coverage baseline file missing: #{baseline_file}"
15
+ exit 1
16
+ end
17
+
18
+ unless File.exist?(last_run_file)
19
+ warn "Coverage last run file missing: #{last_run_file}. Run with COVERAGE=true first."
20
+ exit 1
21
+ end
22
+
23
+ begin
24
+ baseline = CoverageBaseline.load_baseline(baseline_file)
25
+ current = CoverageBaseline.load_last_run(last_run_file)
26
+ rescue StandardError => e
27
+ warn "Error loading coverage data: #{e.message}"
28
+ exit 1
29
+ end
30
+
31
+ puts "Coverage Comparison:"
32
+ puts " Line: Current #{format('%.2f', current.line)}% | Baseline #{format('%.2f', baseline.line)}%"
33
+ puts " Branch: Current #{format('%.2f', current.branch)}% | Baseline #{format('%.2f', baseline.branch)}%"
34
+
35
+ if CoverageBaseline.below?(current: current, baseline: baseline)
36
+ warn "\nCoverage dropped below locked baseline!"
37
+ exit 1
38
+ else
39
+ puts "\nCoverage check PASSED: No regression detected."
40
+ exit 0
41
+ end
script/ci_local ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ bin/rubocop
5
+ bin/brakeman --no-pager --except CheckEOLRuby
6
+ bin/bundler-audit
7
+ bin/importmap audit
8
+ env -u CI COVERAGE=true bundle exec rspec
9
+ ./script/check_coverage_baseline
script/source_archive ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ root="$(git rev-parse --show-toplevel)"
4
+ cd "$root"
5
+ name="rails-8-blog-source-$(date -u +%Y%m%dT%H%M%SZ).tar.gz"
6
+ git archive --format=tar.gz --output="../$name" HEAD
7
+ sha256sum "../$name" > "../$name.sha256"
8
+ printf '%s\n' "../$name"
spec/blueprints/user_blueprint_spec.rb ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "rails_helper"
4
+
5
+ RSpec.describe UserBlueprint do
6
+ it "omits an avatar URL when no public id is present" do
7
+ user = build(:user, avatar_public_id: nil)
8
+
9
+ expect(JSON.parse(described_class.render(user)).fetch("avatar_url")).to be_nil
10
+ expect(JSON.parse(described_class.render(user, view: :compact)).fetch("avatar_url")).to be_nil
11
+ end
12
+
13
+ it "renders avatar URLs in both views when a public id is present" do
14
+ user = build(:user, avatar_public_id: "avatars/user")
15
+ allow(user).to receive(:avatar_url).with(size: 200).and_return("default-avatar")
16
+ allow(user).to receive(:avatar_url).with(size: 100).and_return("compact-avatar")
17
+
18
+ expect(JSON.parse(described_class.render(user)).fetch("avatar_url")).to eq("default-avatar")
19
+ expect(JSON.parse(described_class.render(user, view: :compact)).fetch("avatar_url")).to eq("compact-avatar")
20
+ end
21
+ end
spec/config/active_storage_r2_contract_spec.rb ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require "erb"
5
+ require "pathname"
6
+ require "rbconfig"
7
+ require "tempfile"
8
+
9
+ RSpec.describe "Active Storage R2 production contract" do
10
+ R2_VARIABLES = %w[
11
+ R2_ENDPOINT
12
+ R2_ACCESS_KEY_ID
13
+ R2_SECRET_ACCESS_KEY
14
+ R2_BUCKET
15
+ R2_REGION
16
+ ].freeze
17
+
18
+ let(:project_root) { Pathname(__dir__).join("../..").expand_path }
19
+
20
+ def rendered_storage_config_without_r2_variables(environment)
21
+ probe = <<~'RUBY'
22
+ require "erb"
23
+ require "pathname"
24
+
25
+ module Rails
26
+ def self.root = Pathname.new(Dir.pwd)
27
+ def self.application = Application.new
28
+ def self.env = ENV.fetch("RAILS_ENV")
29
+
30
+ class Application
31
+ def credentials = Credentials.new
32
+ end
33
+
34
+ class Credentials
35
+ def dig(*) = nil
36
+ end
37
+ end
38
+
39
+ puts ERB.new(File.read("config/storage.yml")).result
40
+ RUBY
41
+
42
+ Open3.capture3(
43
+ r2_environment(environment), RbConfig.ruby, "-e", probe, chdir: project_root.to_s
44
+ )
45
+ end
46
+
47
+ def r2_environment(environment, overrides = {})
48
+ R2_VARIABLES.each_with_object({ "RAILS_ENV" => environment }.merge(overrides)) do |name, values|
49
+ values[name] = overrides.fetch(name, nil)
50
+ end
51
+ end
52
+
53
+ def production_environment(overrides = {})
54
+ r2_environment("production", {
55
+ "DATABASE_URL" => ENV.fetch("D3_TEST_DATABASE_URL"),
56
+ "RAILS_MASTER_KEY" => nil,
57
+ "SECRET_KEY_BASE" => nil,
58
+ "SECRET_KEY_BASE_DUMMY" => "1",
59
+ "R2_ENDPOINT" => "https://example.invalid",
60
+ "R2_ACCESS_KEY_ID" => "r2-contract-access-key",
61
+ "R2_SECRET_ACCESS_KEY" => "r2-contract-secret",
62
+ "R2_BUCKET" => "r2-contract-bucket",
63
+ "R2_REGION" => "auto"
64
+ }.merge(overrides))
65
+ end
66
+
67
+ it "renders storage configuration without R2 variables in test" do
68
+ stdout, stderr, status = rendered_storage_config_without_r2_variables("test")
69
+
70
+ expect(status).to be_success, -> { "Test storage configuration failed.\n#{stdout}#{stderr}" }
71
+ expect(stdout).to include("cloudflare_r2:")
72
+ end
73
+
74
+ it "renders storage configuration without R2 variables in development" do
75
+ stdout, stderr, status = rendered_storage_config_without_r2_variables("development")
76
+
77
+ expect(status).to be_success, -> { "Development storage configuration failed.\n#{stdout}#{stderr}" }
78
+ expect(stdout).to include("cloudflare_r2:")
79
+ end
80
+
81
+ R2_VARIABLES.each do |missing_variable|
82
+ it "fails fast in production when #{missing_variable} is missing" do
83
+ probe = <<~'RUBY'
84
+ result_path = ENV.fetch("R2_PRODUCTION_RESULT")
85
+ require File.expand_path("config/environment", Dir.pwd)
86
+ File.write(result_path, "PRODUCTION_BOOT=PASS\n")
87
+ RUBY
88
+
89
+ Tempfile.create("r2-production-result") do |result|
90
+ environment = production_environment(
91
+ missing_variable => nil,
92
+ "R2_PRODUCTION_RESULT" => result.path
93
+ )
94
+ stdout, stderr, status = Open3.capture3(
95
+ environment, RbConfig.ruby, "-e", probe, chdir: project_root.to_s
96
+ )
97
+
98
+ expect(status).not_to be_success, -> { "Production boot unexpectedly succeeded.\n#{stdout}#{stderr}" }
99
+ expect("#{stdout}#{stderr}").to include("key not found: \"#{missing_variable}\"")
100
+ expect(File.read(result.path)).to be_empty
101
+ end
102
+ end
103
+ end
104
+
105
+ it "selects the R2 S3 service in production" do
106
+ probe = <<~'RUBY'
107
+ require File.expand_path("config/environment", Dir.pwd)
108
+
109
+ service_name = Rails.application.config.active_storage.service
110
+ service = ActiveStorage::Service.configure(
111
+ service_name,
112
+ Rails.application.config.active_storage.service_configurations
113
+ )
114
+
115
+ puts "SERVICE=#{service_name}"
116
+ puts "CLASS=#{service.class.name}"
117
+ puts "REQUEST_CHECKSUM_CALCULATION=#{service.client.client.config.request_checksum_calculation}"
118
+ RUBY
119
+ environment = production_environment
120
+
121
+ stdout, stderr, status = Open3.capture3(environment, RbConfig.ruby, "-e", probe, chdir: project_root.to_s)
122
+
123
+ expect(status).to be_success, -> { "Production R2 probe failed.\n#{stdout}#{stderr}" }
124
+ expect(stdout).to include("SERVICE=cloudflare_r2\n")
125
+ expect(stdout).to include("CLASS=ActiveStorage::Service::S3Service\n")
126
+ expect(stdout).to include("REQUEST_CHECKSUM_CALCULATION=when_required\n")
127
+ end
128
+ end
spec/config/d4_runtime_contract_spec.rb ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+ require "open3"
5
+ require "rbconfig"
6
+ require "tempfile"
7
+ require "bundler"
8
+
9
+ # D4 runtime contract: proves the absence of active Redis/Sidekiq runtime
10
+ # behavior at the source/config, dependency, resolved-runtime, and Rack::Attack
11
+ # levels while retaining Solid Queue as the Active Job runtime target.
12
+ RSpec.describe "D4 runtime contract" do
13
+ def project_root
14
+ @project_root ||= Pathname(__dir__).join("../..").expand_path
15
+ end
16
+
17
+ def relative(*segments)
18
+ project_root.join(*segments)
19
+ end
20
+
21
+ def run_probe(environment, script)
22
+ stdout, stderr, status = Open3.capture3(
23
+ environment, RbConfig.ruby, "-e", script, chdir: project_root.to_s
24
+ )
25
+ [ stdout, stderr, status ]
26
+ end
27
+
28
+ describe "active runtime source/config contract" do
29
+ it "does not retain the legacy Sidekiq initializer" do
30
+ expect(relative("config/initializers/sidekiq.rb")).not_to exist
31
+ end
32
+
33
+ it "does not retain the legacy Sidekiq worker YAML" do
34
+ expect(relative("config/sidekiq.yml")).not_to exist
35
+ end
36
+
37
+ it "does not select Sidekiq as the base Active Job adapter" do
38
+ application = relative("config/application.rb").read
39
+ expect(application).not_to include("queue_adapter = :sidekiq")
40
+ end
41
+
42
+ it "does not configure a Redis cache store" do
43
+ application = relative("config/application.rb").read
44
+ expect(application).not_to include("redis_cache_store")
45
+ end
46
+
47
+ it "does not read REDIS_URL from any active runtime source" do
48
+ runtime_paths = %w[
49
+ config/application.rb
50
+ config/initializers/rack_attack.rb
51
+ config/initializers/sidekiq.rb
52
+ app/controllers/api/v1/health_controller.rb
53
+ bin/jobs
54
+ config/queue.yml
55
+ ]
56
+
57
+ offenders = runtime_paths.filter_map do |rel_path|
58
+ full = relative(rel_path)
59
+ next unless full.exist?
60
+
61
+ full.read.lines.filter_map.with_index(1) do |line, number|
62
+ "#{rel_path}:#{number}" if line.include?("REDIS_URL")
63
+ end
64
+ end.flatten
65
+
66
+ expect(offenders).to be_empty
67
+ end
68
+
69
+ it "does not construct Redis or query Sidekiq in the health controller" do
70
+ health = relative("app/controllers/api/v1/health_controller.rb").read
71
+ expect(health).not_to include("Redis.new")
72
+ expect(health).not_to include("Sidekiq::Stats")
73
+ end
74
+ end
75
+
76
+ describe "dependency contract" do
77
+ it "resolves neither redis nor sidekiq dependencies while retaining solid_queue" do
78
+ names = Bundler.load.specs.map(&:name)
79
+
80
+ expect(names).not_to include("redis")
81
+ expect(names).not_to include("sidekiq")
82
+ expect(names).not_to include("sidekiq-scheduler")
83
+ expect(names).to include("solid_queue")
84
+ end
85
+ end
86
+
87
+ describe "application runtime contract" do
88
+ it "resolves Active Job to Solid Queue in the development environment" do
89
+ probe = <<~'RUBY'
90
+ result_path = ENV.fetch("D4_PROBE_RESULT")
91
+ require File.expand_path("config/environment", Dir.pwd)
92
+ File.write(result_path, "ADAPTER=#{ActiveJob::Base.queue_adapter.class.name}\n")
93
+ RUBY
94
+
95
+ Tempfile.create("d4-dev-adapter") do |result|
96
+ environment = {
97
+ "DATABASE_URL" => ENV.fetch("D3_TEST_DATABASE_URL"),
98
+ "RAILS_ENV" => "development",
99
+ "D4_PROBE_RESULT" => result.path,
100
+ "RAILS_MASTER_KEY" => nil,
101
+ "SECRET_KEY_BASE" => nil,
102
+ "SECRET_KEY_BASE_DUMMY" => "1"
103
+ }
104
+
105
+ _stdout, stderr, status = run_probe(environment, probe)
106
+ probe_result = File.read(result.path)
107
+
108
+ expect(status).to be_success, -> { "Development boot failed.\n#{probe_result}#{stderr}" }
109
+ expect(probe_result).to include("ADAPTER=ActiveJob::QueueAdapters::SolidQueueAdapter")
110
+ end
111
+ end
112
+
113
+ it "resolves Active Job to Solid Queue in the production environment" do
114
+ probe = <<~'RUBY'
115
+ result_path = ENV.fetch("D4_PROBE_RESULT")
116
+ require File.expand_path("config/environment", Dir.pwd)
117
+ File.write(result_path, "ADAPTER=#{ActiveJob::Base.queue_adapter.class.name}\n")
118
+ RUBY
119
+
120
+ Tempfile.create("d4-prod-adapter") do |result|
121
+ environment = {
122
+ "DATABASE_URL" => ENV.fetch("D3_TEST_DATABASE_URL"),
123
+ "RAILS_ENV" => "production",
124
+ "D4_PROBE_RESULT" => result.path,
125
+ "RAILS_MASTER_KEY" => nil,
126
+ "SECRET_KEY_BASE" => nil,
127
+ "SECRET_KEY_BASE_DUMMY" => "1",
128
+ "R2_ENDPOINT" => "https://example.invalid",
129
+ "R2_ACCESS_KEY_ID" => "r2-contract-access-key",
130
+ "R2_SECRET_ACCESS_KEY" => "r2-contract-secret",
131
+ "R2_BUCKET" => "r2-contract-bucket",
132
+ "R2_REGION" => "auto"
133
+ }
134
+
135
+ _stdout, stderr, status = run_probe(environment, probe)
136
+ probe_result = File.read(result.path)
137
+
138
+ expect(status).to be_success, -> { "Production boot failed.\n#{probe_result}#{stderr}" }
139
+ expect(probe_result).to include("ADAPTER=ActiveJob::QueueAdapters::SolidQueueAdapter")
140
+ end
141
+ end
142
+
143
+ it "boots the development application without REDIS_URL" do
144
+ probe = <<~'RUBY'
145
+ result_path = ENV.fetch("D4_PROBE_RESULT")
146
+ require File.expand_path("config/environment", Dir.pwd)
147
+ File.write(result_path, "BOOT=PASS\n")
148
+ RUBY
149
+
150
+ Tempfile.create("d4-dev-boot") do |result|
151
+ environment = {
152
+ "DATABASE_URL" => ENV.fetch("D3_TEST_DATABASE_URL"),
153
+ "RAILS_ENV" => "development",
154
+ "D4_PROBE_RESULT" => result.path,
155
+ "RAILS_MASTER_KEY" => nil,
156
+ "SECRET_KEY_BASE" => nil,
157
+ "SECRET_KEY_BASE_DUMMY" => "1",
158
+ "REDIS_URL" => nil
159
+ }
160
+
161
+ _stdout, stderr, status = run_probe(environment, probe)
162
+ probe_result = File.read(result.path)
163
+
164
+ expect(status).to be_success, -> { "Boot without REDIS_URL failed.\n#{probe_result}#{stderr}" }
165
+ expect(probe_result).to eq("BOOT=PASS\n")
166
+ end
167
+ end
168
+ end
169
+
170
+ describe "Rack::Attack store contract" do
171
+ it "uses a non-Redis store in the development environment" do
172
+ probe = <<~'RUBY'
173
+ result_path = ENV.fetch("D4_PROBE_RESULT")
174
+ require File.expand_path("config/environment", Dir.pwd)
175
+ File.write(result_path, "STORE=#{Rack::Attack.cache.store.class.name}\n")
176
+ RUBY
177
+
178
+ Tempfile.create("d4-rack-attack-store") do |result|
179
+ environment = {
180
+ "DATABASE_URL" => ENV.fetch("D3_TEST_DATABASE_URL"),
181
+ "RAILS_ENV" => "development",
182
+ "D4_PROBE_RESULT" => result.path,
183
+ "RAILS_MASTER_KEY" => nil,
184
+ "SECRET_KEY_BASE" => nil,
185
+ "SECRET_KEY_BASE_DUMMY" => "1",
186
+ "REDIS_URL" => nil
187
+ }
188
+
189
+ _stdout, stderr, status = run_probe(environment, probe)
190
+ probe_result = File.read(result.path)
191
+
192
+ expect(status).to be_success, -> { "Rack::Attack probe failed.\n#{probe_result}#{stderr}" }
193
+ expect(probe_result).to include("STORE=ActiveSupport::Cache::MemoryStore")
194
+ end
195
+ end
196
+ end
197
+ end
spec/config/d8_docker_contract_spec.rb ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+ require "yaml"
5
+
6
+ RSpec.describe "D8 Docker and Hugging Face contract" do
7
+ let(:project_root) { Pathname(__dir__).join("../..").expand_path }
8
+ let(:dockerfile) { project_root.join("Dockerfile").read }
9
+
10
+ it "precompiles assets with non-secret values for every required production boot variable" do
11
+ precompile_command = dockerfile[/RUN SECRET_KEY_BASE_DUMMY=1.*?assets:precompile/m]
12
+
13
+ expect(precompile_command).to include("SECRET_KEY_BASE_DUMMY=1")
14
+ expect(precompile_command).to include("DATABASE_URL=postgresql://127.0.0.1:1/rails_8_blog_build")
15
+ %w[R2_ENDPOINT R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY R2_BUCKET R2_REGION].each do |name|
16
+ expect(precompile_command).to match(/#{name}=[^\s]+/)
17
+ end
18
+ end
19
+
20
+ it "exposes the Hugging Face ingress port through Thruster" do
21
+ expect(dockerfile).to include("EXPOSE 7860")
22
+ expect(dockerfile).to include('CMD ["./bin/thrust", "./bin/rails", "server"]')
23
+ end
24
+
25
+ it "ships a Docker Space metadata template separate from the project README" do
26
+ template = project_root.join("deploy/huggingface/README.md")
27
+
28
+ expect(template).to exist
29
+ metadata = YAML.safe_load(template.read.split("---", 3)[1])
30
+ expect(metadata).to include("sdk" => "docker", "app_port" => 7860)
31
+ end
32
+
33
+ it "excludes secrets and test artifacts from the Docker build context" do
34
+ dockerignore = project_root.join(".dockerignore").read
35
+
36
+ expect(dockerignore).to include("/.env*")
37
+ expect(dockerignore).to include("/config/master.key")
38
+ expect(dockerignore).to include("/coverage")
39
+ end
40
+
41
+ it "fits the Solid Queue worker pool within the three-connection Puma runtime pool" do
42
+ queue_config = YAML.safe_load(project_root.join("config/queue.yml").read, aliases: true)
43
+
44
+ expect(queue_config.fetch("default").fetch("workers").first.fetch("threads")).to eq(1)
45
+ end
46
+ end
spec/config/d8_hugging_face_host_authorization_spec.rb ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require "pathname"
5
+
6
+ RSpec.describe "D8 Hugging Face host authorization" do
7
+ let(:project_root) { Pathname(__dir__).join("../..").expand_path }
8
+
9
+ def health_status_for(host)
10
+ probe = <<~RUBY
11
+ require "rack/mock"
12
+ require "./config/environment"
13
+
14
+ response = Rack::MockRequest.new(Rails.application).get("/up", "HTTP_HOST" => ENV.fetch("D8_PROBE_HOST"))
15
+ puts response.status
16
+ RUBY
17
+
18
+ output, error, status = Open3.capture3(
19
+ {
20
+ "RAILS_ENV" => "production",
21
+ "RACK_ENV" => "production",
22
+ "SECRET_KEY_BASE_DUMMY" => "1",
23
+ "DATABASE_URL" => ENV.fetch("D3_TEST_DATABASE_URL"),
24
+ "R2_ENDPOINT" => "https://example.invalid",
25
+ "R2_ACCESS_KEY_ID" => "d8-host-probe-key",
26
+ "R2_SECRET_ACCESS_KEY" => "d8-host-probe-secret",
27
+ "R2_BUCKET" => "d8-host-probe-bucket",
28
+ "R2_REGION" => "auto",
29
+ "SPACE_HOST" => "d8-qualification.hf.space",
30
+ "D8_PROBE_HOST" => host
31
+ },
32
+ RbConfig.ruby,
33
+ "-e",
34
+ probe,
35
+ chdir: project_root.to_s
36
+ )
37
+
38
+ expect(status).to be_success, error
39
+ output.lines.last.to_i
40
+ end
41
+
42
+ it "accepts the local and Hugging Face health hosts but rejects an untrusted host" do
43
+ expect(health_status_for("127.0.0.1")).to eq(200)
44
+ expect(health_status_for("d8-qualification.hf.space")).to eq(200)
45
+ expect(health_status_for("untrusted.example")).to eq(403)
46
+ end
47
+ end
spec/config/postgresql_adapter_spec.rb ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "rails_helper"
4
+
5
+ RSpec.describe "PostgreSQL database adapter" do
6
+ it "uses PostgreSQL for the test environment" do
7
+ expect(ActiveRecord::Base.connection.adapter_name).to eq("PostgreSQL")
8
+ end
9
+ end
spec/config/production_boot_spec.rb ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require "pathname"
5
+ require "rbconfig"
6
+ require "tempfile"
7
+
8
+ RSpec.describe "production boot" do
9
+ project_root = Pathname(__dir__).join("../..").expand_path
10
+ database_url = ENV.fetch("D3_TEST_DATABASE_URL")
11
+
12
+ application_probe = <<~'RUBY'
13
+ require File.expand_path("config/application", Dir.pwd)
14
+ puts "APPLICATION_BUNDLER_REQUIRE=PASS"
15
+ RUBY
16
+
17
+ boot_probe = <<~'RUBY'
18
+ result_path = ENV.fetch("PRODUCTION_BOOT_RESULT")
19
+
20
+ TracePoint.new(:raise) do |trace|
21
+ error = trace.raised_exception
22
+ next unless error.class.name == "ActiveRecord::AdapterNotSpecified"
23
+
24
+ File.write(
25
+ result_path,
26
+ "EXCEPTION_CLASS=#{error.class}\nEXCEPTION_MESSAGE=#{error.message}\n"
27
+ )
28
+ end.enable
29
+
30
+ require File.expand_path("config/environment", Dir.pwd)
31
+ File.write(result_path, "PRODUCTION_BOOT=PASS\n")
32
+ RUBY
33
+
34
+ cache_probe = <<~'RUBY'
35
+ result_path = ENV.fetch("PRODUCTION_CACHE_RESULT")
36
+ require File.expand_path("config/environment", Dir.pwd)
37
+
38
+ cache = Rails.cache
39
+ expected_class = "ActiveSupport::Cache::MemoryStore"
40
+ raise "unexpected cache backend: #{cache.class.name}" unless cache.class.name == expected_class
41
+
42
+ key = "d0-r6-cache-#{Process.pid}-#{Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)}"
43
+ value = "memory-store-round-trip"
44
+
45
+ raise "cache write failed" unless cache.write(key, value)
46
+ raise "cache read failed" unless cache.read(key) == value
47
+ raise "cache delete failed" unless cache.delete(key)
48
+ raise "cache key survived delete" unless cache.read(key).nil?
49
+
50
+ File.write(
51
+ result_path,
52
+ "CACHE_BACKEND_CLASS=#{cache.class.name}\nCACHE_ROUND_TRIP=PASS\n"
53
+ )
54
+ RUBY
55
+
56
+ it "initializes the production application without an undefined database role" do
57
+ Tempfile.create("production-boot-result") do |result|
58
+ environment = {
59
+ "DATABASE_URL" => database_url,
60
+ "PRODUCTION_BOOT_RESULT" => result.path,
61
+ "RAILS_ENV" => "production",
62
+ "RAILS_MASTER_KEY" => nil,
63
+ "SECRET_KEY_BASE" => nil,
64
+ "SECRET_KEY_BASE_DUMMY" => "1",
65
+ "R2_ENDPOINT" => "https://example.invalid",
66
+ "R2_ACCESS_KEY_ID" => "r2-contract-access-key",
67
+ "R2_SECRET_ACCESS_KEY" => "r2-contract-secret",
68
+ "R2_BUCKET" => "r2-contract-bucket",
69
+ "R2_REGION" => "auto"
70
+ }
71
+
72
+ stdout, stderr, status = Open3.capture3(
73
+ environment,
74
+ RbConfig.ruby,
75
+ "-e",
76
+ boot_probe,
77
+ chdir: project_root.to_s
78
+ )
79
+ probe_result = File.read(result.path)
80
+
81
+ expect(status).to be_success, -> {
82
+ "Production initialization failed.\n#{probe_result}#{stdout}#{stderr}"
83
+ }
84
+ expect(probe_result).to eq("PRODUCTION_BOOT=PASS\n")
85
+ end
86
+ end
87
+
88
+ it "boots despite Mobility ActionText's nonstandard require path" do
89
+ environment = {
90
+ "RAILS_ENV" => "production",
91
+ "RAILS_MASTER_KEY" => nil,
92
+ "SECRET_KEY_BASE" => nil,
93
+ "SECRET_KEY_BASE_DUMMY" => "1"
94
+ }
95
+
96
+ stdout, stderr, status = Open3.capture3(
97
+ environment,
98
+ RbConfig.ruby,
99
+ "-e",
100
+ application_probe,
101
+ chdir: project_root.to_s
102
+ )
103
+
104
+ expect(status).to be_success, -> { "Application Bundler boot failed.\n#{stdout}#{stderr}" }
105
+ expect(stdout).to include("APPLICATION_BUNDLER_REQUIRE=PASS\n")
106
+ end
107
+
108
+ it "uses MemoryStore for production cache operations" do
109
+ Tempfile.create("production-cache-result") do |result|
110
+ environment = {
111
+ "DATABASE_URL" => database_url,
112
+ "PRODUCTION_CACHE_RESULT" => result.path,
113
+ "RAILS_ENV" => "production",
114
+ "RAILS_MASTER_KEY" => nil,
115
+ "SECRET_KEY_BASE" => nil,
116
+ "SECRET_KEY_BASE_DUMMY" => "1",
117
+ "R2_ENDPOINT" => "https://example.invalid",
118
+ "R2_ACCESS_KEY_ID" => "r2-contract-access-key",
119
+ "R2_SECRET_ACCESS_KEY" => "r2-contract-secret",
120
+ "R2_BUCKET" => "r2-contract-bucket",
121
+ "R2_REGION" => "auto"
122
+ }
123
+
124
+ stdout, stderr, status = Open3.capture3(
125
+ environment,
126
+ RbConfig.ruby,
127
+ "-e",
128
+ cache_probe,
129
+ chdir: project_root.to_s
130
+ )
131
+ probe_result = File.read(result.path)
132
+
133
+ expect(status).to be_success, -> {
134
+ "Production cache probe failed.\n#{probe_result}#{stdout}#{stderr}"
135
+ }
136
+ expect(probe_result).to eq(
137
+ "CACHE_BACKEND_CLASS=ActiveSupport::Cache::MemoryStore\nCACHE_ROUND_TRIP=PASS\n"
138
+ )
139
+ end
140
+ end
141
+ end
spec/config/solid_queue_primary_database_spec.rb ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require "pathname"
5
+ require "rbconfig"
6
+
7
+ RSpec.describe "Solid Queue primary database topology" do
8
+ project_root = Pathname(__dir__).join("../..").expand_path
9
+ queue_tables = %w[
10
+ solid_queue_blocked_executions
11
+ solid_queue_claimed_executions
12
+ solid_queue_failed_executions
13
+ solid_queue_jobs
14
+ solid_queue_pauses
15
+ solid_queue_processes
16
+ solid_queue_ready_executions
17
+ solid_queue_recurring_executions
18
+ solid_queue_recurring_tasks
19
+ solid_queue_scheduled_executions
20
+ solid_queue_semaphores
21
+ ].freeze
22
+
23
+ production_database_url = -> { ENV.fetch("D3_TEST_DATABASE_URL") }
24
+
25
+ production_environment = lambda do
26
+ {
27
+ "DATABASE_URL" => production_database_url.call,
28
+ "RAILS_ENV" => "production",
29
+ "RAILS_MASTER_KEY" => nil,
30
+ "SECRET_KEY_BASE" => nil,
31
+ "SECRET_KEY_BASE_DUMMY" => "1",
32
+ "R2_ENDPOINT" => "https://example.invalid",
33
+ "R2_ACCESS_KEY_ID" => "r2-contract-access-key",
34
+ "R2_SECRET_ACCESS_KEY" => "r2-contract-secret",
35
+ "R2_BUCKET" => "r2-contract-bucket",
36
+ "R2_REGION" => "auto"
37
+ }
38
+ end
39
+
40
+ run_rails = lambda do |environment, *arguments|
41
+ Open3.capture3(
42
+ environment,
43
+ RbConfig.ruby,
44
+ "bin/rails",
45
+ *arguments,
46
+ chdir: project_root.to_s
47
+ )
48
+ end
49
+
50
+ it "creates every Solid Queue table through normal primary migrations" do
51
+ environment = production_environment.call
52
+ _stdout, stderr, status = run_rails.call(environment, "db:migrate")
53
+
54
+ expect(status).to be_success, stderr
55
+
56
+ probe = <<~RUBY
57
+ expected = #{queue_tables.inspect}
58
+ actual = ActiveRecord::Base.connection.data_sources & expected
59
+ abort "missing Solid Queue tables: \#{expected - actual}" unless actual.sort == expected.sort
60
+ puts "SOLID_QUEUE_TABLES=PASS"
61
+ RUBY
62
+ stdout, stderr, status = run_rails.call(environment, "runner", probe)
63
+
64
+ expect(status).to be_success, stderr
65
+ expect(stdout).to include("SOLID_QUEUE_TABLES=PASS")
66
+ end
67
+
68
+ it "persists a harmless Active Job through the production Solid Queue adapter" do
69
+ environment = production_environment.call
70
+ _stdout, stderr, status = run_rails.call(environment, "db:migrate")
71
+
72
+ expect(status).to be_success, stderr
73
+
74
+ probe = <<~'RUBY'
75
+ class SolidQueuePersistenceProbeJob < ActiveJob::Base
76
+ def perform(*) = nil
77
+ end
78
+
79
+ adapter = ActiveJob::Base.queue_adapter
80
+ abort "unexpected adapter: #{adapter.class.name}" unless adapter.class.name.end_with?("SolidQueueAdapter")
81
+
82
+ job = SolidQueuePersistenceProbeJob.perform_later("probe")
83
+ record = SolidQueue::Job.find_by(active_job_id: job.job_id)
84
+ abort "enqueued job was not persisted" unless record
85
+
86
+ puts "ACTIVE_JOB_ADAPTER=solid_queue"
87
+ puts "PERSISTED_JOB_FOUND=true"
88
+
89
+ record.destroy!
90
+ RUBY
91
+ stdout, stderr, status = run_rails.call(environment, "runner", probe)
92
+
93
+ expect(status).to be_success, stderr
94
+ expect(stdout).to include("ACTIVE_JOB_ADAPTER=solid_queue")
95
+ expect(stdout).to include("PERSISTED_JOB_FOUND=true")
96
+ end
97
+ end
spec/controllers/admin/audit_logs_controller_spec.rb ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ require "rails_helper"
2
+
3
+ RSpec.describe Admin::AuditLogsController, type: :controller do
4
+ let(:admin) { User.create!(email: "admin@example.com", full_name: "Admin", role: "admin", password: "Password123!", confirmed_at: Time.current) }
5
+ let(:author) { User.create!(email: "author@example.com", full_name: "Author", role: "author", password: "Password123!", confirmed_at: Time.current) }
6
+
7
+ before do
8
+ sign_in admin
9
+ end
10
+
11
+ describe "GET #index" do
12
+ let!(:log1) { BlockedRequestLog.create!(ip: "1.2.3.4", reason: "throttled", path: "/auth/sign_in") }
13
+ let!(:log2) { BlockedRequestLog.create!(ip: "5.6.7.8", reason: "blocklisted", path: "/api/v1/posts") }
14
+ let!(:log3) { BlockedRequestLog.create!(ip: "1.2.3.4", reason: "throttled", path: "/auth/sign_in") }
15
+
16
+ it "returns success" do
17
+ get :index, params: { locale: "en" }
18
+ expect(response).to be_successful
19
+ end
20
+
21
+ it "assigns all logs" do
22
+ get :index, params: { locale: "en" }
23
+ expect(assigns(:blocked_logs)).to match_array([ log1, log2, log3 ])
24
+ end
25
+
26
+ it "filters by IP when provided" do
27
+ get :index, params: { locale: "en", ip: "1.2.3.4" }
28
+ expect(assigns(:blocked_logs)).to contain_exactly(log1, log3)
29
+ end
30
+
31
+ it "filters by reason when provided" do
32
+ get :index, params: { locale: "en", reason: "blocklisted" }
33
+ expect(assigns(:blocked_logs)).to contain_exactly(log2)
34
+ end
35
+
36
+ it "paginates results" do
37
+ get :index, params: { locale: "en" }
38
+ expect(assigns(:pagy)).to be_present
39
+ end
40
+ end
41
+
42
+ describe "authorization" do
43
+ context "when user is not admin" do
44
+ before do
45
+ sign_out admin
46
+ sign_in author
47
+ end
48
+
49
+ it "redirects to root path" do
50
+ get :index, params: { locale: "en" }
51
+ expect(response).to redirect_to("/en")
52
+ end
53
+ end
54
+
55
+ context "when user is not signed in" do
56
+ before do
57
+ sign_out admin
58
+ end
59
+
60
+ it "redirects to sign in page" do
61
+ get :index, params: { locale: "en" }
62
+ expect(response).to redirect_to(new_user_session_path)
63
+ end
64
+ end
65
+ end
66
+ end
spec/controllers/admin/dashboard_controller_spec.rb ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ require "rails_helper"
2
+
3
+ RSpec.describe "Admin::Dashboard", type: :request do
4
+ let(:admin) { User.create!(email: "admin_dashboard@example.com", full_name: "Admin", role: "admin", password: "Password123!", confirmed_at: Time.current) }
5
+
6
+ before do
7
+ sign_in admin
8
+ end
9
+
10
+ describe "GET /en/admin" do
11
+ it "returns success" do
12
+ get "/en/admin"
13
+ expect(response).to be_successful
14
+ end
15
+ end
16
+ end
spec/controllers/admin/settings_controller_spec.rb ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ require "rails_helper"
2
+
3
+ RSpec.describe "Admin::Settings", type: :request do
4
+ let(:admin) { User.create!(email: "admin_settings@example.com", full_name: "Admin", role: "admin", password: "Password123!", confirmed_at: Time.current) }
5
+
6
+ before do
7
+ sign_in admin
8
+ Setting.create!(key: "test_string", value: "hello", value_type: "string", category: "general")
9
+ Setting.create!(key: "test_integer", value: "42", value_type: "integer", category: "general")
10
+ Setting.create!(key: "test_boolean", value: "true", value_type: "boolean", category: "general")
11
+ end
12
+
13
+ describe "GET /en/admin/settings" do
14
+ it "returns success" do
15
+ get "/en/admin/settings"
16
+ expect(response).to be_successful
17
+ end
18
+ end
19
+
20
+ describe "PATCH /en/admin/settings" do
21
+ it "updates string setting" do
22
+ patch "/en/admin/settings", params: { settings: { test_string: "world" } }
23
+ expect(Setting.get("test_string")).to eq("world")
24
+ end
25
+
26
+ it "updates integer setting" do
27
+ patch "/en/admin/settings", params: { settings: { test_integer: "100" } }
28
+ expect(Setting.get("test_integer")).to eq(100)
29
+ end
30
+
31
+ it "updates boolean setting" do
32
+ patch "/en/admin/settings", params: { settings: { test_boolean: "1" } }
33
+ expect(Setting.get("test_boolean")).to eq(true)
34
+ end
35
+ end
36
+ end
spec/controllers/api/v1/auth/sessions_controller_spec.rb ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ require 'rails_helper'
2
+
3
+ RSpec.describe Api::V1::Auth::SessionsController, type: :routing do
4
+ describe "routes" do
5
+ it "POST #create routes correctly" do
6
+ expect(post: "/api/v1/auth/sign_in").to route_to(controller: "api/v1/auth/sessions", action: "create")
7
+ end
8
+
9
+ it "DELETE #destroy routes correctly" do
10
+ expect(delete: "/api/v1/auth/sign_out").to route_to(controller: "api/v1/auth/sessions", action: "destroy")
11
+ end
12
+ end
13
+ end
spec/controllers/api/v1/base_controller_spec.rb ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ require 'rails_helper'
2
+
3
+ RSpec.describe Api::V1::BaseController, type: :controller do
4
+ include Devise::Test::ControllerHelpers
5
+
6
+ controller do
7
+ def test_action
8
+ render json: { status: 'ok' }
9
+ end
10
+
11
+ private
12
+ def action_allows_anonymous?
13
+ true
14
+ end
15
+ end
16
+
17
+ before do
18
+ routes.draw { get :test_action, to: 'api/v1/base#test_action' }
19
+ @request.env['devise.mapping'] = Devise.mappings[:user]
20
+ end
21
+
22
+ describe "authentication" do
23
+ context "with valid JWT token in header" do
24
+ it "signs in the user" do
25
+ user = create(:user)
26
+ # We need to use Warden::JWTAuth to generate a proper token that devise-jwt understands
27
+ # or at least ensure the secret and payload are correct.
28
+ # devise-jwt expects 'jti' if using Denylist.
29
+ payload = { 'sub' => user.id, 'scp' => 'user', 'jti' => user.jti }
30
+ token = JWT.encode(payload, ENV.fetch("DEVISE_JWT_SECRET_KEY", "default_secret_for_development"), "HS256")
31
+ request.headers['Authorization'] = "Bearer #{token}"
32
+
33
+ get :test_action
34
+
35
+ expect(controller.current_user).to eq(user)
36
+ end
37
+ end
38
+
39
+ context "with invalid token" do
40
+ it "does not sign in user" do
41
+ request.headers['Authorization'] = "Bearer invalid_token"
42
+
43
+ get :test_action
44
+
45
+ expect(controller.current_user).to be_nil
46
+ end
47
+ end
48
+
49
+ context "without token" do
50
+ before do
51
+ # We need to override action_allows_anonymous? to false for this specific test
52
+ # but since it's an anonymous controller, it's hard to change per test.
53
+ # Instead, let's just test that it's nil.
54
+ end
55
+ it "does not sign in user" do
56
+ get :test_action
57
+
58
+ expect(controller.current_user).to be_nil
59
+ end
60
+ end
61
+ end
62
+
63
+ describe "#set_locale" do
64
+ context "with Accept-Language header" do
65
+ it "sets locale to vi" do
66
+ request.headers['Accept-Language'] = 'vi'
67
+
68
+ get :test_action
69
+
70
+ expect(I18n.locale).to eq(:vi)
71
+ end
72
+ end
73
+
74
+ context "with locale param" do
75
+ it "sets locale from param" do
76
+ get :test_action, params: { locale: 'ja' }
77
+
78
+ expect(I18n.locale).to eq(:ja)
79
+ end
80
+ end
81
+
82
+ context "with invalid locale" do
83
+ it "falls back to default locale" do
84
+ get :test_action, params: { locale: 'invalid' }
85
+
86
+ expect(I18n.locale).to eq(:en)
87
+ end
88
+ end
89
+ end
90
+
91
+ describe "rescue from Pundit::NotAuthorizedError" do
92
+ it "returns 403 forbidden" do
93
+ # We override the action to raise the error
94
+ controller.class_eval do
95
+ def test_action
96
+ raise Pundit::NotAuthorizedError
97
+ end
98
+ end
99
+
100
+ get :test_action
101
+
102
+ expect(response).to have_http_status(:forbidden)
103
+ json = JSON.parse(response.body)
104
+ expect(json['error']).to eq('Forbidden')
105
+ end
106
+ end
107
+ end