the code that runs the idp.global platform
Go to file
2024-12-11 01:19:54 +01:00
.gitea/workflows initial 2024-09-29 13:56:38 +02:00
.vscode initial 2024-09-29 13:56:38 +02:00
html initial 2024-09-29 13:56:38 +02:00
ts update 2024-12-11 01:19:54 +01:00
ts_idpclient feat(core): Refactored plugin and request handling to use idpInterfaces 2024-10-07 10:26:21 +02:00
ts_interfaces feat(core): Refactored plugin and request handling to use idpInterfaces 2024-10-07 10:26:21 +02:00
ts_web update 2024-12-11 01:19:54 +01:00
.dockerignore initial 2024-09-29 13:56:38 +02:00
.gitignore initial 2024-09-29 13:56:38 +02:00
changelog.md update 2024-12-11 01:19:54 +01:00
cli.child.ts initial 2024-09-29 13:56:38 +02:00
cli.js initial 2024-09-29 13:56:38 +02:00
cli.ts.js initial 2024-09-29 13:56:38 +02:00
Dockerfile initial 2024-09-29 13:56:38 +02:00
npmextra.json fix(core): Corrected typos and added missing keywords. 2024-10-01 13:49:18 +02:00
package.json 1.4.2 2024-10-12 23:41:24 +02:00
pnpm-lock.yaml fix(core): Bug fixes and UI enhancements 2024-10-07 15:14:44 +02:00
qenv.yml initial 2024-09-29 13:56:38 +02:00
readme.hints.md add readme 2024-09-29 14:02:10 +02:00
readme.md fix(core): Corrected typos and added missing keywords. 2024-10-01 13:49:18 +02:00
tsconfig.json initial 2024-09-29 13:56:38 +02:00

@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:

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:

// 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:

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.

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

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

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

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

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.

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 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.