Multi-User Isolation and Authentication for an AI Writing Assistant

    This article explains how to turn a single-user AI writing assistant into a multi-user system using a simple ownership chain, a namespaced memory key, and token-based authentication. You will see the three-table data model (parent, child, chat window), how to build a parentId:childId:windowId memory key to stop conversations from mixing, how to implement registration, login, and stateless tokens, and how a lightweight interceptor injects the current user into every request. It also covers the end-to-end request flow and common pitfalls such as authorization checks, token expiry, and key migration.

    Multi-User Isolation and Authentication for an AI Writing Assistant

    1. Where the Problem Starts: Why the AI “Remembers Someone Else’s Words”

    In an early version of an AI homework writing assistant, the system typically served a single user. Every conversation was written into the same memory, and the session identifier sent with each model call was a fixed value. On the surface everything worked. The problem showed up as soon as two children shared the system: the younger one kept chatting, and the model casually continued with a sentence the older one had said earlier.

    This is not the model having a good memory. It is that both conversations were written under the same key. A large language model is usually a stateless inference service; it has no idea who you are. What actually decides “what it remembers” is the session identifier the caller sends in the request, and the history the server pulls based on that identifier. So the core of multi-user isolation is not mysterious: it is a key namespace problem. As long as the key uniquely identifies who is talking, in which window, and about which conversation, memories will not bleed into each other.

    This article takes a general technical perspective and lays out a practical approach: upgrade the system from “one person uses it” to “a family uses it,” with support for a parent account, child profiles, and multiple chat windows, while token authentication ensures each request can only access its own data.

    2. Data Model: An Ownership Chain from Parent to Window

    Multi-user isolation starts with a clear ownership relationship. Keep just three core tables that form a chain: parent 1→N child 1→N window.

    1. -- Parent account: store only the password hash
    2. CREATE TABLE IF NOT EXISTS parent_account (
    3. id INTEGER PRIMARY KEY AUTOINCREMENT,
    4. username TEXT NOT NULL UNIQUE,
    5. password_hash TEXT NOT NULL,
    6. created_at TEXT NOT NULL DEFAULT (datetime('now'))
    7. );
    8. -- Child profile: nickname only, owned by a parent
    9. CREATE TABLE IF NOT EXISTS child_profile (
    10. id INTEGER PRIMARY KEY AUTOINCREMENT,
    11. parent_id INTEGER NOT NULL,
    12. nickname TEXT NOT NULL,
    13. created_at TEXT NOT NULL DEFAULT (datetime('now')),
    14. FOREIGN KEY (parent_id) REFERENCES parent_account(id)
    15. );
    16. -- Chat window: one child can open several, each with independent memory
    17. CREATE TABLE IF NOT EXISTS chat_window (
    18. id INTEGER PRIMARY KEY AUTOINCREMENT,
    19. child_id INTEGER NOT NULL,
    20. title TEXT NOT NULL DEFAULT 'New chat',
    21. created_at TEXT NOT NULL DEFAULT (datetime('now')),
    22. FOREIGN KEY (child_id) REFERENCES chat_profile(id)
    23. );

    Three design points matter:

    1. Children do not register on their own. A child is just a nickname under a parent, which avoids the burden of having young users manage passwords and naturally keeps permissions with the parent.
    2. The window is the smallest unit of memory. Multiple windows for the same child act as separate homework scenarios (Chinese, math, English) that do not contaminate each other.
    3. Foreign keys form the ownership chain. Every later query must validate along parent → child → window, not just look up by window ID.

    3. The Truth About Memory Isolation: Combine IDs into a Namespace

    With the ownership chain in place, the memory key follows naturally: parentId:childId:windowId.

    1. String memoryId = parentId + ":" + childId + ":" + windowId;

    In AI application development frameworks that support separating memory by session identifier, there is usually an annotation or parameter for passing that identifier. Its semantics are equivalent to a Map key: different keys map to different history lists. Once you understand this, isolation comes down to three constraints:

    • On write: build the key from the currently logged-in parent, current child, and current window. Never use a fixed string.
    • On read: build the key from the same triple; if no history is found, treat it as a new session.
    • Authorization protection: the window ID cannot be freely supplied by the frontend. You must verify it belongs to a child under the current parent.

    A common mistake is “isolating only by child.” If multiple windows for the same child share one key, the AI will still mix math problems with essays. Window-level isolation is what keeps things clean.

    4. Authentication Design: Lightweight Hashing Plus Tokens, Nothing More

    The requirement is “register, log in, and intercept requests,” not a full security filter chain. Just bring in one password hashing component, and avoid taking on the complexity of an entire framework for a simple need.

    4.1 Registration: Hash into the Database, Register and Log In at Once

    1. // Pseudocode: registration flow
    2. String hash = passwordEncoder.encode(rawPassword); // Use a strong hash such as BCrypt
    3. try {
    4. dao.insertParent(username, hash);
    5. } catch (DuplicateKeyException e) {
    6. return "Username already registered"; // Hit the UNIQUE constraint
    7. }
    8. String token = tokenService.issue(parentId); // Issue a token right after successful registration

    Key points:

    • Never store passwords in plaintext; use a salted strong hash algorithm (BCrypt and similar are common in the industry).
    • Leave username uniqueness to the database; on a constraint collision, return a friendly message.
    • Issue a token immediately after successful registration, which is equivalent to “register and log in at once” and saves a step.

    4.2 Login: A Nearly Identical Flow, Fewer Inserts, More Password Verification

    Login is almost identical to registration: look up the hash by username, compare the plaintext with the hasher; on failure return a single generic error to avoid revealing whether the user does not exist or the password is wrong; on success, issue a token.

    4.3 Tokens: Stateless, Verifiable, with Expiry

    For tokens, use the industry-standard three-part “header.payload.signature” structure, put parentId and an expiry time in the payload, and verify the signature on the server with a secret key. This identifies the user without a database lookup, which suits small and medium-sized applications.

    1. token = base64(header) + "." + base64(payload) + "." + sign
    2. payload = { "parentId": 1, "exp": 1730000000 }

    5. Interceptor: Every Request First Asks “Who Are You”

    A token only matters if it is verified on every protected request. A lightweight interceptor is enough:

    1. public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object h) {
    2. String auth = req.getHeader("Authorization");
    3. if (auth == null || !auth.startsWith("Bearer ")) {
    4. resp.setStatus(401); return false;
    5. }
    6. Claims c = tokenService.verify(auth.substring(7)); // Verify signature + expiry
    7. if (c == null) { resp.setStatus(401); return false; }
    8. req.setAttribute("parentId", c.get("parentId")); // Inject the current user
    9. return true;
    10. }

    Key conventions:

    • The frontend sends the token in the request header, and the server uniformly injects parentId; the business layer no longer trusts a user ID passed from the frontend.
    • All endpoints that query windows, query history, or send messages go through the interceptor.
    • Status codes are clear: 401 for unauthenticated, 403 for authenticated but unauthorized.

    6. End-to-End Flow: How One Question Avoids Crossing Wires

    Putting the pieces together, the full flow of a single question is:

    1. The frontend sends a “send message” request with the token, plus childId and windowId.
    2. The interceptor verifies the signature and injects parentId.
    3. The server checks that windowId belongs to the childId under that parentId, otherwise 403.
    4. It loads history with parentId:childId:windowId, assembles the context, and calls the model.
    5. It writes the new question and answer back to the same key and updates the window title (for example, using the first several characters of the first question).

    This way, the older child and the younger one, math and essays, yesterday and today, all land in different namespaces and never mix.

    7. Common Pitfalls and Hardening Tips

    • Store only hashes, never plaintext: no log or exception stack trace should ever contain a raw password.
    • Token expiry and refresh: set a reasonable validity period and provide a refresh mechanism when needed; for logout, maintain a server-side blacklist.
    • The authorization triple: querying windows, querying history, and sending messages must all verify ownership; you cannot rely on hiding buttons in the frontend.
    • Key length and migration: the triple key must stay stable; if you later add a “device” dimension, design a compatible migration strategy.
    • Observability: use a general logging service to record authentication failures and blocked unauthorized access, and pair it with monitoring and alerts to spot abnormal endpoint abuse.
    • Deployment shape: if you later move to the cloud, you can run the application on a container platform, put static assets in object storage, and use logging and monitoring services for auditing, all through general-purpose capability categories.

    8. Summary

    Multi-user isolation does not rely on advanced tricks. It is a refactor that turns implicit sharing into an explicit namespace: an ownership chain defines relationships in the data, a triple key separates sessions in memory, hashing plus tokens guard the entrance in authentication, and the interceptor injects identity into every request. After these four steps, the AI writing assistant can genuinely “tell the older child from the younger one,” and it leaves a clear boundary for later expansion to multiple devices and multiple roles.