> For the complete documentation index, see [llms.txt](https://docs.eximee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.eximee.com/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/uslugi-platformy/pobranie-kontekstu-uzytkownika.md).

# Kontekst zalogowanego użytkownika

API pozwala na pobranie kontekstu użytkownika aktualnie wypełniającego formularz. Kontekst opisuje użytkowników zalogowanych na formularzu, w aplikacji Dashboard czy aplikacjach klienta zintegrowanych z systemem Eximee oraz informacje o sesji użytkownika niezalogowanego.

## User API (api.user.v1)

Uniwersalny interfejs, który precyzyjnie opisuje użytkowników we wszystkich kanałach dostępu (zalogowanych przez Web, przez aplikację Dashboard, w systemach zintegrowanych oraz użytkowników niezalogowanych).

{% hint style="info" %}
**Dostępność:** Funkcjonalność dostępna od wersji platformy **4.737.0**. Działa na wnioskach uruchamianych w aplikacji WebForms oraz w systemie Eximee Dashboard.
{% endhint %}

### Struktura tożsamości użytkownika (UserIdentity)

{% hint style="warning" %}
**Zależność od wdrożenia:** Struktura oraz zawartość obiektu zwracanego przez tę metodę ściśle zależy od specyfiki wdrożenia i implementacji mechanizmów uwierzytelniania u konkretnego klienta. W zależności od konfiguracji platformy i dostawcy tożsamości (IdP), nie wszystkie poniższe pola muszą być wypełnione lub w ogóle dostępne.
{% endhint %}

Metoda `api.user.v1.getIdentity()` zwraca obiekt reprezentujący aktualną tożsamość. Poniższa tabela opisuje jego domyślne, najczęściej spotykane właściwości:

| Pole        | Typ            | Opis                                                                                                                          |
| ----------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `userId`    | String         | Unikalny identyfikator użytkownika.                                                                                           |
| `username`  | String         | Nazwa użytkownika przeznaczona do wyświetlania.                                                                               |
| `roles`     | Array\<String> | Lista ról przypisanych do użytkownika w postaci tablicy ciągów znaków (np. `["EXIMEE_BROKER", "USER"]`).                      |
| `firstName` | String         | Imię użytkownika.                                                                                                             |
| `lastName`  | String         | Nazwisko użytkownika.                                                                                                         |
| `type`      | String         | Typ uwierzytelnienia. Zwraca jedną z wartości: `'client'` (klient), `'employee'` (pracownik) lub `'otp'` (jednorazowe hasło). |
| `system`    | String         | Identyfikator systemu dostarczającego uwierzytelnienie.                                                                       |

***

```typescript
interface User {
    v1: {
        getIdentity(): UserIdentity
    }
}


interface UserIdentity {
    userId(): string,
    username(): string,
    roles(): string[],
    firstName(): string,
    lastName(): string,
    type(): 'client'|'employee'|'otp',
    system(): string
}
```

{% hint style="info" %}
Pola: username, firstName, lastName, roles są zależne od sposobu integracji uwierzytelniania w ramach wdrożenia.

Najczęściej pola są dostępne jedynie dla uwierzytelnienia typu Pracownik (employee) w systemach Dashboard lub systemach Klienta zintegrowanych z Eximee.
{% endhint %}

{% hint style="warning" %}
Od wersji platformy 4.1092.0 kontekst rozdziela identyfikator użytkownika od jego nazwy:

* `userId` to identyfikator użytkownika, pobierany z claimu wskazanego w konfiguracji wdrożenia. Używaj go wszędzie, gdzie porównujesz lub zapisujesz użytkownika.
* `username` to nazwa użytkownika przeznaczona do wyświetlania. Nie jest identyfikatorem — może się zmieniać i nie musi być unikalna.
  {% endhint %}

### Pobranie danych użytkownika

```javascript
function callService(context) {
    const identity = api.user.v1.getIdentity();
    Logger.info("Get user identity: {}", identity)
    return [{
        'userId': identity.userId,
        'username': identity.username,
        'firstName': identity.firstName,
        'lastName': identity.lastName,
        'type': identity.type,
        'system': identity.system,
    }];
} 
```

### Przykład użycia User API z walidacją ról

Poniższy skrypt pobiera tożsamość użytkownika, sprawdza czy posiada on odpowiednią rolę do wykonania akcji, a w przypadku jej braku – rzuca wyjątek biznesowy i przerywa działanie.

```javascript
function callService(context) {
    const AVAILABLE_ROLES = ["EXIMEE_BROKER_MORTGAGE_DASHBOARD"];
    let identity = api.user.v1.getIdentity();
    let roles = identity.roles;
    
    Logger.info("Pobrano tożsamość użytkownika. Role: {}", roles);

    // Weryfikacja czy użytkownik posiada jakiekolwiek role
    if (!roles) {
        throwBusinessError(context, "error_page_default-*", "Brak uprawnień do uruchomienia procesu.");
    }
    
    // Sprawdzenie, czy na liście ról użytkownika znajduje się wymagana rola
    let isAvailableRole = roles.some(role => AVAILABLE_ROLES.includes(role.toUpperCase()));

    if (!isAvailableRole) {
        throwBusinessError(context, "error_page_default-*", "Brak odpowiedniej roli do uruchomienia procesu.");
    }
    
    return [{'userId': identity.userId, 'status': 'Zautoryzowano'}];

    /**
     * Funkcja pomocnicza generująca stronę błędu biznesowego
     */
    function throwBusinessError(ctx, textcontentName, errorDescription) {
        const builder = ctx.getErrorPageDefinitionBuilder();
        builder.bodyTextContent(textcontentName);
        builder.msg(errorDescription);
        ctx.throwBusinessException(builder);
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.eximee.com/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/uslugi-platformy/pobranie-kontekstu-uzytkownika.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
