JavaScript Widget

An easy to add JavaScript library that helps to integrate the Almefy login into any website. You can use either data attributes or initialize and control the widget with vanilla JavaScript.

Using Data Attributes

Add the following few lines to your HTML frontend to show the Almefy image used for authentication.

<!-- Place this HTML code wherever the Almefy image should appear -->
<div data-almefy-auth
     data-almefy-key="5bbf4923faf099a3515a40d9b0e6e6e32c890ef6cd7a8a120657c2f49d2341fe"
     data-almefy-auth-url="/path/to/auth-controller"></div>

<!-- Load the JavaScript library -->
<script defer src="https://cdn.almefy.com/js/almefy-1.0.0.js"
        integrity="sha384-9cWXAg8MurIKKZOnt0x5QIm7o6HzOwVT9r03rLTSwkjti7f4SEmJAM1CZPBJkZ1X"
        crossorigin="anonymous"></script>

Available Data Attributes

ParameterTypeDescription
data-almefy-authEmptyUse this element to show authentication image
data-almefy-keyStringAlmefy API Key
data-almefy-langStringThe language to use, e.g. en (Browser setting by default)
data-almefy-auth-urlStringAuthentication controller to receive the Almefy auth token
data-almefy-auth-headerStringAuthorization header to use. Default is 'X-Almefy-Auth'
data-almefy-auto-startBooleanShow the auth image immediately. True by default
data-almefy-styleStringCan be set to pure to show only the auth image
data-almefy-apiStringAPI to connect to, https://api.almefy.com by default

Note: Bold parameters are mandatory, Italic are optional

Using Inline JavaScript

Add the following few lines to your HTML frontend to show the Almefy image used for authentication.

<!-- Place this HTML code wherever the Almefy image should appear -->
<div id="almefy"></div>

<!-- Load the JavaScript library asynchronously (non-blocking) and configure it -->
<script defer id="almefy-js" src="https://cdn.almefy.com/js/almefy-1.0.0.js"
        integrity="sha384-9cWXAg8MurIKKZOnt0x5QIm7o6HzOwVT9r03rLTSwkjti7f4SEmJAM1CZPBJkZ1X"
        crossorigin="anonymous"></script>

<script>
    // Wait until the script has been loaded
    document.getElementById("almefy-js").addEventListener("load", function() {
        var almefy = new Almefy.Auth({
            element: "almefy", // The id of element to use for the Almefy auth image
            key:  "5bbf4923faf099a3515a40d9b0e6e6e32c890ef6cd7a8a120657c2f49d2341fe", // API key
            authUrl: "/path/to/auth-controller", // Your authentication controller
            autoStart: false // Don't start the widget automatically
        });

        // Do something ...

        // Start the Almefy login
        almefy.start();
    });
</script>

Configuration Options

ParameterTypeDescription
keyStringAlmefy API Key
authUrlStringAuthentication controller to receive the Almefy auth token
langStringThe language to use, e.g. en (Browser setting by default)
elementString | ElementUse this element to show authentication image, 'almefy-login' by default
authHeaderStringAuthorization header to use. Default is 'X-Almefy-Auth'
autoStartBooleanShow the auth image immediately. True by default
styleStringCan be set to pure to show only the auth image
apiStringAPI to connect to, https://api.almefy.com by default

Note: Bold parameters are mandatory, Italic are optional

Available Events

The Almefy JavaScript widget populates many events that can be used to extend the functionality and implement custom logic, like redirecting users to a registration page, or informing them to connect their account with the Almefy App first. The following events are available:

EventDescription
almefy.auth.successAlmefy successfully authenticated a user
almefy.auth.client-successYour auth controller successfully authenticated a user
almefy.auth.client-errorYour auth controller returned an error
almefy.auth.challenge-errorInvalid parameters. Check browser console for more
almefy.auth.entity-not-foundAlmefy API key is unknown or invalid
almefy.auth.entity-lockedAlmefy API key was locked
almefy.auth.identity-not-foundAlmefy App is not linked with any account yet
almefy.auth.identity-lockedAlmefy App or the link to an account is locked
almefy.auth.challenge-expiredLogin has expired
almefy.auth.network-errorBrowser has issues to connect to the Almefy API
almefy.auth.server-errorAn issue on Almefy API

Handle HTML Events

You can handle all events using the addEventListener() on the appropriate HTML element:

document.getElementById("almefy-login").addEventListener("almefy.auth.client-success", function(event) {
  console.log("Successfully authenticated.");
  // You can access additional data through the 'event.detail' property 
});

Handle Widget Events

If you need advanced control, just use the widget directly by overwriting the provided onEvent(event, data) handler:

// Get widget instance by element id
var almefyInstance = Almefy.Auth.getInstance("almefy-login");

// Only attach the handler if an instance is available on the current page
if (almefyInstance) {
  almefyInstance.onEvent = function (event, data) {
    
    // Handle different events using one event handler
    if (event === "almefy.auth.client-success") {
      console.log("Successfully authenticated.");
      // You can access additional data through the 'data' variable
    }    
  };
}

Suppress Widget Messages

The Almefy widget will always show a message related to the error that occurred. You can suppress it by returning false from the onEvent(event, data) handler:

almefyInstance.onEvent = function(event, data) {
  
  if (event === "almefy.auth.identity-not-found") {
    
    return false;
  }
  
}




 



Notice: You can only suppress the message using the onEvent(event, data) handler. The standard HTML addEventListener(event, data) does not support this feature.

Additional Data

All events have access to additional data through the event.detail property (when using addEventListener(event)) or via the data variable when using the onEvent(event, data) handler. This object provides the following properties:

{
  code: integer,            // The HTTP status code, 0 in any other case
  message: string,          // A message describing the response status
  response: object | string // Any response data as object if it's a json, otherwise as string
}

Customize Authentication

The almefy.auth.success event will return the response from Almefy API inside the data.response property (usually the JWT to handle inside your auth controller), while the almefy.auth.client-success event will return the response from your auth controller inside data.response property. This is handy if you want to customize the authentication flow or attach further logic.

If you want e.g. to handle authentication by yourself, just omit the data-almefy-auth-url attribute and the authUrl setting, and handle the authentication inside the onEvent() handler:

almefyInstance.onEvent = function (event, data) {
  
  // Handle authentication with data from Almefy API
  if (event === "almefy.auth.success") {
    fetch("/account/login", {
      method: "POST",
      body: JSON.stringify({
        jwt: data.token,
        csrf: "{CSRF_TOKEN}" // Additional parameter as example
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    }).then(function(data) {
      // Success
    }).catch(function(error) {
      // Error
    });
  }
  
}

Handle Errors

In case the Almefy widget populates any error event, the provided data variable will hold some information on what went wrong. This JavaScript object has the following properties:

{
  code: integer,            // The HTTP status code, 0 in any other case
  message: string,          // A message describing the issue
  response: object | string // Any response data as object if it's a json, otherwise as string
}

Use Case: Almefy App not connected yet

One issue that might happen when you enable Almefy on your website is the situation, when a User tries to scan the login with the Almefy App, but either hasn't connected any account yet, or doesn't even have one.

The App itself will show a message about the missing link, but it is highly recommended to provide some information to the User about what to do next:

almefyInstance.onEvent = function (event, data) {
  
  // The user has not linked any accounts with the App yet
  if (event === "almefy.auth.identity-not-found") {
    
    // Show a message to the user where to connect his existing account with the Almefy App,
    // or provide a link to the registration page in case he hasn't created one yet.

    // Uncomment the return statement if you want to surppress the message inside Almefy widget
    // return false;
  }
  
}

Use Case: Local account disabled

Another use-case is to handle errors related to an already connected account. In case the account is for any reason suspended in your local User database, you can listen for the almefy.auth.client-error event in the onEvent handler.

The data.response property will provide access to the response from your auth controller,

almefyInstance.onEvent = function (event, data) {
  
  // The auth controller returned an error
  if (event === "almefy.auth.client-error") {

    // Use the data.response property to access anything you return from your auth controller
    
    // Uncomment the return statement if you want to surppress the message inside Almefy widget
    // return false;
  }
  
}