ruby
9 lines · 1 tab
Kai Nakamura
Apr 2026
1 tab
allowed_types = ['image/png', 'image/jpeg', 'application/pdf']
uploaded = params.require(:document)
raise ActionController::BadRequest, 'file too large' if uploaded.size > 10.megabytes
raise ActionController::BadRequest, 'type not allowed' unless allowed_types.include?(uploaded.content_type)
filename = "#{SecureRandom.uuid}#{File.extname(uploaded.original_filename).downcase}"
storage_path = Rails.root.join('storage', 'uploads', filename)
File.binwrite(storage_path, uploaded.read)
1 file · ruby
Explain with highlit
File uploads are attacker-controlled input with extra surface area. I validate extension and MIME type, rename everything server side, scan risky formats, and keep user uploads out of executable paths. If the business allows arbitrary uploads, storage isolation becomes non-negotiable.
Related snips
ruby
class SignupForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :account_name, :string
attribute :email, :string
Shallow Controller, Deep Params: Form Object Pattern
rails
activemodel
form-object
by codesnips
3 tabs
ruby
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]
sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first
SQL injection prevention with unsafe and safe query patterns
sql-injection
owasp
database
by Kai Nakamura
3 tabs
ruby
RegistrationSchema = Dry::Schema.Params do
required(:email).filled(:string, format?: URI::MailTo::EMAIL_REGEXP)
required(:password).filled(:string, min_size?: 12)
optional(:marketing_opt_in).filled(:bool)
optional(:country).filled(:string, included_in?: %w[US CA GB AU])
end
Input validation with allowlists and explicit schemas
input-validation
schemas
secure-coding
by Kai Nakamura
1 tab
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation Example</title>
<style>
HTML forms with validation and accessibility
html
forms
validation
by Alex Chang
1 tab
ruby
raw_token = SecureRandom.urlsafe_base64(32)
token_digest = Digest::SHA256.hexdigest(raw_token)
PasswordReset.create!(
user: user,
token_digest: token_digest,
Secure random token generation for sessions and recovery flows
randomness
tokens
authentication
by Kai Nakamura
1 tab
python
import psycopg
with psycopg.connect(conninfo) as connection:
with connection.cursor() as cursor:
cursor.execute(
'SELECT id, email FROM users WHERE email = %s',
Parameterized queries in Python with psycopg
python
sql-injection
psycopg
by Kai Nakamura
1 tab
Share this code
Here's the card — post it anywhere.