# @idp.global/idp.global

An identity provider software managing user authentications, registrations, and sessions.

## Install

To install `@idp.global/idp.global`, you can run the following command in your terminal:

```bash
npm install @idp.global/idp.global
```

This will download and install the necessary dependencies along with the module to your project.

## Usage

To use `@idp.global/idp.global`, one needs to understand its key components and functionalities. Below, we'll guide you through setting up, logging in, registering, and managing users and organizations within an IDP (Identity Provider) environment using this package.

### Setting Up the Environment

First, let's set up the environment:

```typescript
// Import the necessary modules
import * as serviceworker from '@api.global/typedserver/web_serviceworker_client';
import * as domtools from '@design.estate/dees-domtools';
import { html, render } from '@design.estate/dees-element';
import { IdpWelcome } from './elements/idp-welcome.js';

// Define an asynchronous run function
const run = async () => {
  // Set up DOM tools
  const domtoolsInstance = await domtools.DomTools.setupDomTools();
  domtools.elementBasic.setup();

  // Configure website information
  domtoolsInstance.setWebsiteInfo({
    metaObject: {
      title: 'idp.global',
      description: 'the code that runs idp.global',
      canonicalDomain: 'https://idp.global',
      ldCompany: {
        name: 'Task Venture Capital GmbH',
        status: 'active',
        contact: {
          address: {
            name: 'Task Venture Capital GmbH',
            city: 'Grasberg',
            country: 'Germany',
            houseNumber: '24',
            postalCode: '28879',
            streetName: 'Eickedorfer Vorweide',
          },
        }
      },
    },
  });

  // Set up the service worker
  const serviceWorker = await serviceworker.getServiceworkerClient();

  // Render the main template
  const mainTemplate = html`
    <style>
      body {
        margin: 0px;
        --background-accent: #303f9f;
      }
    </style>
    <idp-welcome></idp-welcome>
  `;

  render(mainTemplate, document.body);
};

// Run the function
run();
```

### Using the IDP Client

The IDP Client is essential to communicate with the IDP server. Below is a sample of how to set up and use the IDP client:

```typescript
import { IdpState } from './idp.state.js';
import * as plugins from './plugins.js';

// Instantiate IdpState which provides a singleton instance
export class IdpDemo {
  private idpState = IdpState.getSingletonInstance();

  // Function to initialize and use IdpClient
  public async demo() {
    // Fetch the client instance
    const { idpClient } = this.idpState;
    // Handler for login
    const handleLogin = async () => {
      const response = await idpClient.requests.loginWithUserNameAndPassword.fire({
        username: 'user@example.com',
        password: 'password123',
      });
      if (response.refreshToken) {
        await idpClient.storeJwt(response.jwt);
        console.log("Logged in successfully, JWT stored.");
      } else {
        console.log("Login failed.");
      }
    };
    // Execute login handler
    await handleLogin();
  }
}

// Instantiate and run demo
const demo = new IdpDemo();
demo.demo();
```

### Managing User Authentication

Several functionalities are available for managing user authentication. These include registering, logging in, and refreshing JWTs.

#### Registration Process

The registration process is typically more involved and requires steps such as email validation, setting user-specific data, and verifying OTPs for additional security.

```typescript
import * as plugins from './plugins.js';
import { IdpState } from './idp.state.js';

// Registration stepper element
export class IdpRegistrationStepper extends plugins.DeesElement {
  private idpState = IdpState.getSingletonInstance();

  public async firstUpdated() {
    await this.domtoolsPromise;
    this.domtools.router.on(`/finishregistration`, async (routeArg) => {
      const validationToken = routeArg.queryParams.validationtoken;
      if (!validationToken) {
        this.renderErrorMessage("Validation token not found.");
        return;
      }
      const emailResponse = await this.validateEmail(validationToken);
      if (!emailResponse.email) {
        this.renderErrorMessage("Invalid validation token.");
        return;
      }
      await this.renderRegistrationForm(emailResponse.email);
    });
  }

  private async validateEmail(token: string) {
    return await this.idpState.idpClient.requests.afterRegistrationEmailClicked.fire({
      token
    });
  }

  private async renderRegistrationForm(email: string) {
    const template = plugins.html`
    <dees-form @formData="${async (event) => await this.handleFormSubmission(event, email)}">
      <dees-input-text key="First Name" label="First Name" required></dees-input-text>
      <dees-input-text key="Last Name" label="Last Name" required></dees-input-text>
      <dees-form-submit>Next</dees-form-submit>
    </dees-form>
    `;
    this.render(template, this.shadowRoot);
  }

  private async handleFormSubmission(event: FormDataEvent, email: string) {
    const formData = (event.target as any).getFormData();
    await this.idpState.idpClient.requests.setData.fire({
      token: this.storedData.validationTokenUrlParam,
      userData: {
        email,
        first_name: formData.FirstName,
        last_name: formData.LastName,
      },
    });
    // Proceed to the next steps as per the registration flow
  }

  private renderErrorMessage(message: string) {
    const template = plugins.html`<div>Error: ${message}</div>`;
    this.render(template, this.shadowRoot);
  }
}
```

### User Management

Managing user data including roles, organizations, and billing plans is essential in any identity provider software.

#### Getting User Data

```typescript
import * as plugins from './plugins.js';

const fetchUserData = async (jwt: string) => {
  const user = await plugins.typedrequest.TypedRequest<plugins.lointReception.request.IReq_GetUserData>(
    `/getUserData`, 'POST').fire({jwt});
  console.log(user);
};

fetchUserData('<JWT_TOKEN_HERE>');
```

#### Creating an Organization

```typescript
import { IdpState } from './idp.state.js';

export class OrganizationManager {
  private idpState = IdpState.getSingletonInstance();

  public async createOrganization(name: string, slug: string, jwt: string) {
    const response = await this.idpState.idpClient.requests.createOrganization.fire({
      jwt: jwt,
      organizationName: name,
      organizationSlug: slug,
      action: 'manifest',
    });
    if (response.resultingOrganization) {
      console.log(`Organization ${name} created successfully.`);
    } else {
      console.log(`Organization creation failed.`);
    }
  }
}

// Usage
const organizationManager = new OrganizationManager();
organizationManager.createOrganization('Dev Org', 'dev-org', '<JWT_TOKEN_HERE>');
```

### Managing JWTs

The `@idp.global/idp.global` package involves managing JSON Web Tokens (JWTs) for session handling and security.

#### Refreshing JWTs

```typescript
import { IdpClient } from './idp.client.js';

export const refreshJwt = async (client: IdpClient) => {
  const currentJwt = await client.getJwt();
  if (!currentJwt) return null;
  const response = await client.requests.refreshJwt.fire({
    refreshToken: currentJwt.data.refreshToken
  });
  if (response.jwt) {
    await client.storeJwt(response.jwt);
    console.log("JWT refreshed and stored.");
    return response.jwt;
  } else {
    console.log("JWT refresh failed.");
    return null;
  }
};

// Usage
const idpClient = new IdpClient('https://reception.lossless.one/typedrequest');
refreshJwt(idpClient);
```

### Handling Authentication Tokens

Handling tokens (JWTs, refresh tokens, transfer tokens) securely is crucial for maintaining session integrity.

#### Exchanging Refresh Token for Transfer Token

```typescript
import { IdpClient } from './idp.client.js';

const getTransferToken = async (client: IdpClient) => {
  const refreshToken = await client.getJwt().data.refreshToken;
  const response = await client.requests.obtainOneTimeToken.fire({
    refreshToken
  });
  if(response.transferToken) {
    console.log("Obtained Transfer Token: ", response.transferToken);
    return response.transferToken;
  } else {
    console.log("Failed to obtain Transfer Token.");
    return null;
  }
};

// Usage
const idpClient = new IdpClient('https://reception.lossless.one/typedrequest');
getTransferToken(idpClient);
```

This comprehensive guide should help you understand the detailed setup and usage of the `@idp.global/idp.global` module effectively.

## License and Legal Information

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. 

**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

### Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

### Company Information

Task Venture Capital GmbH  
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
