Building Complete Legal Aid for Production

In this article · 12 sections
A legal-aid platform is a coordination system before it is an AI interface. Citizens, lawyers and administrators see different information, messages arrive after the browser disconnects, documents have an access history, and a drafting request may remain unfinished when an external model times out. A polished dashboard can conceal those problems during a demo without solving them.
Complete Legal Aid is the project behind this walkthrough. My portfolio describes my work as full-stack development and AI integration. Here I focus on the engineering boundaries a reader can reuse: authorization, state transitions, event delivery, document access and model-assisted drafting. Examples are simplified design patterns, not instructions for a particular legal matter or claims of an independently audited system.
Begin with actors and operations
“Citizen dashboard,” “lawyer dashboard” and “admin dashboard” are navigation concepts. They are not access-control rules. A useful authorization model names the caller, operation and resource: can this citizen view this case attachment, can this lawyer edit this draft, can this administrator approve this specific transition?
A role alone is too broad. Two citizens share a role but must not automatically see each other's documents. A lawyer's relationship to a case can change, so assignment is a fact to check at the time of access rather than a permission permanently implied by their profession.
Start with a matrix of operations and relationships. For each operation, define the allowed role, required resource membership, relevant case state and the response when access is denied. That matrix becomes a source for endpoint checks and negative tests. It also exposes product questions that a frontend alone cannot answer.
Trace one workflow across the boundaries
Consider a citizen submitting documents, a lawyer reviewing them and an AI service proposing a draft. The upload endpoint authorizes the citizen against the case. The storage layer assigns an internal object identifier. A review event becomes visible to the assigned lawyer. A drafting request reads only the authorized material, produces a draft and records its status.
No single step should infer that every later step is permitted. A successful upload does not grant every connected WebSocket client access. A drafting tool should not receive a storage URL simply because a browser previously displayed it. Each boundary needs an explicit contract.
For debugging, attach a correlation identifier to the workflow and stable identifiers to its case, document and drafting attempt. Do not use the raw document body as a debugging shortcut. A trace should explain where an operation failed without becoming a second uncontrolled copy of sensitive content.
Authenticate the connection and authorize the object
The inspected realtime code includes per-user streams and a case-presence consumer. The presence connection checks authentication, account status and case access before joining the case's group. That is the right kind of boundary to look for: group membership is a consequence of authorization, not a substitute for it.
The Django Channels security guide also explains why WebSocket origin checks matter. An authenticated browser session does not make every origin safe. Connection authentication, allowed origins and resource-level authorization address different risks and should not be collapsed into one “secured socket” checkbox.
Long-lived connections need a policy for changed permissions. If a lawyer is reassigned after connecting, what happens to existing subscriptions? Recheck authorization for protected operations and decide how revocation reaches active connections. A check performed once at connection time does not establish permanent entitlement.
Model transitions instead of loosely related booleans
An appointment can be requested, accepted, cancelled or completed. A draft can be queued, running, ready or failed. Several independent booleans can accidentally encode impossible combinations, such as a draft being both ready and failed.
Define permitted transitions and make them explicit at the service boundary. Include the expected current state in an update so two callers cannot silently overwrite one another's decisions. If two operations race, one should detect the conflict and return a useful response rather than invent a new state through timing.
This teaching example demonstrates a transition check without prescribing the project's database schema:
ALLOWED = {
"queued": {"running", "cancelled"},
"running": {"ready", "failed"},
"ready": set(),
"failed": {"queued"},
"cancelled": set(),
}
def transition(current, target):
if target not in ALLOWED.get(current, set()):
raise ValueError(f"invalid transition: {current} -> {target}")
return target
assert transition("running", "ready") == "ready"
The function checks a local rule. A production update also needs a transaction or conditional write to ensure that current has not changed since it was read. A pure Python state machine cannot by itself coordinate concurrent workers.
A successful write and a delivered event are different facts
Suppose a database transaction saves a message, then the process crashes before publishing the notification. The message exists, but another browser sees no realtime update. Reversing the order can produce a notification for data that later rolls back.
An outbox design addresses this by saving a durable event record with the business write and delivering it separately. The worker can retry delivery; consumers must tolerate duplicates. This is a proposed reliability pattern, not a claim that every Complete Legal Aid event currently uses an outbox.
Django's transaction documentation describes atomic blocks and commit hooks. A commit hook is useful for avoiding publication before commit, but it is not itself a durable queue. The distinction becomes visible when the process dies after commit and before the hook finishes its external work.
Design reconnect as recovery rather than a fresh start
Realtime delivery should improve responsiveness, not be the only route to truth. After reconnecting, a client needs a way to retrieve authoritative state and identify events it may have missed. Stable message identifiers and a cursor make that recovery possible.
The interface should distinguish queued, acknowledged and failed sends. If a user retries the same message after a timeout, an idempotency key can prevent duplicate creation. The server decides whether the operation already completed; the browser should not infer failure merely because its acknowledgement was lost.
Test this deliberately: disconnect immediately after sending, reconnect, then retry. The desired outcome is a single durable message with a recoverable status. Count what the server stored, not only what appeared during an uninterrupted browser session.
Treat document access as a separate operation
An opaque filename is not an access-control system. The service that resolves a document identifier should verify the caller's relationship to the case. If using time-limited download links, define their lifetime and the consequences of forwarding a link to someone else.
Uploads require size limits, permitted formats and careful handling of filenames and content. A browser-provided MIME type is a hint rather than proof. Keep access logs focused on identifiers and outcomes. Avoid logging the body of an uploaded document simply because a request failed.
Deletion and revocation need their own behavior. A document removed from a dashboard should not remain indefinitely available through an old public path. An engineering review should inspect the storage route and authorization path, not only the UI's visibility condition.
Bound the authority of an AI drafting workflow
A drafting service should receive the smallest authorized context needed for its task. Give it a narrow output contract and a set of approved operations. Treat document contents as source material, including when a document contains text that looks like an instruction to the assistant.
The inspected agent guardrail module includes jurisdiction framing, a non-advice disclaimer and regular-expression redaction for obvious identifiers in logs. These are useful controls, but regex matching is incomplete and a disclaimer does not establish factual correctness or enforce tool authorization. Server-side access checks must stand independently of model compliance.
Keep the output labeled as a draft and preserve the distinction between source text, model-generated text and reviewed text. If a referenced passage cannot be located in the source material, do not turn that absence into a confident citation. Evidence traceability is part of the workflow, not a decoration added after generation.
Measure drafting quality beyond time saved
A short generation time can coexist with a long review time. I would separate queue delay, model latency, time to a reviewable draft and time spent correcting unsupported or missing content. Report the task definition and sample size before claiming an efficiency improvement.
The earlier blog included a 45-minute-to-under-3-minute comparison without the benchmark protocol needed to interpret it. This article does not present that comparison as a validated general result. A useful future evaluation would use a consistent set of drafting tasks, a documented review rubric and a clear separation between automated output and human acceptance.
For the application itself, useful tests include another citizen's document identifier, a revoked lawyer assignment, a repeated callback, an unavailable model provider and a worker restart during generation. Those tests examine boundaries that an ordinary happy-path demo misses.
Deployment is part of the application contract
The frontend, HTTP API, socket service, background workers and storage depend on different runtime conditions. Check health separately and expose readiness only when a service can perform its essential function. A process listening on a port is not evidence that its queue or database is usable.
Keep production secrets outside the browser bundle, terminate TLS correctly and document backups and restore procedures. Rollback needs to account for schema compatibility as well as container versions. A new image that expects a new column cannot necessarily be replaced by an old image without a plan.
These are deployment requirements to verify, not a blanket certification of the project. The Django deployment checklist is a useful primary reference for framework-level checks.
A concrete exercise for the reader
Implement a draft job with four states and an idempotency key. Simulate a crash after saving the result but before sending the browser its notification. Restart the worker, reconnect the client and verify that the result appears once.
Then repeat the retrieval using an account that has no case relationship. The same data should remain recoverable for the authorized user and unavailable to the unauthorized one. Reliability and access control must both survive the recovery path.
Sources and project context
- Complete Legal Aid project case study: portfolio context and project scope. The implementation repository is private; access can be requested through the project page.
- Django Channels: security.
- Django: database transactions.
- Django: deployment checklist.
The state-machine code, failure scenarios and outbox discussion are explanatory designs. They should not be read as claims that every proposed reliability improvement is already implemented or independently audited.