XSS対策の方法を変更

This commit is contained in:
Rikuoh Tsujitani 2024-08-14 14:22:10 +09:00
parent 9574ca0bbc
commit 091bb382c8
5 changed files with 16 additions and 29 deletions

View file

@ -4,26 +4,22 @@ require 'sinatra'
require 'sinatra/reloader'
require 'json'
require 'securerandom'
require 'rack/protection'
require 'rack/utils'
require 'cgi'
use Rack::Protection
FILE_PATH = 'memos.json'
helpers do
include Rack::Utils
alias_method :h, :escape_html
def h(text)
CGI.escapeHTML(text.to_s)
end
end
FILE_PATH = 'memos.json' # publicフォルダから移動
def load_memos
if File.exist?(FILE_PATH) && !File.zero?(FILE_PATH)
if !File.zero?(FILE_PATH)
JSON.parse(File.read(FILE_PATH))
else
{}
end
rescue JSON::ParserError
{}
end
def save_memos(memos)
@ -48,7 +44,7 @@ end
post '/memos' do
memos = load_memos
id = SecureRandom.uuid
memos[id] = { 'title' => h(params[:title]), 'content' => h(params[:content]) }
memos[id] = { 'title' => params[:title], 'content' => params[:content] }
save_memos(memos)
redirect '/memos'
end
@ -68,7 +64,7 @@ end
patch '/memos/:id' do
memos = load_memos
halt 404, erb(:not_found) unless memos[params[:id]]
memos[params[:id]] = { 'title' => h(params[:title]), 'content' => h(params[:content]) }
memos[params[:id]] = { 'title' => params[:title], 'content' => params[:content] }
save_memos(memos)
redirect "/memos/#{params[:id]}"
end

View file

@ -1,8 +1,8 @@
<form action="/memos/<%= params[:id] %>" method="post">
<input type="hidden" name="_method" value="patch">
<label for="title">タイトル</label>
<input type="text" name="title" id="title" value="<%= @memo["title"] %>">
<input type="text" name="title" id="title" value="<%= h(@memo['title']) %>">
<label for="content">内容</label>
<textarea name="content" id="content"><%= @memo["content"] %></textarea>
<textarea name="content" id="content"><%= h(@memo['content']) %></textarea>
<button type="submit" class="edit">変更</button>
</form>

View file

@ -1,5 +1,5 @@
<ul class="memo-list">
<% @memos.each do |id, memo| %>
<li><a href="/memos/<%= id %>"><%= memo["title"] %></a></li>
<li><a href="/memos/<%= id %>"><%= h(memo["title"]) %></a></li>
<% end %>
</ul>

View file

@ -1,12 +1,3 @@
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>404 Not Found</title>
</head>
<body>
<h1>404 Not Found</h1>
<p>お探しのページは見つかりませんでした。</p>
<a href="/memos">メモ一覧に戻る</a>
</body>
</html>
<h1>404 Not Found</h1>
<p>お探しのページは見つかりませんでした。</p>
<a href="/">トップページに戻る</a>

View file

@ -1,5 +1,5 @@
<h2><%= @memo["title"] %></h2>
<p><%= @memo["content"] %></p>
<h2><%= h(@memo['title']) %></h2>
<p><%= h(@memo['content']) %></p>
<div class="memo-actions">
<form action="/memos/<%= params[:id] %>/edit" method="get">
<button type="submit" class="edit">変更</button>