Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4f5812d737 | |||
| b47cdc7ad7 | |||
| a5ea66d660 | |||
| efaeb5325e | |||
| e40f7a3620 | |||
| e8be071064 | |||
| be40b4bcc4 | |||
| fb275b4763 | |||
| ef6219dcb1 | |||
| 04b01bf1c6 | |||
| 4c474d2bdf |
@@ -1,14 +1,16 @@
|
|||||||
class ApplicationController < ActionController::API
|
class ApplicationController < ActionController::API
|
||||||
|
before_action :reject_banned_ip_address!
|
||||||
before_action :authenticate_user
|
before_action :authenticate_user
|
||||||
|
before_action :reject_banned_user!
|
||||||
|
|
||||||
def current_user
|
def current_user = @current_user
|
||||||
@current_user
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def authenticate_user
|
def authenticate_user
|
||||||
code = request.headers['X-Transfer-Code'] || request.headers['HTTP_X_TRANSFER_CODE']
|
code = request.headers['X-Transfer-Code'] || request.headers['HTTP_X_TRANSFER_CODE']
|
||||||
|
return if code.blank?
|
||||||
|
|
||||||
@current_user = User.find_by(inheritance_code: code)
|
@current_user = User.find_by(inheritance_code: code)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -22,4 +24,17 @@ class ApplicationController < ActionController::API
|
|||||||
s.in?(['', '1', 'true', 'on', 'yes'])
|
s.in?(['', '1', 'true', 'on', 'yes'])
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def reject_banned_ip_address!
|
||||||
|
ip_address = IpAddress.find_by(ip_address: IPAddr.new(request.remote_ip).hton)
|
||||||
|
return unless ip_address&.banned?
|
||||||
|
|
||||||
|
head :forbidden
|
||||||
|
end
|
||||||
|
|
||||||
|
def reject_banned_user!
|
||||||
|
return unless current_user&.banned?
|
||||||
|
|
||||||
|
head :forbidden
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
class UsersController < ApplicationController
|
class UsersController < ApplicationController
|
||||||
def create
|
def create
|
||||||
return head :unprocessable_entity if request.remote_ip.blank?
|
|
||||||
|
|
||||||
user = nil
|
user = nil
|
||||||
|
|
||||||
User.transaction do
|
User.transaction do
|
||||||
user = User.create!(inheritance_code: SecureRandom.uuid, role: :guest)
|
user = User.create!(inheritance_code: SecureRandom.uuid, role: :guest)
|
||||||
attach_ip_address!(user)
|
attach_ip_address!(user)
|
||||||
@@ -17,8 +14,7 @@ class UsersController < ApplicationController
|
|||||||
def verify
|
def verify
|
||||||
user = User.find_by(inheritance_code: params[:code])
|
user = User.find_by(inheritance_code: params[:code])
|
||||||
return render json: { valid: false } unless user
|
return render json: { valid: false } unless user
|
||||||
|
return head :forbidden if user.banned?
|
||||||
return head :unprocessable_entity if request.remote_ip.blank?
|
|
||||||
|
|
||||||
attach_ip_address!(user)
|
attach_ip_address!(user)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
require 'digest'
|
||||||
|
|
||||||
|
|
||||||
|
class WikiAssetsController < ApplicationController
|
||||||
|
def index
|
||||||
|
page_id = params[:wiki_page_id].to_i
|
||||||
|
page = WikiPage.find_by(id: page_id)
|
||||||
|
return head :not_found unless page
|
||||||
|
|
||||||
|
render json: WikiAssetRepr.many(page.assets)
|
||||||
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
return head :unauthorized unless current_user
|
||||||
|
return head :forbidden unless current_user.gte_member?
|
||||||
|
|
||||||
|
wiki_page_id = params[:wiki_page_id].to_i
|
||||||
|
page = WikiPage.find_by(id: wiki_page_id)
|
||||||
|
return head :not_found unless page
|
||||||
|
|
||||||
|
file = params[:file]
|
||||||
|
return head :bad_request if file.blank?
|
||||||
|
|
||||||
|
asset = nil
|
||||||
|
page.with_lock do
|
||||||
|
no = page.next_asset_no
|
||||||
|
alt_text = params[:alt_text].presence
|
||||||
|
sha256 = Digest::SHA256.file(file.tempfile.path).digest
|
||||||
|
|
||||||
|
asset = WikiAsset.new(wiki_page_id:, no:, alt_text:, sha256:, created_by_user: current_user)
|
||||||
|
asset.file.attach(file)
|
||||||
|
asset.save!
|
||||||
|
|
||||||
|
page.update!(next_asset_no: no + 1)
|
||||||
|
end
|
||||||
|
|
||||||
|
render json: WikiAssetRepr.base(asset)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -109,7 +109,7 @@ class WikiPagesController < ApplicationController
|
|||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless current_user.gte_member?
|
return head :forbidden unless current_user.gte_member?
|
||||||
|
|
||||||
title = params[:title]&.strip
|
title = params[:title].to_s.strip
|
||||||
body = params[:body].to_s
|
body = params[:body].to_s
|
||||||
|
|
||||||
return head :unprocessable_entity if title.blank? || body.blank?
|
return head :unprocessable_entity if title.blank? || body.blank?
|
||||||
@@ -143,7 +143,14 @@ class WikiPagesController < ApplicationController
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
head :ok
|
message = params[:message].presence
|
||||||
|
Wiki::Commit.content!(page:,
|
||||||
|
body:,
|
||||||
|
created_user: current_user,
|
||||||
|
message:,
|
||||||
|
base_revision_id:)
|
||||||
|
|
||||||
|
render json: WikiPageRepr.base(page).merge(body:)
|
||||||
end
|
end
|
||||||
|
|
||||||
def search
|
def search
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
class IpAddress < ApplicationRecord
|
class IpAddress < ApplicationRecord
|
||||||
validates :ip_address, presence: true, length: { maximum: 16 }
|
validates :ip_address, presence: true, length: { maximum: 16 }
|
||||||
validates :banned, inclusion: { in: [true, false] }
|
|
||||||
|
|
||||||
has_many :user_ips, dependent: :destroy
|
has_many :user_ips, dependent: :destroy
|
||||||
has_many :users, through: :user_ips
|
has_many :users, through: :user_ips
|
||||||
|
|
||||||
|
def banned? = banned_at.present?
|
||||||
|
def ban! = banned? || update!(banned_at: Time.current)
|
||||||
|
def unban! = update!(banned_at: nil)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ class PostVersion < ApplicationRecord
|
|||||||
include VersionRecord
|
include VersionRecord
|
||||||
|
|
||||||
belongs_to :post
|
belongs_to :post
|
||||||
belongs_to :parent, class_name: 'Post', optional: true
|
|
||||||
|
|
||||||
validates :url, presence: true
|
validates :url, presence: true
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ class User < ApplicationRecord
|
|||||||
validates :name, length: { maximum: 255 }
|
validates :name, length: { maximum: 255 }
|
||||||
validates :inheritance_code, presence: true, length: { maximum: 64 }
|
validates :inheritance_code, presence: true, length: { maximum: 64 }
|
||||||
validates :role, presence: true, inclusion: { in: roles.keys }
|
validates :role, presence: true, inclusion: { in: roles.keys }
|
||||||
validates :banned, inclusion: { in: [true, false] }
|
|
||||||
|
|
||||||
has_many :created_posts,
|
has_many :created_posts,
|
||||||
class_name: 'Post', foreign_key: :uploaded_user_id, dependent: :nullify
|
class_name: 'Post', foreign_key: :uploaded_user_id, dependent: :nullify
|
||||||
@@ -19,5 +18,10 @@ class User < ApplicationRecord
|
|||||||
class_name: 'WikiPage', foreign_key: :updated_user_id, dependent: :nullify
|
class_name: 'WikiPage', foreign_key: :updated_user_id, dependent: :nullify
|
||||||
|
|
||||||
def viewed?(post) = user_post_views.exists?(post_id: post.id)
|
def viewed?(post) = user_post_views.exists?(post_id: post.id)
|
||||||
|
|
||||||
def gte_member? = member? || admin?
|
def gte_member? = member? || admin?
|
||||||
|
|
||||||
|
def banned? = banned_at.present?
|
||||||
|
def ban! = banned? || update!(banned_at: Time.current)
|
||||||
|
def unban! = update!(banned_at: nil)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
class WikiAsset < ApplicationRecord
|
||||||
|
belongs_to :wiki_page
|
||||||
|
belongs_to :created_by_user, class_name: 'User'
|
||||||
|
|
||||||
|
has_one_attached :file
|
||||||
|
|
||||||
|
validates :file, presence: true
|
||||||
|
|
||||||
|
def url
|
||||||
|
Rails.application.routes.url_helpers.rails_blob_url(file, only_path: true)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -13,6 +13,8 @@ class WikiPage < ApplicationRecord
|
|||||||
foreign_key: :redirect_page_id,
|
foreign_key: :redirect_page_id,
|
||||||
dependent: :nullify
|
dependent: :nullify
|
||||||
|
|
||||||
|
has_many :assets, class_name: 'WikiAsset', dependent: :destroy
|
||||||
|
|
||||||
has_many :wiki_versions
|
has_many :wiki_versions
|
||||||
|
|
||||||
belongs_to :tag_name
|
belongs_to :tag_name
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# frozen_string_literal: true
|
||||||
|
|
||||||
|
|
||||||
|
module WikiAssetRepr
|
||||||
|
BASE = { only: [:wiki_page_id, :no], methods: [:url] }.freeze
|
||||||
|
|
||||||
|
module_function
|
||||||
|
|
||||||
|
def base wiki_asset
|
||||||
|
wiki_asset.as_json(BASE)
|
||||||
|
end
|
||||||
|
|
||||||
|
def many wiki_assets
|
||||||
|
wiki_assets.map { |a| base(a) }
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -48,6 +48,8 @@ Rails.application.routes.draw do
|
|||||||
get :exists
|
get :exists
|
||||||
get :diff
|
get :diff
|
||||||
end
|
end
|
||||||
|
|
||||||
|
resources :assets, controller: :wiki_assets, only: [:index, :create]
|
||||||
end
|
end
|
||||||
|
|
||||||
resources :posts, only: [:index, :show, :create, :update] do
|
resources :posts, only: [:index, :show, :create, :update] do
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
class CreateWikiAssets < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
create_table :wiki_assets do |t|
|
||||||
|
t.references :wiki_page, null: false, foreign_key: true, index: false
|
||||||
|
t.integer :no, null: false
|
||||||
|
t.string :alt_text
|
||||||
|
t.column :sha256, 'binary(32)', null: false
|
||||||
|
t.references :created_by_user, null: false, foreign_key: { to_table: :users }
|
||||||
|
t.timestamps
|
||||||
|
end
|
||||||
|
|
||||||
|
add_index :wiki_assets, [:wiki_page_id, :sha256], unique: true
|
||||||
|
add_index :wiki_assets, [:wiki_page_id, :no], unique: true
|
||||||
|
|
||||||
|
add_column :wiki_pages, :next_asset_no, :integer, null: false, default: 1
|
||||||
|
end
|
||||||
|
end
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
class RenameBannedToBannedAtInUsersAndIpAddresses < ActiveRecord::Migration[8.0]
|
||||||
|
def up
|
||||||
|
[:users, :ip_addresses].each do
|
||||||
|
add_column _1, :banned_at, :datetime, after: :banned
|
||||||
|
add_index _1, :banned_at
|
||||||
|
remove_column _1, :banned
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def down
|
||||||
|
[:ip_addresses, :users].each do
|
||||||
|
add_column _1, :banned, :boolean, null: false, default: false, after: :banned_at
|
||||||
|
remove_column _1, :banned_at
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
Generated
+5
-3
@@ -10,7 +10,7 @@
|
|||||||
#
|
#
|
||||||
# It's strongly recommended that you check this file into your version control system.
|
# It's strongly recommended that you check this file into your version control system.
|
||||||
|
|
||||||
ActiveRecord::Schema[8.0].define(version: 2026_04_27_214800) do
|
ActiveRecord::Schema[8.0].define(version: 2026_05_01_153900) do
|
||||||
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.string "name", null: false
|
t.string "name", null: false
|
||||||
t.string "record_type", null: false
|
t.string "record_type", null: false
|
||||||
@@ -50,9 +50,10 @@ ActiveRecord::Schema[8.0].define(version: 2026_04_27_214800) do
|
|||||||
|
|
||||||
create_table "ip_addresses", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "ip_addresses", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.binary "ip_address", limit: 16, null: false
|
t.binary "ip_address", limit: 16, null: false
|
||||||
t.boolean "banned", default: false, null: false
|
t.datetime "banned_at"
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["banned_at"], name: "index_ip_addresses_on_banned_at"
|
||||||
t.index ["ip_address"], name: "index_ip_addresses_on_ip_address", unique: true
|
t.index ["ip_address"], name: "index_ip_addresses_on_ip_address", unique: true
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -332,9 +333,10 @@ ActiveRecord::Schema[8.0].define(version: 2026_04_27_214800) do
|
|||||||
t.string "name"
|
t.string "name"
|
||||||
t.string "inheritance_code", limit: 64, null: false
|
t.string "inheritance_code", limit: 64, null: false
|
||||||
t.string "role", null: false
|
t.string "role", null: false
|
||||||
t.boolean "banned", default: false, null: false
|
t.datetime "banned_at"
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["banned_at"], name: "index_users_on_banned_at"
|
||||||
end
|
end
|
||||||
|
|
||||||
create_table "wiki_assets", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "wiki_assets", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
FactoryBot.define do
|
||||||
|
factory :ip_address do
|
||||||
|
ip_address { IPAddr.new('203.0.113.10').hton }
|
||||||
|
banned_at { nil }
|
||||||
|
|
||||||
|
trait :banned do
|
||||||
|
banned_at { Time.current }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,15 +1,24 @@
|
|||||||
FactoryBot.define do
|
FactoryBot.define do
|
||||||
factory :user do
|
factory :user do
|
||||||
name { "test-user" }
|
name { nil }
|
||||||
inheritance_code { SecureRandom.uuid }
|
inheritance_code { SecureRandom.uuid }
|
||||||
role { "guest" }
|
role { 'guest' }
|
||||||
|
banned_at { nil }
|
||||||
|
|
||||||
|
trait :guest do
|
||||||
|
role { 'guest' }
|
||||||
|
end
|
||||||
|
|
||||||
trait :member do
|
trait :member do
|
||||||
role { "member" }
|
role { 'member' }
|
||||||
end
|
end
|
||||||
|
|
||||||
trait :admin do
|
trait :admin do
|
||||||
role { 'admin' }
|
role { 'admin' }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
trait :banned do
|
||||||
|
banned_at { Time.current }
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1409,6 +1409,22 @@ RSpec.describe 'Posts API', type: :request do
|
|||||||
post.snapshot_tag_names.join(' ')
|
post.snapshot_tag_names.join(' ')
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def create_post_version_for!(post)
|
||||||
|
PostVersion.create!(
|
||||||
|
post: post,
|
||||||
|
version_no: 1,
|
||||||
|
event_type: 'create',
|
||||||
|
title: post.title,
|
||||||
|
url: post.url,
|
||||||
|
thumbnail_base: post.thumbnail_base,
|
||||||
|
tags: snapshot_tags(post),
|
||||||
|
original_created_from: post.original_created_from,
|
||||||
|
original_created_before: post.original_created_before,
|
||||||
|
created_at: post.created_at,
|
||||||
|
created_by_user: post.uploaded_user
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
it 'creates version 1 on POST /posts' do
|
it 'creates version 1 on POST /posts' do
|
||||||
sign_in_as(member)
|
sign_in_as(member)
|
||||||
|
|
||||||
|
|||||||
@@ -1,109 +1,266 @@
|
|||||||
require "rails_helper"
|
require 'rails_helper'
|
||||||
|
|
||||||
|
RSpec.describe 'Users', type: :request do
|
||||||
|
let(:remote_ip) { '203.0.113.10' }
|
||||||
|
|
||||||
|
before do
|
||||||
|
allow_any_instance_of(ActionDispatch::Request)
|
||||||
|
.to receive(:remote_ip)
|
||||||
|
.and_return(remote_ip)
|
||||||
|
end
|
||||||
|
|
||||||
|
def auth_headers(user)
|
||||||
|
{ 'X-Transfer-Code' => user.inheritance_code }
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'POST /users' do
|
||||||
|
it 'creates guest user, IpAddress and UserIp, and returns code' do
|
||||||
|
expect {
|
||||||
|
post '/users'
|
||||||
|
}.to change(User, :count).by(1)
|
||||||
|
.and change(IpAddress, :count).by(1)
|
||||||
|
.and change(UserIp, :count).by(1)
|
||||||
|
|
||||||
RSpec.describe "Users", type: :request do
|
|
||||||
describe "POST /users" do
|
|
||||||
it "creates guest user and returns code" do
|
|
||||||
post "/users"
|
|
||||||
expect(response).to have_http_status(:created)
|
expect(response).to have_http_status(:created)
|
||||||
expect(json["code"]).to be_present
|
expect(json['code']).to be_present
|
||||||
expect(json["user"]["role"]).to eq("guest")
|
expect(json['user']['role']).to eq('guest')
|
||||||
|
|
||||||
|
user = User.last
|
||||||
|
ip_address = IpAddress.find_by(ip_address: IPAddr.new(remote_ip).hton)
|
||||||
|
|
||||||
|
expect(user.role).to eq('guest')
|
||||||
|
expect(ip_address).to be_present
|
||||||
|
expect(UserIp.exists?(user:, ip_address:)).to eq(true)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 403 and does not create user when current IP address is banned' do
|
||||||
|
IpAddress.create!(
|
||||||
|
ip_address: IPAddr.new(remote_ip).hton,
|
||||||
|
banned_at: Time.current
|
||||||
|
)
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/users'
|
||||||
|
}.not_to change(User, :count)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
expect(UserIp.count).to eq(0)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "POST /users/code/renew" do
|
describe 'POST /users/code/renew' do
|
||||||
it "returns 401 when not logged in" do
|
it 'returns 401 when not logged in' do
|
||||||
sign_out
|
post '/users/code/renew'
|
||||||
post "/users/code/renew"
|
|
||||||
expect(response).to have_http_status(:unauthorized)
|
expect(response).to have_http_status(:unauthorized)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it 'returns 403 when current user is banned' do
|
||||||
|
user = create(:user, :banned)
|
||||||
|
|
||||||
|
post '/users/code/renew', headers: auth_headers(user)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 403 when current IP address is banned' do
|
||||||
|
user = create(:user)
|
||||||
|
|
||||||
|
IpAddress.create!(
|
||||||
|
ip_address: IPAddr.new(remote_ip).hton,
|
||||||
|
banned_at: Time.current
|
||||||
|
)
|
||||||
|
|
||||||
|
post '/users/code/renew', headers: auth_headers(user)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "PUT /users/:id" do
|
describe 'PUT /users/:id' do
|
||||||
let(:user) { create(:user, name: "old-name", role: "guest") }
|
let(:user) { create(:user, name: 'old-name', role: 'guest') }
|
||||||
|
|
||||||
|
it 'returns 401 when current_user id mismatch' do
|
||||||
|
other_user = create(:user)
|
||||||
|
|
||||||
|
put "/users/#{user.id}",
|
||||||
|
params: { name: 'new-name' },
|
||||||
|
headers: auth_headers(other_user)
|
||||||
|
|
||||||
it "returns 401 when current_user id mismatch" do
|
|
||||||
sign_in_as(create(:user))
|
|
||||||
put "/users/#{user.id}", params: { name: "new-name" }
|
|
||||||
expect(response).to have_http_status(:unauthorized)
|
expect(response).to have_http_status(:unauthorized)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "returns 400 when name is blank" do
|
it 'returns 400 when name is blank' do
|
||||||
sign_in_as(user)
|
put "/users/#{user.id}",
|
||||||
put "/users/#{user.id}", params: { name: " " }
|
params: { name: ' ' },
|
||||||
|
headers: auth_headers(user)
|
||||||
|
|
||||||
expect(response).to have_http_status(:bad_request)
|
expect(response).to have_http_status(:bad_request)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "updates name and returns 201 with user slice" do
|
it 'updates name and returns user slice' do
|
||||||
sign_in_as(user)
|
put "/users/#{user.id}",
|
||||||
put "/users/#{user.id}", params: { name: "new-name" }
|
params: { name: 'new-name' },
|
||||||
|
headers: auth_headers(user)
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json["id"]).to eq(user.id)
|
expect(json['id']).to eq(user.id)
|
||||||
expect(json["name"]).to eq("new-name")
|
expect(json['name']).to eq('new-name')
|
||||||
|
|
||||||
user.reload
|
user.reload
|
||||||
expect(user.name).to eq("new-name")
|
expect(user.name).to eq('new-name')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 403 when current user is banned' do
|
||||||
|
user.update!(banned_at: Time.current)
|
||||||
|
|
||||||
|
put "/users/#{user.id}",
|
||||||
|
params: { name: 'new-name' },
|
||||||
|
headers: auth_headers(user)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
|
||||||
|
user.reload
|
||||||
|
expect(user.name).to eq('old-name')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 403 when current IP address is banned' do
|
||||||
|
IpAddress.create!(
|
||||||
|
ip_address: IPAddr.new(remote_ip).hton,
|
||||||
|
banned_at: Time.current
|
||||||
|
)
|
||||||
|
|
||||||
|
put "/users/#{user.id}",
|
||||||
|
params: { name: 'new-name' },
|
||||||
|
headers: auth_headers(user)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
|
||||||
|
user.reload
|
||||||
|
expect(user.name).to eq('old-name')
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "POST /users/verify" do
|
describe 'POST /users/verify' do
|
||||||
it "returns valid:false when code not found" do
|
it 'returns valid:false when code not found' do
|
||||||
post "/users/verify", params: { code: "nope" }
|
post '/users/verify', params: { code: 'nope' }
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json["valid"]).to eq(false)
|
expect(json['valid']).to eq(false)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "creates IpAddress and UserIp, and returns valid:true with user slice" do
|
it 'returns 403 when current IP address is banned' do
|
||||||
user = create(:user, inheritance_code: SecureRandom.uuid, role: "guest")
|
user = create(:user, inheritance_code: SecureRandom.uuid, role: 'guest')
|
||||||
|
|
||||||
# request.remote_ip を固定
|
IpAddress.create!(
|
||||||
allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("203.0.113.10")
|
ip_address: IPAddr.new(remote_ip).hton,
|
||||||
|
banned_at: Time.current
|
||||||
|
)
|
||||||
|
|
||||||
expect {
|
expect {
|
||||||
post "/users/verify", params: { code: user.inheritance_code }
|
post '/users/verify', params: { code: user.inheritance_code }
|
||||||
|
}.not_to change(UserIp, :count)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 403 when verified user is banned' do
|
||||||
|
user = create(
|
||||||
|
:user,
|
||||||
|
:banned,
|
||||||
|
inheritance_code: SecureRandom.uuid,
|
||||||
|
role: 'guest'
|
||||||
|
)
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/users/verify', params: { code: user.inheritance_code }
|
||||||
|
}.not_to change(UserIp, :count)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'creates IpAddress and UserIp, and returns valid:true with user slice' do
|
||||||
|
user = create(:user, inheritance_code: SecureRandom.uuid, role: 'guest')
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/users/verify', params: { code: user.inheritance_code }
|
||||||
}.to change(UserIp, :count).by(1)
|
}.to change(UserIp, :count).by(1)
|
||||||
|
.and change(IpAddress, :count).by(1)
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json["valid"]).to eq(true)
|
expect(json['valid']).to eq(true)
|
||||||
expect(json["user"]["id"]).to eq(user.id)
|
expect(json['user']['id']).to eq(user.id)
|
||||||
expect(json["user"]["inheritance_code"]).to eq(user.inheritance_code)
|
expect(json['user']['inheritance_code']).to eq(user.inheritance_code)
|
||||||
expect(json["user"]["role"]).to eq("guest")
|
expect(json['user']['role']).to eq('guest')
|
||||||
|
|
||||||
# ついでに IpAddress もできてることを確認(ipの保存形式がバイナリでも count で見れる)
|
ip_address = IpAddress.find_by(ip_address: IPAddr.new(remote_ip).hton)
|
||||||
expect(IpAddress.count).to be >= 1
|
expect(ip_address).to be_present
|
||||||
|
expect(UserIp.exists?(user:, ip_address:)).to eq(true)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "is idempotent for same user+ip (does not create duplicate UserIp)" do
|
it 'is idempotent for same user and same IP address' do
|
||||||
user = create(:user, inheritance_code: SecureRandom.uuid, role: "guest")
|
user = create(:user, inheritance_code: SecureRandom.uuid, role: 'guest')
|
||||||
allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("203.0.113.10")
|
|
||||||
|
|
||||||
post "/users/verify", params: { code: user.inheritance_code }
|
post '/users/verify', params: { code: user.inheritance_code }
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
expect {
|
expect {
|
||||||
post "/users/verify", params: { code: user.inheritance_code }
|
post '/users/verify', params: { code: user.inheritance_code }
|
||||||
}.not_to change(UserIp, :count)
|
}.not_to change(UserIp, :count)
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json["valid"]).to eq(true)
|
expect(json['valid']).to eq(true)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'creates another UserIp for same user and different IP address' do
|
||||||
|
user = create(:user, inheritance_code: SecureRandom.uuid, role: 'guest')
|
||||||
|
|
||||||
|
post '/users/verify', params: { code: user.inheritance_code }
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
allow_any_instance_of(ActionDispatch::Request)
|
||||||
|
.to receive(:remote_ip)
|
||||||
|
.and_return('203.0.113.11')
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/users/verify', params: { code: user.inheritance_code }
|
||||||
|
}.to change(UserIp, :count).by(1)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['valid']).to eq(true)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "GET /users/me" do
|
describe 'GET /users/me' do
|
||||||
it "returns 404 when code not found" do
|
it 'returns 404 when code not found' do
|
||||||
get "/users/me", params: { code: "nope" }
|
get '/users/me', params: { code: 'nope' }
|
||||||
|
|
||||||
expect(response).to have_http_status(:not_found)
|
expect(response).to have_http_status(:not_found)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "returns user slice when found" do
|
it 'returns user slice when found' do
|
||||||
user = create(:user, inheritance_code: SecureRandom.uuid, name: "me", role: "guest")
|
user = create(:user, inheritance_code: SecureRandom.uuid, name: 'me', role: 'guest')
|
||||||
get "/users/me", params: { code: user.inheritance_code }
|
|
||||||
|
get '/users/me', params: { code: user.inheritance_code }
|
||||||
|
|
||||||
expect(response).to have_http_status(:ok)
|
expect(response).to have_http_status(:ok)
|
||||||
expect(json["id"]).to eq(user.id)
|
expect(json['id']).to eq(user.id)
|
||||||
expect(json["name"]).to eq("me")
|
expect(json['name']).to eq('me')
|
||||||
expect(json["inheritance_code"]).to eq(user.inheritance_code)
|
expect(json['inheritance_code']).to eq(user.inheritance_code)
|
||||||
expect(json["role"]).to eq("guest")
|
expect(json['role']).to eq('guest')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns 403 when current IP address is banned' do
|
||||||
|
user = create(:user, inheritance_code: SecureRandom.uuid)
|
||||||
|
|
||||||
|
IpAddress.create!(
|
||||||
|
ip_address: IPAddr.new(remote_ip).hton,
|
||||||
|
banned_at: Time.current
|
||||||
|
)
|
||||||
|
|
||||||
|
get '/users/me', params: { code: user.inheritance_code }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,191 @@
|
|||||||
|
require 'digest'
|
||||||
|
require 'rails_helper'
|
||||||
|
require 'stringio'
|
||||||
|
|
||||||
|
|
||||||
|
RSpec.describe 'WikiAssets API', type: :request do
|
||||||
|
def dummy_upload(content = 'dummy-image', filename: 'dummy.png', content_type: 'image/png')
|
||||||
|
Rack::Test::UploadedFile.new(StringIO.new(content),
|
||||||
|
content_type,
|
||||||
|
original_filename: filename)
|
||||||
|
end
|
||||||
|
|
||||||
|
let(:member) { create(:user, :member, name: 'member user') }
|
||||||
|
let(:guest) { create(:user, name: 'guest user') }
|
||||||
|
|
||||||
|
let!(:tag_name) { TagName.create!(name: 'spec_wiki_asset_page') }
|
||||||
|
let!(:page) do
|
||||||
|
WikiPage.create!(tag_name: tag_name, created_user: member, updated_user: member).tap do |p|
|
||||||
|
Wiki::Commit.content!(page: p, body: 'init', created_user: member, message: 'init')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /wiki/:wiki_page_id/assets' do
|
||||||
|
subject(:do_request) do
|
||||||
|
get "/wiki/#{wiki_page_id}/assets"
|
||||||
|
end
|
||||||
|
|
||||||
|
let(:wiki_page_id) { page.id }
|
||||||
|
|
||||||
|
let!(:asset) do
|
||||||
|
WikiAsset.new(wiki_page: page,
|
||||||
|
no: 1,
|
||||||
|
alt_text: 'spec alt',
|
||||||
|
sha256: Digest::SHA256.digest('asset-1'),
|
||||||
|
created_by_user: member).tap do |record|
|
||||||
|
record.file.attach(dummy_upload('asset-1'))
|
||||||
|
record.save!
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when wiki page exists' do
|
||||||
|
it 'returns assets for the page' do
|
||||||
|
do_request
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json).to be_an(Array)
|
||||||
|
expect(json.size).to eq(1)
|
||||||
|
|
||||||
|
expect(json.first).to include(
|
||||||
|
'wiki_page_id' => page.id,
|
||||||
|
'no' => 1)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not include assets from other pages' do
|
||||||
|
other_tag_name = TagName.create!(name: 'spec_other_wiki_asset_page')
|
||||||
|
other_page = WikiPage.create!(tag_name: other_tag_name,
|
||||||
|
created_user: member,
|
||||||
|
updated_user: member)
|
||||||
|
Wiki::Commit.content!(page: other_page, body: 'other', created_user: member, message: 'other')
|
||||||
|
|
||||||
|
WikiAsset.new(wiki_page: other_page,
|
||||||
|
no: 1,
|
||||||
|
alt_text: 'other alt',
|
||||||
|
sha256: Digest::SHA256.digest('asset-2'),
|
||||||
|
created_by_user: member).tap do |record|
|
||||||
|
record.file.attach(dummy_upload('asset-2', filename: 'other.png'))
|
||||||
|
record.save!
|
||||||
|
end
|
||||||
|
|
||||||
|
do_request
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json.size).to eq(1)
|
||||||
|
expect(json.first['wiki_page_id']).to eq(page.id)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when wiki page does not exist' do
|
||||||
|
let(:wiki_page_id) { 999_999_999 }
|
||||||
|
|
||||||
|
it 'returns 404' do
|
||||||
|
do_request
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'POST /wiki/:wiki_page_id/assets' do
|
||||||
|
subject(:do_request) do
|
||||||
|
post "/wiki/#{wiki_page_id}/assets", params: params
|
||||||
|
end
|
||||||
|
|
||||||
|
let(:wiki_page_id) { page.id }
|
||||||
|
let(:params) do
|
||||||
|
{ file: dummy_upload(upload_content),
|
||||||
|
alt_text: 'uploaded alt' }
|
||||||
|
end
|
||||||
|
let(:upload_content) { 'uploaded-image-binary' }
|
||||||
|
|
||||||
|
context 'when not logged in' do
|
||||||
|
it 'returns 401' do
|
||||||
|
sign_out
|
||||||
|
do_request
|
||||||
|
expect(response).to have_http_status(:unauthorized)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when logged in but not member' do
|
||||||
|
it 'returns 403' do
|
||||||
|
sign_in_as(guest)
|
||||||
|
do_request
|
||||||
|
expect(response).to have_http_status(:forbidden)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when wiki page does not exist' do
|
||||||
|
let(:wiki_page_id) { 999_999_999 }
|
||||||
|
|
||||||
|
it 'returns 404' do
|
||||||
|
sign_in_as(member)
|
||||||
|
do_request
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when file is blank' do
|
||||||
|
let(:params) { { alt_text: 'uploaded alt' } }
|
||||||
|
|
||||||
|
it 'returns 400' do
|
||||||
|
sign_in_as(member)
|
||||||
|
do_request
|
||||||
|
expect(response).to have_http_status(:bad_request)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when success' do
|
||||||
|
before do
|
||||||
|
sign_in_as(member)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'creates asset, attaches file, increments next_asset_no, and returns json' do
|
||||||
|
expect { do_request }
|
||||||
|
.to change(WikiAsset, :count).by(1)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
asset = WikiAsset.order(:id).last
|
||||||
|
expect(asset.wiki_page_id).to eq(page.id)
|
||||||
|
expect(asset.no).to eq(1)
|
||||||
|
expect(asset.alt_text).to eq('uploaded alt')
|
||||||
|
expect(asset.sha256).to eq(Digest::SHA256.digest(upload_content))
|
||||||
|
expect(asset.created_by_user_id).to eq(member.id)
|
||||||
|
expect(asset.file).to be_attached
|
||||||
|
expect(asset.file.download).to eq(upload_content)
|
||||||
|
|
||||||
|
expect(page.reload.next_asset_no).to eq(2)
|
||||||
|
|
||||||
|
expect(json).to include(
|
||||||
|
'wiki_page_id' => page.id,
|
||||||
|
'no' => 1,
|
||||||
|
'url' => asset.url
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'uses the next page-local number when assets already exist' do
|
||||||
|
existing = WikiAsset.new(wiki_page: page,
|
||||||
|
no: 1,
|
||||||
|
alt_text: 'existing alt',
|
||||||
|
sha256: Digest::SHA256.digest('existing'),
|
||||||
|
created_by_user: member)
|
||||||
|
existing.file.attach(dummy_upload('existing', filename: 'existing.png'))
|
||||||
|
existing.save!
|
||||||
|
page.update!(next_asset_no: 2)
|
||||||
|
|
||||||
|
do_request
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
|
||||||
|
asset = WikiAsset.order(:id).last
|
||||||
|
expect(asset.no).to eq(2)
|
||||||
|
expect(page.reload.next_asset_no).to eq(3)
|
||||||
|
|
||||||
|
expect(json).to include(
|
||||||
|
'wiki_page_id' => page.id,
|
||||||
|
'no' => 2,
|
||||||
|
'url' => asset.url
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -113,6 +113,7 @@ RSpec.describe 'Wiki API', type: :request do
|
|||||||
|
|
||||||
page_id = json.fetch('id')
|
page_id = json.fetch('id')
|
||||||
expect(json.fetch('title')).to eq('TestPage')
|
expect(json.fetch('title')).to eq('TestPage')
|
||||||
|
expect(json.fetch('body')).to eq("a\nb\nc")
|
||||||
|
|
||||||
created_page = WikiPage.find(page_id)
|
created_page = WikiPage.find(page_id)
|
||||||
version = created_page.wiki_versions.order(:version_no).last
|
version = created_page.wiki_versions.order(:version_no).last
|
||||||
|
|||||||
@@ -2,14 +2,12 @@ module TestRecords
|
|||||||
def create_member_user!
|
def create_member_user!
|
||||||
User.create!(name: 'spec user',
|
User.create!(name: 'spec user',
|
||||||
inheritance_code: SecureRandom.hex(16),
|
inheritance_code: SecureRandom.hex(16),
|
||||||
role: 'member',
|
role: 'member')
|
||||||
banned: false)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def create_admin_user!
|
def create_admin_user!
|
||||||
User.create!(name: 'spec admin',
|
User.create!(name: 'spec admin',
|
||||||
inheritance_code: SecureRandom.hex(16),
|
inheritance_code: SecureRandom.hex(16),
|
||||||
role: 'admin',
|
role: 'admin')
|
||||||
banned: false)
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,42 +1,9 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import WikiMarkdown from '@/components/WikiMarkdown'
|
||||||
import { useMemo } from 'react'
|
|
||||||
import ReactMarkdown from 'react-markdown'
|
|
||||||
import remarkGFM from 'remark-gfm'
|
|
||||||
|
|
||||||
import PrefetchLink from '@/components/PrefetchLink'
|
|
||||||
import { wikiKeys } from '@/lib/queryKeys'
|
|
||||||
import remarkWikiAutoLink from '@/lib/remark-wiki-autolink'
|
|
||||||
import { fetchWikiPages } from '@/lib/wiki'
|
|
||||||
|
|
||||||
import type { FC } from 'react'
|
import type { FC } from 'react'
|
||||||
import type { Components } from 'react-markdown'
|
|
||||||
|
|
||||||
type Props = { title: string
|
type Props = { title: string
|
||||||
body?: string }
|
body?: string }
|
||||||
|
|
||||||
const mdComponents = { a: (({ href, children }) => (
|
export default (({ title, body }: Props) =>
|
||||||
['/', '.'].some (e => href?.startsWith (e))
|
<WikiMarkdown title={title} body={body ?? ''}/>) satisfies FC<Props>
|
||||||
? <PrefetchLink to={href!}>{children}</PrefetchLink>
|
|
||||||
: (
|
|
||||||
<a href={href}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer">
|
|
||||||
{children}
|
|
||||||
</a>))) } as const satisfies Components
|
|
||||||
|
|
||||||
|
|
||||||
export default (({ title, body }: Props) => {
|
|
||||||
const { data } = useQuery ({
|
|
||||||
enabled: Boolean (body),
|
|
||||||
queryKey: wikiKeys.index ({ }),
|
|
||||||
queryFn: () => fetchWikiPages ({ }) })
|
|
||||||
const pageNames = (data ?? []).map (page => page.title).sort ((a, b) => b.length - a.length)
|
|
||||||
|
|
||||||
const remarkPlugins = useMemo (
|
|
||||||
() => [() => remarkWikiAutoLink (pageNames), remarkGFM], [pageNames])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ReactMarkdown components={mdComponents} remarkPlugins={remarkPlugins}>
|
|
||||||
{body || `このページは存在しません。[新規作成してください](/wiki/new?title=${ encodeURIComponent (title) })。`}
|
|
||||||
</ReactMarkdown>)
|
|
||||||
}) satisfies FC<Props>
|
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import MdEditor from 'react-markdown-editor-lite'
|
||||||
|
|
||||||
|
import WikiMarkdown from '@/components/WikiMarkdown'
|
||||||
|
import Label from '@/components/common/Label'
|
||||||
|
import { apiPost } from '@/lib/api'
|
||||||
|
|
||||||
|
import type { FC } from 'react'
|
||||||
|
|
||||||
|
import type { WikiAsset } from '@/types'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
title: string
|
||||||
|
body: string
|
||||||
|
onSubmit: (title: string, body: string) => void
|
||||||
|
id?: number | null }
|
||||||
|
|
||||||
|
|
||||||
|
export default (({ title: initTitle, body: initBody, onSubmit, id }: Props) => {
|
||||||
|
const forEdit = id != null
|
||||||
|
|
||||||
|
const [title, setTitle] = useState<string> (initTitle)
|
||||||
|
const [body, setBody] = useState<string> (initBody)
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
setTitle (initTitle)
|
||||||
|
setBody (initBody)
|
||||||
|
}, [initTitle, initBody])
|
||||||
|
|
||||||
|
const handleImageUpload = async (file: File) => {
|
||||||
|
if (!(forEdit))
|
||||||
|
throw new Error ('画像は Wiki 作成前に追加することができません.')
|
||||||
|
|
||||||
|
const formData = new FormData
|
||||||
|
formData.append ('file', file)
|
||||||
|
|
||||||
|
const asset = await apiPost<WikiAsset> (
|
||||||
|
`/wiki/${ id }/assets`,
|
||||||
|
formData,
|
||||||
|
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||||
|
|
||||||
|
return asset.url
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* タイトル */}
|
||||||
|
{/* TODO: タグ補完 */}
|
||||||
|
<div>
|
||||||
|
<Label>タイトル</Label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={title}
|
||||||
|
onChange={e => setTitle (e.target.value)}
|
||||||
|
className="w-full border p-2 rounded"/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 本文 */}
|
||||||
|
<div>
|
||||||
|
<Label>本文</Label>
|
||||||
|
<MdEditor
|
||||||
|
value={body}
|
||||||
|
style={{ height: '500px' }}
|
||||||
|
renderHTML={text => <WikiMarkdown body={text} preview/>}
|
||||||
|
onChange={({ text }) => setBody (text)}
|
||||||
|
onImageUpload={handleImageUpload}/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 送信 */}
|
||||||
|
<button
|
||||||
|
onClick={() => onSubmit (title, body)}
|
||||||
|
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400">
|
||||||
|
{forEdit ? '編輯' : '追加'}
|
||||||
|
</button>
|
||||||
|
</>)
|
||||||
|
}) satisfies FC<Props>
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { useMemo } from 'react'
|
||||||
|
import ReactMarkdown from 'react-markdown'
|
||||||
|
import remarkGFM from 'remark-gfm'
|
||||||
|
|
||||||
|
import PrefetchLink from '@/components/PrefetchLink'
|
||||||
|
import SectionTitle from '@/components/common/SectionTitle'
|
||||||
|
import SubsectionTitle from '@/components/common/SubsectionTitle'
|
||||||
|
import { wikiKeys } from '@/lib/queryKeys'
|
||||||
|
import remarkWikiAutoLink from '@/lib/remark-wiki-autolink'
|
||||||
|
import { fetchWikiPages } from '@/lib/wiki'
|
||||||
|
|
||||||
|
import type { FC } from 'react'
|
||||||
|
import type { Components } from 'react-markdown'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
title?: string
|
||||||
|
body: string
|
||||||
|
preview?: boolean }
|
||||||
|
|
||||||
|
|
||||||
|
const makeComponents = (preview = false) => (
|
||||||
|
{ h1: ({ children }) => <SectionTitle>{children}</SectionTitle>,
|
||||||
|
h2: ({ children }) => <SubsectionTitle>{children}</SubsectionTitle>,
|
||||||
|
ol: ({ children }) => <ol className="list-decimal pl-6">{children}</ol>,
|
||||||
|
ul: ({ children }) => <ul className="list-disc pl-6">{children}</ul>,
|
||||||
|
a: ({ href, children }) => {
|
||||||
|
if (!(href))
|
||||||
|
return <>{children}</>
|
||||||
|
|
||||||
|
if (!(preview) && ['/', '.'].some (e => href.startsWith (e)))
|
||||||
|
return <PrefetchLink to={href}>{children}</PrefetchLink>
|
||||||
|
|
||||||
|
const ext = /^(?:https?:)?\/\//.test (href)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<a href={href}
|
||||||
|
target={ext ? '_blank' : undefined}
|
||||||
|
rel={ext ? 'noopener noreferrer' : undefined}>
|
||||||
|
{children}
|
||||||
|
</a>)
|
||||||
|
},
|
||||||
|
img: (({ src, alt }) => (
|
||||||
|
<img src={src ?? ''}
|
||||||
|
alt={alt ?? ''}
|
||||||
|
className="max-w-[240px] max-h-[320px]"/>)),
|
||||||
|
} as const satisfies Components)
|
||||||
|
|
||||||
|
|
||||||
|
export default (({ title, body, preview = false }: Props) => {
|
||||||
|
const { data } = useQuery ({
|
||||||
|
queryKey: wikiKeys.index ({ }),
|
||||||
|
queryFn: () => fetchWikiPages ({ }) })
|
||||||
|
|
||||||
|
const pageNames = useMemo (
|
||||||
|
() => (data ?? []).map ((page) => page.title).sort ((a, b) => b.length - a.length),
|
||||||
|
[data])
|
||||||
|
|
||||||
|
const remarkPlugins = useMemo (
|
||||||
|
() => [() => remarkWikiAutoLink (pageNames), remarkGFM],
|
||||||
|
[pageNames])
|
||||||
|
|
||||||
|
const components = useMemo (
|
||||||
|
() => makeComponents (preview),
|
||||||
|
[preview])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ReactMarkdown
|
||||||
|
components={components}
|
||||||
|
remarkPlugins={remarkPlugins}>
|
||||||
|
{body
|
||||||
|
|| (title
|
||||||
|
? ('このページは存在しません。'
|
||||||
|
+`[新規作成してください](/wiki/new?title=${ encodeURIComponent (title) })。`)
|
||||||
|
: '')}
|
||||||
|
</ReactMarkdown>)
|
||||||
|
}) satisfies FC<Props>
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import MarkdownIt from 'markdown-it'
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { Helmet } from 'react-helmet-async'
|
import { Helmet } from 'react-helmet-async'
|
||||||
import MdEditor from 'react-markdown-editor-lite'
|
|
||||||
import { useParams, useNavigate } from 'react-router-dom'
|
import { useParams, useNavigate } from 'react-router-dom'
|
||||||
|
|
||||||
|
import WikiEditForm from '@/components/WikiEditForm'
|
||||||
import MainArea from '@/components/layout/MainArea'
|
import MainArea from '@/components/layout/MainArea'
|
||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
@@ -18,8 +17,6 @@ import type { FC } from 'react'
|
|||||||
|
|
||||||
import type { User, WikiPage } from '@/types'
|
import type { User, WikiPage } from '@/types'
|
||||||
|
|
||||||
const mdParser = new MarkdownIt
|
|
||||||
|
|
||||||
type Props = { user: User | null }
|
type Props = { user: User | null }
|
||||||
|
|
||||||
|
|
||||||
@@ -37,7 +34,7 @@ export default (({ user }: Props) => {
|
|||||||
const [loading, setLoading] = useState (true)
|
const [loading, setLoading] = useState (true)
|
||||||
const [title, setTitle] = useState ('')
|
const [title, setTitle] = useState ('')
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async (title: string, body: string) => {
|
||||||
const formData = new FormData ()
|
const formData = new FormData ()
|
||||||
formData.append ('title', title)
|
formData.append ('title', title)
|
||||||
formData.append ('body', body)
|
formData.append ('body', body)
|
||||||
@@ -46,8 +43,6 @@ export default (({ user }: Props) => {
|
|||||||
{
|
{
|
||||||
await apiPut (`/wiki/${ id }`, formData,
|
await apiPut (`/wiki/${ id }`, formData,
|
||||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||||
qc.setQueryData (wikiKeys.show (title, { }),
|
|
||||||
(prev: WikiPage) => ({ ...prev, title, body }))
|
|
||||||
qc.invalidateQueries ({ queryKey: wikiKeys.root })
|
qc.invalidateQueries ({ queryKey: wikiKeys.root })
|
||||||
toast ({ title: '投稿成功!' })
|
toast ({ title: '投稿成功!' })
|
||||||
navigate (`/wiki/${ title }`)
|
navigate (`/wiki/${ title }`)
|
||||||
@@ -77,32 +72,11 @@ export default (({ user }: Props) => {
|
|||||||
<h1 className="text-2xl font-bold mb-2">Wiki ページを編輯</h1>
|
<h1 className="text-2xl font-bold mb-2">Wiki ページを編輯</h1>
|
||||||
|
|
||||||
{loading ? 'Loading...' : (
|
{loading ? 'Loading...' : (
|
||||||
<>
|
<WikiEditForm
|
||||||
{/* タイトル */}
|
title={title}
|
||||||
{/* TODO: タグ補完 */}
|
body={body}
|
||||||
<div>
|
onSubmit={handleSubmit}
|
||||||
<label className="block font-semibold mb-1">タイトル</label>
|
id={Number (id)}/>)}
|
||||||
<input type="text"
|
|
||||||
value={title}
|
|
||||||
onChange={e => setTitle (e.target.value)}
|
|
||||||
className="w-full border p-2 rounded"/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 本文 */}
|
|
||||||
<div>
|
|
||||||
<label className="block font-semibold mb-1">本文</label>
|
|
||||||
<MdEditor value={body}
|
|
||||||
style={{ height: '500px' }}
|
|
||||||
renderHTML={text => mdParser.render (text)}
|
|
||||||
onChange={({ text }) => setBody (text)}/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 送信 */}
|
|
||||||
<button onClick={handleSubmit}
|
|
||||||
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400">
|
|
||||||
編輯
|
|
||||||
</button>
|
|
||||||
</>)}
|
|
||||||
</div>
|
</div>
|
||||||
</MainArea>)
|
</MainArea>)
|
||||||
}) satisfies FC<Props>
|
}) satisfies FC<Props>
|
||||||
|
|||||||
@@ -1,21 +1,19 @@
|
|||||||
import MarkdownIt from 'markdown-it'
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import { useState } from 'react'
|
|
||||||
import { Helmet } from 'react-helmet-async'
|
import { Helmet } from 'react-helmet-async'
|
||||||
import MdEditor from 'react-markdown-editor-lite'
|
|
||||||
import { useLocation, useNavigate } from 'react-router-dom'
|
import { useLocation, useNavigate } from 'react-router-dom'
|
||||||
|
|
||||||
|
import WikiEditForm from '@/components/WikiEditForm'
|
||||||
import MainArea from '@/components/layout/MainArea'
|
import MainArea from '@/components/layout/MainArea'
|
||||||
import { toast } from '@/components/ui/use-toast'
|
import { toast } from '@/components/ui/use-toast'
|
||||||
import { SITE_TITLE } from '@/config'
|
import { SITE_TITLE } from '@/config'
|
||||||
import { apiPost } from '@/lib/api'
|
import { apiPost } from '@/lib/api'
|
||||||
|
import { wikiKeys } from '@/lib/queryKeys'
|
||||||
import Forbidden from '@/pages/Forbidden'
|
import Forbidden from '@/pages/Forbidden'
|
||||||
|
|
||||||
import 'react-markdown-editor-lite/lib/index.css'
|
import 'react-markdown-editor-lite/lib/index.css'
|
||||||
|
|
||||||
import type { User, WikiPage } from '@/types'
|
import type { User, WikiPage } from '@/types'
|
||||||
|
|
||||||
const mdParser = new MarkdownIt
|
|
||||||
|
|
||||||
type Props = { user: User | null }
|
type Props = { user: User | null }
|
||||||
|
|
||||||
|
|
||||||
@@ -26,13 +24,12 @@ export default ({ user }: Props) => {
|
|||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
const navigate = useNavigate ()
|
const navigate = useNavigate ()
|
||||||
|
|
||||||
|
const qc = useQueryClient ()
|
||||||
|
|
||||||
const query = new URLSearchParams (location.search)
|
const query = new URLSearchParams (location.search)
|
||||||
const titleQuery = query.get ('title') ?? ''
|
const titleQuery = query.get ('title') ?? ''
|
||||||
|
|
||||||
const [title, setTitle] = useState (titleQuery)
|
const handleSubmit = async (title: string, body: string) => {
|
||||||
const [body, setBody] = useState ('')
|
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
|
||||||
const formData = new FormData
|
const formData = new FormData
|
||||||
formData.append ('title', title)
|
formData.append ('title', title)
|
||||||
formData.append ('body', body)
|
formData.append ('body', body)
|
||||||
@@ -40,7 +37,8 @@ export default ({ user }: Props) => {
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
const data = await apiPost<WikiPage> ('/wiki', formData,
|
const data = await apiPost<WikiPage> ('/wiki', formData,
|
||||||
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
{ headers: { 'Content-Type': 'multipart/form-data' } })
|
||||||
|
qc.invalidateQueries ({ queryKey: wikiKeys.root })
|
||||||
toast ({ title: '投稿成功!' })
|
toast ({ title: '投稿成功!' })
|
||||||
navigate (`/wiki/${ data.title }`)
|
navigate (`/wiki/${ data.title }`)
|
||||||
}
|
}
|
||||||
@@ -58,30 +56,10 @@ export default ({ user }: Props) => {
|
|||||||
<div className="max-w-xl mx-auto p-4 space-y-4">
|
<div className="max-w-xl mx-auto p-4 space-y-4">
|
||||||
<h1 className="text-2xl font-bold mb-2">新規 Wiki ページ</h1>
|
<h1 className="text-2xl font-bold mb-2">新規 Wiki ページ</h1>
|
||||||
|
|
||||||
{/* タイトル */}
|
<WikiEditForm
|
||||||
{/* TODO: タグ補完 */}
|
title={titleQuery}
|
||||||
<div>
|
body=""
|
||||||
<label className="block font-semibold mb-1">タイトル</label>
|
onSubmit={handleSubmit}/>
|
||||||
<input type="text"
|
|
||||||
value={title}
|
|
||||||
onChange={e => setTitle (e.target.value)}
|
|
||||||
className="w-full border p-2 rounded"/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 本文 */}
|
|
||||||
<div>
|
|
||||||
<label className="block font-semibold mb-1">本文</label>
|
|
||||||
<MdEditor value={body}
|
|
||||||
style={{ height: '500px' }}
|
|
||||||
renderHTML={text => mdParser.render (text)}
|
|
||||||
onChange={({ text }) => setBody (text)}/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 送信 */}
|
|
||||||
<button onClick={handleSubmit}
|
|
||||||
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400">
|
|
||||||
追加
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</MainArea>)
|
</MainArea>)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -223,6 +223,11 @@ export type User = {
|
|||||||
|
|
||||||
export type ViewFlagBehavior = typeof ViewFlagBehavior[keyof typeof ViewFlagBehavior]
|
export type ViewFlagBehavior = typeof ViewFlagBehavior[keyof typeof ViewFlagBehavior]
|
||||||
|
|
||||||
|
export type WikiAsset = {
|
||||||
|
wikiPageId: number
|
||||||
|
no: number
|
||||||
|
url: string }
|
||||||
|
|
||||||
export type WikiPage = {
|
export type WikiPage = {
|
||||||
id: number
|
id: number
|
||||||
title: string
|
title: string
|
||||||
|
|||||||
Reference in New Issue
Block a user