> ## Documentation Index
> Fetch the complete documentation index at: https://help.hoopai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# User Context in Marketplace Apps

> Access user context in your HoopAI Platform marketplace app

# User Context in Marketplace Apps

The HoopAI Platform provides a secure mechanism for accessing authenticated user information through signed tokens. This guide explains how to generate and use a **Shared Secret** key to access user context securely.

## Setting Up Shared Secret

### Generating a Shared Secret Key

1. Navigate to your application's **Advanced Settings**.
2. Go to the **Auth** section.
3. Under **Shared Secret**, click the **Generate** button to create your Shared Secret key.

***

## Frontend Implementation Methods

There are two ways to access this data in your frontend, depending on where your code runs.

### 1. Custom JavaScript Implementation

If you are using custom JavaScript injected into HoopAI Platform pages, use the `exposeSessionDetails` method:

```javascript theme={null}
async function getUserData() {
  try {
    // APP_ID is your application's unique identifier
    const encryptedUserData = await window.exposeSessionDetails(APP_ID)

    // Send this encrypted data to your backend for decryption
    const response = await fetch('your-backend-endpoint', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ encryptedData: encryptedUserData })
    })

    const userData = await response.json()
    return userData
  } catch (error) {
    console.error('Failed to fetch session details:', error)
    throw error
  }
}
```

### 2. Custom Pages Implementation

If you are trying to get user context in a custom page, use the `postMessage` method to communicate with the parent window:

```javascript theme={null}
async function getUserData() {
  try {
    const encryptedUserData = await new Promise((resolve) => {
      // Request user data from parent window
      window.parent.postMessage({ message: 'REQUEST_USER_DATA' }, '*')

      // Listen for the response
      const messageHandler = ({ data }) => {
        if (data.message === 'REQUEST_USER_DATA_RESPONSE') {
          window.removeEventListener('message', messageHandler)
          resolve(data.payload)
        }
      }

      window.addEventListener('message', messageHandler)
    })

    // Send encrypted data to your backend for decryption
    const response = await fetch('your-backend-endpoint', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ encryptedData: encryptedUserData })
    })

    const userData = await response.json()
    return userData
  } catch (error) {
    console.error('Failed to fetch user data:', error)
    throw error
  }
}
```

***

## Backend Implementation

Regardless of which frontend method you use, the backend decryption process is the same:

```javascript theme={null}
const CryptoJS = require('crypto-js')

function decryptUserData(encryptedUserData, sharedSecretKey) {
  try {
    const decrypted = CryptoJS.AES.decrypt(encryptedUserData, sharedSecretKey)
      .toString(CryptoJS.enc.Utf8)
    return JSON.parse(decrypted)
  } catch (error) {
    throw new Error('Failed to decrypt user data')
  }
}

// Example Express endpoint
app.post('/decrypt-user-data', (req, res) => {
  try {
    const { encryptedData } = req.body
    const userData = decryptUserData(encryptedData, process.env.HOOPAI_APP_SHARED_SECRET)
    res.json(userData)
  } catch (error) {
    res.status(400).json({ error: 'Failed to decrypt user data' })
  }
})
```

***

## Decrypted Data Structure

After decryption, the data is returned as a JSON object containing user information. The structure varies based on whether the user is accessing from a Company or Location context.

### Company Context

```json theme={null}
{
  "userId": "MKQJ7wOVVmNOMvrnKKKK",
  "companyId": "GNb7aIv4rQFVb9iwNl5K",
  "role": "admin",
  "type": "agency",
  "userName": "John Doe",
  "email": "johndoe@gmail.com"
}
```

### Location Context

```json theme={null}
{
  "userId": "MKQJ7wOVVmNOMvrnKKKK",
  "companyId": "GNb7aIv4rQFVb9iwNl5K",
  "role": "admin",
  "type": "agency",
  "activeLocation": "yLKVZpNppIdYpah4RjNE",
  "userName": "John Doe",
  "email": "johndoe@gmail.com"
}
```

### Field Descriptions

| Field            | Type   | Description                                                                         |
| ---------------- | ------ | ----------------------------------------------------------------------------------- |
| `userId`         | string | Unique identifier for the user                                                      |
| `companyId`      | string | Unique identifier for the company                                                   |
| `role`           | string | User's role in the system (e.g., `admin`, `user`)                                   |
| `type`           | string | Context type: `company` (company-level access) or `location` (account-level access) |
| `activeLocation` | string | (Location context only) Unique identifier for the active location                   |
| `userName`       | string | Full name of the user                                                               |
| `email`          | string | User's email address                                                                |

***

## Security Considerations

* Never expose your Shared Secret key in client-side code.
* Always perform decryption on your backend.
* Store your Shared Secret key securely using environment variables.
* Use HTTPS for all communications between your frontend and backend.
* Regularly rotate your Shared Secret keys for enhanced security.
