# Refresh Token Implementation

This document explains the implementation of the refresh token system in the LensSeek application, which keeps users logged in until they explicitly log out.

## Backend Implementation

### 1. Session Model Extension

The Session model has been extended to include refresh tokens and additional metadata:

```prisma
model Session {
  id           String   @id @default(cuid())
  userId       String
  refreshToken String   @unique
  expiresAt    DateTime
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt
  lastUsedAt   DateTime @default(now())
  device       String?
  ipAddress    String?
  userAgent    String?
  isActive     Boolean  @default(true)
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}
```

### 2. Auth Service Enhancements

The Auth Service now includes:

- `createSession`: Creates a new session with refresh token
- `refreshToken`: Validates refresh token and issues new access token
- `revokeSession`: Deactivates a specific session
- `revokeAllSessions`: Deactivates all sessions for a user

### 3. New API Endpoints

New endpoints have been added:

- `POST /auth/refresh`: Exchanges a refresh token for a new access token
- `POST /auth/logout`: Revokes a specific refresh token
- `POST /auth/logout-all`: Revokes all refresh tokens for the user

## Frontend Implementation

### 1. Token Storage

Both access and refresh tokens are stored securely:

- On web: Using localStorage
- On mobile: Using SecureStore

### 2. Automatic Token Refresh

The API utility has been enhanced with interceptors that:

- Automatically attach the access token to requests
- Detect 401 Unauthorized errors
- Use the refresh token to obtain a new access token
- Retry the original request
- Queue any concurrent requests during the refresh process

### 3. Session Management

The Session context now:

- Stores and manages both access and refresh tokens
- Properly handles logout by revoking refresh tokens
- Maintains persistent sessions across app restarts

## Security Considerations

1. Refresh tokens have a long expiration (30 days by default)
2. Access tokens maintain a short expiration (60 minutes)
3. Refresh tokens are invalidated on logout
4. Each session tracks device information for auditing
5. Sessions can be revoked individually or all at once

## Migration

Run the following command to apply the necessary database changes:

```bash
# On Linux/Mac
./packages/api/scripts/apply-refresh-token.sh

# On Windows
.\packages\api\scripts\apply-refresh-token.bat
```

## Testing

Test the implementation by:

1. Logging in and checking that a refresh token is received
2. Waiting for the access token to expire (or manually expire it)
3. Making a new request and verifying it succeeds due to automatic refresh
4. Testing logout and confirming the refresh token is revoked
