# How i-have-adhd Handles User Authentication: JWT Middleware Explained

> Learn how i-have-adhd handles user authentication using JWT middleware. Discover how it validates Bearer tokens and secures your data.

- Repository: [Ayoub Ghriss/i-have-adhd](https://github.com/ayghri/i-have-adhd)
- Tags: deep-dive
- Published: 2026-07-30

---

**The i-have-adhd skill implements JSON Web Token (JWT) authentication via middleware that validates Bearer tokens in the `Authorization` header, returning 401 Unauthorized for missing or invalid credentials.**

The `ayghri/i-have-adhd` repository defines an Instagit skill that relies on external JWT issuance while handling verification internally. According to the project documentation in [`skills/i-have-adhd/SKILL.md`](https://github.com/ayghri/i-have-adhd/blob/main/skills/i-have-adhd/SKILL.md), the authentication flow delegates user credential management to the host platform while enforcing token validation at the skill level.

## JWT Authentication Architecture

The skill adopts a stateless authentication model where the Instagit or Cursor platform issues signed JWTs to authenticated users. The skill itself does not store user passwords or session data; instead, it expects every incoming request to carry a valid token in the HTTP headers.

**Key architectural decisions:**
- **Platform-issued tokens**: The surrounding Instagit infrastructure generates and signs JWTs using a shared secret
- **Bearer token pattern**: Clients must include `Authorization: Bearer <token>` in request headers
- **Middleware verification**: A centralized middleware function intercepts requests before they reach business logic handlers

## Token Verification Implementation

The verification logic is designed to reside in [`src/auth.ts`](https://github.com/ayghri/i-have-adhd/blob/main/src/auth.ts) (referenced at line 42 in the documentation), utilizing the `jsonwebtoken` npm package to validate token signatures and expiration.

**Middleware responsibilities:**
1. Extract the token from the `Authorization` header
2. Verify the token against the `JWT_SECRET` environment variable
3. Attach the decoded payload to the request object for downstream use
4. Return **401 Unauthorized** if validation fails

```typescript
import jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';

export const verifyToken = (req: Request, res: Response, next: NextFunction) => {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing token' });
  }

  const token = authHeader.split(' ')[1];
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!);
    // Attach user info to request for later handlers
    (req as any).user = decoded;
    next();
  } catch (e) {
    return res.status(401).json({ error: 'Invalid token' });
  }
};

```

As noted in the project documentation, developers must run `npm install jsonwebtoken` and configure the verification middleware in `src/auth.ts:42` to enable this flow.

## Handling Authenticated Requests

Clients interacting with the i-have-adhd API must obtain a valid JWT from the Instagit platform before making requests. The following Node.js example demonstrates the proper header formatting:

```javascript
import fetch from 'node-fetch';

// Assume you already have a valid JWT stored in `myToken`
const myToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6...';

fetch('https://api.instagit.com/i-have-adhd/endpoint', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${myToken}`,
    'Content-Type': 'application/json',
  },
})
  .then(res => {
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return res.json();
  })
  .then(data => console.log('Authenticated response:', data))
  .catch(err => console.error('Auth error:', err));

```

The skill strictly enforces that the `Authorization` header follows the Bearer scheme; deviations result in immediate rejection.

## Error Handling and Test Coverage

The authentication layer includes specific error responses validated by the test suite. According to [`auth.spec.ts`](https://github.com/ayghri/i-have-adhd/blob/main/auth.spec.ts) (referenced in the documentation), the middleware must return a 401 status code when:

- The `Authorization` header is completely absent
- The header value does not start with `Bearer `
- The token signature is invalid or expired
- The token format is malformed

The test case at `auth.spec.ts:42` explicitly checks for this behavior, expecting a 401 response when authentication headers are missing, contrasting with the 200 OK returned for valid requests.

## Summary

- **i-have-adhd authentication** relies on JWT Bearer tokens validated by middleware in [`src/auth.ts`](https://github.com/ayghri/i-have-adhd/blob/main/src/auth.ts)
- The skill uses the **`jsonwebtoken`** package to verify signatures against a `JWT_SECRET` environment variable
- Requests must include `Authorization: Bearer <token>` headers; missing or invalid tokens yield **401 Unauthorized**
- User account management is delegated to the Instagit platform; the skill only handles token verification
- Test coverage in [`auth.spec.ts`](https://github.com/ayghri/i-have-adhd/blob/main/auth.spec.ts) validates that unauthenticated requests are rejected at line 42

## Frequently Asked Questions

### How does i-have-adhd verify JWT tokens?

The skill uses a middleware function—typically implemented in [`src/auth.ts`](https://github.com/ayghri/i-have-adhd/blob/main/src/auth.ts)—that extracts the token from the `Authorization: Bearer <token>` header and validates it using the `jsonwebtoken` library. The verification checks the token signature against the `JWT_SECRET` environment variable and ensures the token has not expired before attaching the decoded payload to the request object.

### What happens if the Authorization header is missing?

The middleware returns a **401 Unauthorized** response with an error message indicating the missing token. As documented in the test specifications at `auth.spec.ts:42`, requests without proper authentication headers fail immediately without reaching the business logic handlers.

### Does i-have-adhd manage user accounts?

No, the skill does not handle user registration, password storage, or account management. It relies on the surrounding Instagit or Cursor platform to authenticate users and issue signed JWTs. The skill's responsibility is limited to verifying that incoming tokens are valid and unexpired.

### Where is the authentication logic located?

While the primary documentation resides in [`skills/i-have-adhd/SKILL.md`](https://github.com/ayghri/i-have-adhd/blob/main/skills/i-have-adhd/SKILL.md), the implementation references [`src/auth.ts`](https://github.com/ayghri/i-have-adhd/blob/main/src/auth.ts) as the location for the `verifyToken` middleware. The documentation instructs developers to install the `jsonwebtoken` dependency and implement the verification logic at line 42 of that file, though the actual source file may need to be created during skill setup.