0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Designing a Visitor Check-in Backend: QR Tokens, Watchlist Matching and Arabic Support

0
Posted at

Introduction

Visitor check-in looks like a simple CRUD problem: a guest arrives, you save a row, you print a badge. In practice, a real front desk system has to deal with duplicate visitors, expired invitations, replayed QR codes, watchlist matching, unreliable notification channels and two languages at once.

This article walks through the backend design of a visitor check-in flow and the issues worth planning for before you ship. The examples use Python with FastAPI and PostgreSQL, but the ideas apply to any stack.

1. Model the visit, not just the visitor

A common first mistake is to store only a visitors table. A person can visit many times, invited by different hosts, with different access zones. Separate the identity from the event.

CREATE TABLE visitors (
    id            UUID PRIMARY KEY,
    full_name     TEXT NOT NULL,
    phone         TEXT,
    email         TEXT,
    id_doc_hash   TEXT,          -- hash of the ID number, never the raw value
    photo_key     TEXT,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE visits (
    id             UUID PRIMARY KEY,
    visitor_id     UUID NOT NULL REFERENCES visitors(id),
    host_id        UUID NOT NULL,
    zones          TEXT[] NOT NULL,
    status         TEXT NOT NULL CHECK (status IN
                   ('invited','checked_in','checked_out','denied','expired')),
    valid_from     TIMESTAMPTZ NOT NULL,
    valid_until    TIMESTAMPTZ NOT NULL,
    checked_in_at  TIMESTAMPTZ,
    checked_out_at TIMESTAMPTZ,
    qr_nonce       TEXT
);

CREATE INDEX visits_on_site ON visits (status) WHERE status = 'checked_in';

The partial index on checked_in matters more than it looks. During an evacuation, the only query anyone cares about is "who is in the building right now", and it has to be instant.

Note the id_doc_hash column. Storing raw national ID or passport numbers creates a privacy liability. A keyed hash (HMAC) still lets you detect repeat visitors without keeping the number itself.

import hmac, hashlib, os

ID_KEY = os.environ["ID_HASH_KEY"].encode()

def hash_id_number(raw: str) -> str:
    normalized = raw.replace("-", "").replace(" ", "").upper()
    return hmac.new(ID_KEY, normalized.encode(), hashlib.sha256).hexdigest()

2. Make QR invitations single-use and short-lived

Pre-registration usually sends the guest a QR code. If that QR simply contains the visit ID, anyone with a screenshot can check in, and the same code can be reused forever.

A safer pattern is a signed token with an expiry and a one-time nonce:

import secrets, time, jwt  # PyJWT

SECRET = os.environ["QR_SECRET"]

def issue_qr_token(visit_id: str, valid_until: int) -> tuple[str, str]:
    nonce = secrets.token_urlsafe(16)
    token = jwt.encode(
        {"vid": visit_id, "nonce": nonce, "exp": valid_until},
        SECRET, algorithm="HS256",
    )
    return token, nonce  # store the nonce on the visit row

At check-in, verify the signature, check the expiry, then consume the nonce atomically so the same code cannot be used twice:

from fastapi import HTTPException

async def redeem_qr(db, token: str):
    try:
        claims = jwt.decode(token, SECRET, algorithms=["HS256"])
    except jwt.ExpiredSignatureError:
        raise HTTPException(410, "Invitation expired")
    except jwt.InvalidTokenError:
        raise HTTPException(400, "Invalid code")

    row = await db.fetchrow(
        """
        UPDATE visits
           SET status = 'checked_in', checked_in_at = now(), qr_nonce = NULL
         WHERE id = $1 AND qr_nonce = $2 AND status = 'invited'
        RETURNING id, visitor_id, host_id, zones
        """,
        claims["vid"], claims["nonce"],
    )
    if row is None:
        raise HTTPException(409, "Code already used or visit not active")
    return row

The WHERE ... AND status = 'invited' condition turns the update into a compare-and-set. Two kiosks scanning the same code at the same moment cannot both succeed.

3. Watchlist matching is fuzzy by nature

Exact string matching on names fails quickly. Names are transliterated differently ("Mohammed", "Mohamed", "Muhammad"), written in Arabic or Latin script, and entered with typos.

A practical approach combines several signals:

  1. Exact match on id_doc_hash (strongest signal).
  2. Normalized name similarity using trigram matching.
  3. Optional face match score from the kiosk camera.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX watchlist_name_trgm ON watchlist USING gin (name_norm gin_trgm_ops);

SELECT id, name, similarity(name_norm, $1) AS score
  FROM watchlist
 WHERE id_doc_hash = $2
    OR name_norm % $1
 ORDER BY (id_doc_hash = $2) DESC, score DESC
 LIMIT 5;

Two design rules help here. First, a watchlist hit should never silently deny entry; it should raise an alert to a human. False positives are common, and a guest being turned away by a machine is a bad experience. Second, log every screening decision with its score so security teams can audit why an alert fired.

4. Host notifications must not block check-in

The guest should not wait at the kiosk while your SMS provider times out. Notification is a side effect, so push it to a queue and return immediately.

async def check_in(db, queue, token: str):
    visit = await redeem_qr(db, token)
    await queue.enqueue("notify_host", {
        "visit_id": str(visit["id"]),
        "channels": ["push", "email", "sms"],
    })
    return {"status": "checked_in", "badge": build_badge(visit)}

The worker should try channels in order and record which one succeeded. Make the job idempotent with the visit ID as a key, because queues deliver at least once and hosts do not want three identical messages.

5. Arabic and English at the same time

Bilingual kiosks raise problems that are easy to miss in testing:

  • Direction: set dir="rtl" on the root element for Arabic and use logical CSS properties (margin-inline-start instead of margin-left) so the layout mirrors correctly.
  • Mixed content: a badge may show an Arabic name next to a Latin company name and a phone number. Wrap each value in its own element with dir="auto" to avoid scrambled ordering.
  • Fonts: pick a font with full Arabic coverage for the badge printer, and test it at the printer's actual resolution.
  • Search: normalize Arabic text before matching (remove diacritics, unify alef forms) so "أحمد" and "احمد" match.
import re

AR_DIACRITICS = re.compile(r"[\u064B-\u0652]")

def normalize_ar(text: str) -> str:
    text = AR_DIACRITICS.sub("", text)
    return text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")

6. Do not forget check-out

Most systems handle check-in well and check-out badly. Guests leave without tapping out, so the "on site" list drifts away from reality. A scheduled job that closes visits after valid_until, plus exit readers on turnstiles where possible, keeps the evacuation list trustworthy.

UPDATE visits
   SET status = 'expired', checked_out_at = valid_until
 WHERE status = 'checked_in' AND valid_until < now();

Seeing it in a real product

These patterns are the building blocks of a production Visitor Management System. TekVisit, used by organisations in the UAE, combines touchless check-in by face, QR or Emirates ID, pre-registration with NDA signing, watchlist screening, instant host notifications, smart badge printing and full Arabic support on top of a flow very similar to the one described above.

Summary

  • Separate visitors from visits, and index the "on site" query.
  • Hash ID numbers instead of storing them.
  • Use signed, expiring, single-use QR tokens with a compare-and-set update.
  • Treat watchlist matching as fuzzy, and alert humans instead of auto-denying.
  • Send notifications asynchronously and idempotently.
  • Design for right-to-left text, mixed scripts and Arabic normalization from day one.
  • Automate check-out so emergency headcounts stay accurate.

If you are building something similar, I hope these notes save you a few production incidents.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?