惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Stack Overflow Blog
Stack Overflow Blog
Forbes - Security
Forbes - Security
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
N
News | PayPal Newsroom
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Project Zero
Project Zero
Cyberwarzone
Cyberwarzone
Vercel News
Vercel News
M
MIT News - Artificial intelligence
云风的 BLOG
云风的 BLOG
Google Online Security Blog
Google Online Security Blog
Simon Willison's Weblog
Simon Willison's Weblog
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
T
Tenable Blog
I
InfoQ
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
D
DataBreaches.Net
博客园 - Franky
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
S
Security @ Cisco Blogs
Hacker News: Ask HN
Hacker News: Ask HN
J
Java Code Geeks
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Full Disclosure
C
Cisco Blogs
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Fortinet All Blogs
Jina AI
Jina AI
V
Visual Studio Blog
L
LINUX DO - 热门话题
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Resume Download Gate: Email Collection, Signed Tokens, and an S3 Lesson
Vicente G. Reyes · 2026-05-29 · via DEV Community

I wanted a soft gate on my resume download. Not a paywall. Just an email field — enough friction to filter bots, enough signal to know who's interested. What started as a straightforward feature turned into a three-part lesson: stateless token signing, S3 public access, and email delivery mechanics.

Here's the full story.


The Feature

The flow I wanted:

  1. Visitor clicks "Download Resume" on the About page or Hero
  2. A modal asks for their email
  3. Backend validates the email (format + disposable domain check)
  4. A signed, time-limited link is emailed to them
  5. They click the link, the PDF opens

No database tokens. No cron jobs. No permanent S3 URLs floating around.


Part 1 — The Model and the Gate

The Resume Model

Resume follows the singleton pattern I already use for page headers — force pk=1 on every save, restrict add/delete in admin. One row, forever.

class Resume(models.Model):
    pdf = models.FileField(upload_to="resume/", storage=private_resume_storage)
    last_updated = models.DateField(default=date.today)

    def save(self, *args, **kwargs):
        self.pk = 1
        super().save(*args, **kwargs)

ResumeDownloadRequest logs every email that requests a link — no tokens, no expiry columns, just a record of who asked and when.

class ResumeDownloadRequest(models.Model):
    email = models.EmailField()
    created_at = models.DateTimeField(auto_now_add=True)
    unsubscribed = models.BooleanField(default=False)

    class Meta:
        ordering = ["-created_at"]

The unsubscribed flag is there for a future newsletter broadcast — when a new blog post goes out, skip anyone who opted out.

Blocking Disposable Emails

Before signing anything, the email is checked against a frozenset of ~70 known throwaway domains:

# core/validators.py
DISPOSABLE_EMAIL_DOMAINS: frozenset[str] = frozenset({
    "mailinator.com",
    "guerrillamail.com",
    "yopmail.com",
    "10minutemail.com",
    "trashmail.com",
    # ... ~70 total
})

def is_disposable_email(email: str) -> bool:
    if "@" not in email:
        return False
    domain = email.rsplit("@", 1)[-1].lower().strip()
    return domain in DISPOSABLE_EMAIL_DOMAINS

The serializer calls it in validate_email so DRF surfaces it as a standard field error.


Part 2 — django.core.signing.TimestampSigner

This is the part I hadn't used before. Django ships a signing module in django.core.signing that most people only know from cookies and sessions. It's a general-purpose tool for producing tamper-proof, time-limited strings — no database, no cache, no state anywhere.

from django.core import signing

signer = signing.TimestampSigner()

# Sign a payload — embeds the current timestamp
token = signer.sign_object({"pk": 1, "email": "user@example.com"})
# → "eyJwayI6MSwiZW1haWwiOiJ1c2VyQGV4YW1wbGUuY29tIn0:1wSd5Q:EHGb3ife..."

# Verify — raises SignatureExpired if older than max_age seconds
data = signer.unsign_object(token, max_age=900)  # 15 minutes
# → {"pk": 1, "email": "user@example.com"}

The token is three colon-delimited parts: base64-encoded JSON payload, a base64-encoded timestamp, and an HMAC signature derived from SECRET_KEY. Tamper any part and it raises BadSignature. Wait too long and it raises SignatureExpired.

No rows inserted. No rows deleted. The server is completely stateless between the two requests.

The Two API Views

RESUME_TOKEN_MAX_AGE = 900  # 15 minutes

class ResumeRequestDownloadView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request):
        serializer = ResumeDownloadRequestSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {"data": None, "message": "", "errors": serializer.errors},
                status=status.HTTP_400_BAD_REQUEST,
            )
        email = serializer.validated_data["email"]
        resume = Resume.objects.filter(pk=1).first()
        if not resume:
            return Response(
                {"data": None, "message": "No resume available.", "errors": None},
                status=status.HTTP_404_NOT_FOUND,
            )
        ResumeDownloadRequest.objects.create(email=email)
        signer = signing.TimestampSigner()
        token = signer.sign_object({"pk": resume.pk, "email": email})
        download_path = reverse("api:resume-download") + f"?token={token}"
        download_url = request.build_absolute_uri(download_path)
        expires_minutes = RESUME_TOKEN_MAX_AGE // 60
        self._send_download_email(email, download_url, expires_minutes)
        return Response({
            "data": None,
            "message": f"Check your inbox — the link expires in {expires_minutes} minutes.",
            "errors": None,
        })

    def _send_download_email(self, email, download_url, expires_minutes):
        body = (
            f"Hi there!\n\n"
            f"Here's your link to download my resume:\n\n"
            f"{download_url}\n\n"
            f"This link expires in {expires_minutes} minutes.\n\n"
            f"— Vicente Reyes\n"
            f"   https://vicentereyes.org"
        )
        with contextlib.suppress(Exception):
            send_mail(
                subject="Your resume download link",
                message=body,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[email],
                fail_silently=True,
            )

class ResumeDownloadView(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request):
        token = request.query_params.get("token", "")
        if not token:
            return Response(
                {"data": None, "message": "", "errors": {"token": ["This field is required."]}},
                status=status.HTTP_400_BAD_REQUEST,
            )
        signer = signing.TimestampSigner()
        data = None
        with contextlib.suppress(signing.SignatureExpired, signing.BadSignature):
            data = signer.unsign_object(token, max_age=RESUME_TOKEN_MAX_AGE)

        if data is None:
            try:
                signer.unsign_object(token)
                return Response(
                    {"data": None, "message": "Download link expired. Please request a new one.", "errors": None},
                    status=status.HTTP_410_GONE,
                )
            except signing.BadSignature:
                return Response(
                    {"data": None, "message": "Invalid download token.", "errors": None},
                    status=status.HTTP_400_BAD_REQUEST,
                )

        resume = Resume.objects.filter(pk=data.get("pk")).first()
        if not resume or not resume.pdf:
            return Response(
                {"data": None, "message": "Resume not found.", "errors": None},
                status=status.HTTP_404_NOT_FOUND,
            )
        return HttpResponseRedirect(resume.pdf.url)

The expired-vs-tampered distinction matters: 410 Gone tells the frontend "the link was real but timed out, ask again." 400 means the token is garbage. Different messages, different user actions.


Part 3 — The S3 Bypass

I shipped it. It worked. Then I opened the S3 URL directly:

https://bucket.s3.amazonaws.com/media/resume/Vicente_Reyes_Resume.pdf

The PDF downloaded. No token, no email, no gate.

What Went Wrong

Two settings in production.py:

AWS_QUERYSTRING_AUTH = False   # plain URLs, no signed query strings
AWS_DEFAULT_ACL = None         # objects inherit bucket ACL → public-read

resume.pdf.url was returning a permanent, unauthenticated S3 URL. The gate was checking ID at the front door while the back window was wide open.

The Fix: Per-Field Private Storage

Changing AWS_QUERYSTRING_AUTH globally would break every other media file — blog covers, project screenshots, testimonial avatars — all meant to be public. The right scope is narrower: only the resume field needs private storage.

django-storages supports this through custom storage classes. Pass a callable to FileField's storage parameter and Django calls it at runtime to get the storage instance.

# core/storages.py
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from storages.backends.s3boto3 import S3Boto3Storage

def private_resume_storage():
    if getattr(settings, "AWS_STORAGE_BUCKET_NAME", None):
        return S3Boto3Storage(
            location="media",
            default_acl="private",
            querystring_auth=True,
            querystring_expire=120,   # presigned URL valid for 2 minutes
            custom_domain=None,       # presigned URLs need the real S3 endpoint
            file_overwrite=False,
        )
    return FileSystemStorage()

# models.py
class Resume(models.Model):
    pdf = models.FileField(upload_to="resume/", storage=private_resume_storage)

Now resume.pdf.url returns a presigned URL:

https://bucket.s3.amazonaws.com/media/resume/filename.pdf
  ?X-Amz-Algorithm=AWS4-HMAC-SHA256
  &X-Amz-Credential=...
  &X-Amz-Expires=120
  &X-Amz-Signature=...

Valid for 120 seconds. The direct URL without the signature returns a 403. Sharing the URL or bookmarking it is pointless.

Why custom_domain=None

The production config has AWS_S3_CUSTOM_DOMAIN set. Custom domains don't support AWS Signature v4 query parameters — the presigned URL would be malformed. Setting custom_domain=None on the private storage instance forces django-storages to use the real S3 endpoint for that field only.

The Migration Surprise

Switching the storage callable requires a migration even though no columns change. Django records the storage class in migration state, so changing it from default to a callable produces a ~ Alter field pdf on resume migration. It's a no-op at the database level but Django needs it for consistency.


Part 4 — Email-First, Not Token-First

The original frontend flow returned the token in the API response and called window.open(downloadUrl, '_blank') immediately. The PDF opened before the user even checked their email.

The problem: someone could submit any email address, get the immediate download in their browser, and the link would go to whoever owned that inbox. The email was a log entry, not a gate.

Switching to email-first fixes it. The token is built server-side, put in the email body, and never returned to the frontend:

# Before
return Response({"data": {"token": token}, ...})

# After
self._send_download_email(email, download_url, expires_minutes)
return Response({"data": None, "message": "Check your inbox...", ...})

The frontend modal now shows a confirmation state instead of opening a new tab:

{sent ? (
  <div className="text-center space-y-4">
    <CheckCircle size={48} className="text-neo-green" />
    <h2 className="text-2xl font-black uppercase">Check Your Inbox</h2>
    <p className="font-medium opacity-80">
      A download link has been sent to <span className="font-black">{email}</span>.
      It expires in <span className="font-black">15 minutes</span>.
    </p>
    <Button variant="dark" size="md" onClick={onClose} fullWidth>Done</Button>
  </div>
) : (
  // ... form
)}


Part 5 — The Sender Name

First real email came in showing Portfolio Backend V2 as the sender. Not ideal.

The display name in From: headers comes from DEFAULT_FROM_EMAIL. It was hardcoded in the settings default:

# Before
DEFAULT_FROM_EMAIL = env(
    "DJANGO_DEFAULT_FROM_EMAIL",
    default="Portfolio Backend V2 <noreply@vicentereyes.org>",
)

# After
DEFAULT_FROM_EMAIL = env(
    "DJANGO_DEFAULT_FROM_EMAIL",
    default="Vicente Reyes <noreply@vicentereyes.org>",
)

One-line fix. The env var takes precedence if set on the server, so updating the default in code is just the fallback.


The Full Stack at a Glance

Browser                     Django                       S3
  │                            │                          │
  │ POST /api/resume/           │                          │
  │   request-download/         │                          │
  │   { email }                 │                          │
  │ ─────────────────────────► │                          │
  │                            │ validate email            │
  │                            │ block disposable domains  │
  │                            │ log ResumeDownloadRequest │
  │                            │ TimestampSigner.sign()    │
  │                            │ build_absolute_uri()      │
  │                            │ send_mail() ──────────────────► inbox
  │ ◄───────────────────────── │                          │
  │   { message: "Check        │                          │
  │     your inbox" }          │                          │
  │                            │                          │
  │ [user clicks email link]   │                          │
  │                            │                          │
  │ GET /api/resume/download/  │                          │
  │   ?token=<signed>          │                          │
  │ ─────────────────────────► │                          │
  │                            │ verify token (15 min)     │
  │                            │ resume.pdf.url ──────────► presigned URL
  │                            │                          │   (120 sec)
  │ ◄───────────────────────── │                          │
  │   302 → presigned URL      │                          │
  │                            │                          │
  │ GET presigned URL ─────────────────────────────────► │
  │ ◄───────────────────────────────────────────────── PDF│


What I'd Do Differently

Rate-limit the POST endpoint. Right now someone can hammer POST /api/resume/request-download/ with valid emails and flood inboxes. A simple per-IP throttle class on the view would fix it.

Consider Celery for the email send. send_mail in the request/response cycle means the API response waits for the SMTP round trip. On Mailgun it's fast, but wrapping it in a task would make the response instant and give you retries for free.

The existing S3 object still needs its ACL changed manually. The private storage fix applies to new uploads. Vicente_Reyes_Resume.pdf was already uploaded as public. Re-uploading via admin or changing the object ACL in the AWS console closes that gap.