sdk-lvconnect
TypeScript icon, indicating that this package has built-in type declarations

1.2.4 • Public • Published

LVConnect JavaScript SDK

This library aims to ease the usage of LVConnect in JavaScript environments (Browsers and NodeJS).

The library works in three modes:

  • public: This mode omits the appSecret, therefore you should definitively use this mode for web frontends where you can't hide credentials. The authorization workflow will return an access token which can be used immediately for any LVConnect route. But the user will have to login each time the token comes to expiration. This mode is very useful for a small app that doesn't have any backend server.
  • proxy: This mode is very similar to public mode but requires a backend server that will proxy calls to the token generation endpoint by adding the appSecret on the fly. This backend should have at least an endpoint for access token generation. It should proxy to https://lvconnect.link-value.fr/oauth/token. If this backend is in NodeJS, you can use this SDK to make the call easily.
  • private: This mode requires the appSecret and therefore must be used only on backend since it's the only place you can hide credentials.

Getting started

The most basic usage of the SDK is by adding the following code to your app entry point or in a script tag at the at the bottom of the body if not a web application. When using CommonJS or ES6 modules, you'll use the following code:

import LVConnectSDK from 'sdk-lvconnect';
 
const sdk = new LVConnectSDK({
  mode: 'private',
  appId: 'your_app_id',
  appSecret: 'your_app_secret',
});
 
sdk.mountLoginButton('.my-login-button-container');

If you want to use it directly in browser, you'll use this code:

<script type="text/javascript" src="sdk-lvconnect.min.js"></script>
<script type="text/javascript">
  var sdk = new window.LVConnectSDK({
    mode: 'public',
    appId: 'your_app_id',
    redirectUri: 'https://your.domain.com/callback'
  });
  
  sdk.mountLoginButton('.my-login-button-container');
</script> 

If you want the script loading to be deferred:

<script type="text/javascript" src="sdk-lvconnect.min.js" async></script>
<script type="text/javascript">
  window.LVConnectSDK = window.LVConnectSDK || {};
  window.LVConnectSDK.onload = function () {
    var sdk = new window.LVConnectSDK({
      mode: 'public',
      appId: 'your_app_id',
      redirectUri: 'https://your.domain.com/callback'
    });
    
    sdk.mountLoginButton('.my-login-button-container');
  }
</script> 

And in your authentication callback page (your redirect URI), you will have to add the following code:

LVConnectSDK.handleLoginDone();

This will tell the SDK that you're done processing authorization code and that the popup can close.

API

Public

constructor(config: object)

The LVConnectSDK constructor accepts the following configuration:

  • config: object
    • mode: string could be either public, proxy or private, required.
    • appId: string your app id from LVConnect, required in all modes.
    • appSecret?: string your app secret from LVConnect, required only in private mode.
    • redirectUri: string the URL to where the login popup redirect when authorization is done. Required in public and proxy mode.
    • tokenEndpoint?: string the endpoint used to fetch access tokens for authentication. Required in proxy mode.
    • shouldGetTokensOnLoginDone?: boolean a optional flag that tells if the SDK should do generate tokens from authorization code. If you have a PHP backend that handles the code on its side you must set this to false.

login(scopes?: string[]): Promise<string|void>

⚠️ This method only works on browser side ⚠️

This methods logs in the user by either using the refresh token or displaying the authorization tunnel. If refresh token is not present or is invalid, the authorization workflow will appear.

  • scopes?: string[] optional array of scopes for the token generation, used only if shouldGetTokensOnLoginDone is set to true.

The returned promise will resolve when the authorization tunnel is completed and the popup calls handleLoginDone. If shouldGetTokensOnLoginDone option is set to true, the SDK will also wait for tokens generation before resolving. If set to false, the promise will resolve with the authorization code so you can process it like you want. If user declines permission or closes the window or hits a 403 while fetching tokens, promise will reject.

logout(): this

⚠️ This method only works on browser side ⚠️

This methods clears the tokens from the localStorage, logging out the user.

isLoggedIn(): boolean

Returns true if user has non expired access token stored in the local storage.

api(route: string, options?: object): Promise<any>

Makes a call to LVConnect API (if url starts with a /) or to custom endpoint with access tokens in the Authorization header. When hitting a 403, the SDK will automatically try to regenerate tokens from refresh token. If token generation or retry fails the returned Promise will reject. Otherwise, if status code is not 403, the returned promise will resolve with fetch response object, so you'll have to call res.json() for response body.

getUserProfile(): Promise<LVConnectSDK.IUser>

Fetches the user profile from LVConnect server with authentication. Resolves with user profile or rejects if status code is not 200. It uses .api() under the hood so it will also have the auto-retry mechanism.

getAccessToken(): string

Returns the currently stored access token. If using the SDK in NodeJS environment, it will get the token from memory.

on(event: string, listener: Function): this

Listens to an event on the SDK.

  • event: string: the event to listen to. Throws if event is not handled.
  • listener: Function: A listener that will be called when event is dispatched.

The available events are:

  • loginSuccess: this event is emitted after call to .login() is successful. It's useful in case you let the SDK handle the login button click automatically.
  • loginError: dispatched when the login has failed.

off(event: string, listener: Function): this

Removes one or all listeners to an event on the SDK.

  • event: string: the event to remove the listener from. If no listener is given, all listeners will be removed.
  • listener: Function: The listener to remove.

setAccessToken(accessToken: string): this

Store the given access token. If using the SDK in NodeJS environment, it will store the token in memory.

fetchTokensFromAuthCode(code: string, scopes?: string[]): Promise<void>

Fetches tokens from the authorization code received after authorization tunnel.

mountLoginButton(element: string|HTMLElement, handleClick:boolean): Promise<HTMLIFrameElement>

⚠️ This method only works on browser side ⚠️

Mounts a LVConnect login button into the given html element.

  • element: string|HTMLElement: The element to append the button to. If string is passed, querySelector will be used to match the element, otherwise it will append the button to the given HTMLElement.
  • handleClick: boolean: Tells if the SDK should listen to button click (defaults to true). This is useful if you want to run additional checks before logging in.

Returns a promise that resolves with the mounted element when button iframe is loaded.

Static

LVConnectSDK.unmountLoginButton(element: string|HTMLElement): void

⚠️ This method only works on browser side ⚠️

This method unmounts the login button by removing listeners and destroying the iframe. If you're using the SDK within a React application for example, you should use this method within componentWillUnmount

  • element: string|HTMLElement: The iframe element mounted by the SDK or a string matching that element.

LVConnectSDK.handleLoginDone(): void

⚠️ This method only works on browser side in authorization popup ⚠️

This method signals the host window that the authorization tunnel has ended and will automatically fetch code or error from query parameters.

LVConnectSDK.getRefreshToken(): string

⚠️ This method only works on browser side ⚠️

Returns the currently stored refresh token.

LVConnectSDK.setRefreshToken(refreshToken: string): void

⚠️ This method only works on browser side ⚠️

Stores the given refresh token.

LVConnectSDK.overrideLVConnectEndpoint(endpoint: string): void

This method allows you to configure a custom endpoint for LVConnect. This is useful if you want to use the local/staging environment to run tests.

Readme

Keywords

none

Package Sidebar

Install

npm i sdk-lvconnect

Weekly Downloads

1

Version

1.2.4

License

MIT

Unpacked Size

52 kB

Total Files

7

Last publish

Collaborators

  • d34thwings