eLabSDK.Oauth

Functions

NameDescription
getInstalledAddonID(rootVar)Retrieve the installed add-on ID for a given root variable.

This fetches the add-on information including its system ID based on the add-on's root
variable identifier. Returns a Promise that resolves with the add-on data. Use this to
get the add-on ID required for other OAuth operations. The add-on must be installed in
the system for this to succeed.
getAccessToken(addonID, [scope]) | Retrieve an OAuth2 access token for an add-on.

This fetches a valid access token for the specified add-on's OAuth2 configuration. If the
token exists and is valid, it's returned. If expired, it may be automatically refreshed.
Returns a Promise that resolves with the token or undefined if no token exists (user needs
to authenticate). The optional scope parameter can request specific permissions. Use this
before making authenticated requests to external services.
getAuthUri(addonID) | Get the OAuth2 authorization URL for an add-on.

This retrieves the OAuth2 authorization URL where users should be directed to authenticate
and authorize the add-on to access their external service account. The URL includes all
necessary OAuth parameters (client ID, redirect URI, state, scope). Open this URL in a
popup or new window to start the OAuth flow. After authentication, the user is redirected
back with an authorization code. Use this to initiate OAuth authentication.
setAccessAndRefreshToken(addonID, code, [scope]) | Exchange an OAuth2 authorization code for access and refresh tokens.

This completes the OAuth2 flow by exchanging the authorization code (received after user
authentication) for access and refresh tokens. The tokens are stored server-side for future
use. This is typically called in the OAuth callback handler after the user completes
authentication. The optional scope parameter should match the scope used in getAuthUri().
Returns a Promise that resolves when tokens are successfully stored.
handleTokenForRootVar(rootVar, [scope]) | Automatically handle OAuth callback for a specific add-on root variable.

This convenience method automatically detects and processes OAuth callbacks for the
specified add-on. It checks URL parameters for an authorization code and matching rootVar,
then automatically exchanges the code for tokens and closes the window. Place this in your
add-on's initialization code to handle OAuth redirects automatically. This eliminates the
need to manually parse URL parameters and call setAccessAndRefreshToken().

getInstalledAddonID(rootVar)

Retrieve the installed add-on ID for a given root variable.

This fetches the add-on information including its system ID based on the add-on's root
variable identifier. Returns a Promise that resolves with the add-on data. Use this to
get the add-on ID required for other OAuth operations. The add-on must be installed in
the system for this to succeed.

Kind: global function
Returns: Promise.<Object> - Promise that resolves with add-on information or rejects with error message

ParamTypeDescription
rootVarstringThe root variable identifier for the add-on

Example

// Get add-on ID for OAuth operations
eLabSDK.Oauth.getInstalledAddonID('MyExternalIntegration')
  .then(function(addon) {
    console.log('Add-on ID:', addon.sdkPluginID);
    console.log('Add-on name:', addon.name);
    
    // Use the ID for OAuth
    return eLabSDK.Oauth.getAccessToken(addon.sdkPluginID);
  })
  .then(function(token) {
    console.log('Access token:', token);
  })
  .catch(function(error) {
    console.error('Error:', error);
  });

Example

// Check if add-on is installed before using it
async function initializeIntegration() {
  try {
    var addon = await eLabSDK.Oauth.getInstalledAddonID('ExternalService');
    if (addon) {
      console.log('Integration add-on is installed');
      initializeOAuthFlow(addon.sdkPluginID);
    }
  } catch (error) {
    console.error('Add-on not found:', error);
    alert('Please install the External Service add-on first');
  }
}

getAccessToken(addonID, [scope])

Retrieve an OAuth2 access token for an add-on.

This fetches a valid access token for the specified add-on's OAuth2 configuration. If the
token exists and is valid, it's returned. If expired, it may be automatically refreshed.
Returns a Promise that resolves with the token or undefined if no token exists (user needs
to authenticate). The optional scope parameter can request specific permissions. Use this
before making authenticated requests to external services.

Kind: global function
Returns: Promise.<(string|undefined)> - Promise that resolves with access token string, or undefined if not authenticated

ParamTypeDescription
addonIDnumberThe numeric add-on ID (SDK plugin ID)
[scope]stringOptional OAuth scope to request specific permissions

Example

// Get access token and make API call
async function fetchExternalData(addonID) {
  try {
    var token = await eLabSDK.Oauth.getAccessToken(addonID);
    
    if (!token) {
      console.log('User not authenticated - starting OAuth flow');
      var authUrl = await eLabSDK.Oauth.getAuthUri(addonID);
      window.open(authUrl, '_blank');
      return;
    }
    
    console.log('Token retrieved:', token);
    
    // Use token for external API call
    var response = await fetch('https://api.external.com/data', {
      headers: {
        'Authorization': 'Bearer ' + token
      }
    });
    
    var data = await response.json();
    console.log('External data:', data);
  } catch (error) {
    console.error('Error:', error);
  }
}

Example

// Get token with specific scope
async function uploadToExternalService(addonID, data) {
  try {
    var token = await eLabSDK.Oauth.getAccessToken(addonID, 'upload.write');
    
    if (token) {
      await $.ajax({
        url: 'https://api.external.com/upload',
        method: 'POST',
        headers: {
          'Authorization': 'Bearer ' + token
        },
        data: JSON.stringify(data)
      });
      
      alert('Upload successful');
    }
  } catch (error) {
    alert('Upload failed: ' + error);
  }
}

Example

// Check token availability before operation
eLabSDK.Oauth.getAccessToken(123)
  .then(function(token) {
    if (token) {
      console.log('Authenticated - token available');
      performAuthenticatedOperation(token);
    } else {
      console.log('Not authenticated');
      showAuthenticationButton();
    }
  })
  .catch(function(error) {
    console.error('Token retrieval error:', error);
  });

getAuthUri(addonID)

Get the OAuth2 authorization URL for an add-on.

This retrieves the OAuth2 authorization URL where users should be directed to authenticate
and authorize the add-on to access their external service account. The URL includes all
necessary OAuth parameters (client ID, redirect URI, state, scope). Open this URL in a
popup or new window to start the OAuth flow. After authentication, the user is redirected
back with an authorization code. Use this to initiate OAuth authentication.

Kind: global function
Returns: Promise.<string> - Promise that resolves with the OAuth authorization URL

ParamTypeDescription
addonIDnumberThe numeric add-on ID (SDK plugin ID)

Example

// Start OAuth flow with popup window
async function authenticateWithExternalService(addonID) {
  try {
    var authUrl = await eLabSDK.Oauth.getAuthUri(addonID);
    console.log('Opening authentication URL:', authUrl);
    
    var popup = window.open(
      authUrl,
      'oauth_window',
      'width=600,height=700'
    );
    
    // Wait for popup to close (user completed auth)
    var checkPopup = setInterval(function() {
      if (popup.closed) {
        clearInterval(checkPopup);
        console.log('Authentication complete');
        
        // Check if we now have a token
        eLabSDK.Oauth.getAccessToken(addonID).then(function(token) {
          if (token) {
            alert('Successfully authenticated!');
          }
        });
      }
    }, 500);
  } catch (error) {
    console.error('Auth error:', error);
  }
}

Example

// Add authenticate button
eLabSDK.ready(function() {
  var addonID = 456;
  
  var authBtn = new eLabSDK.GUI.Button({
    label: 'Connect to External Service',
    icon: 'link',
    action: async function() {
      try {
        var authUrl = await eLabSDK.Oauth.getAuthUri(addonID);
        window.open(authUrl, '_blank');
      } catch (error) {
        alert('Failed to get authentication URL');
      }
    }
  });
});

Example

// Check token and prompt authentication if needed
async function ensureAuthenticated(addonID) {
  var token = await eLabSDK.Oauth.getAccessToken(addonID);
  
  if (!token) {
    console.log('No token - prompting authentication');
    var authUrl = await eLabSDK.Oauth.getAuthUri(addonID);
    
    if (confirm('You need to authenticate with the external service. Open authentication page?')) {
      window.open(authUrl, '_blank');
    }
  } else {
    console.log('Already authenticated');
    return token;
  }
}

setAccessAndRefreshToken(addonID, code, [scope])

Exchange an OAuth2 authorization code for access and refresh tokens.

This completes the OAuth2 flow by exchanging the authorization code (received after user
authentication) for access and refresh tokens. The tokens are stored server-side for future
use. This is typically called in the OAuth callback handler after the user completes
authentication. The optional scope parameter should match the scope used in getAuthUri().
Returns a Promise that resolves when tokens are successfully stored.

Kind: global function
Returns: Promise.<Object> - Promise that resolves with success response or rejects with error

ParamTypeDescription
addonIDnumberThe numeric add-on ID (SDK plugin ID)
codestringThe authorization code received from OAuth provider
[scope]stringOptional OAuth scope that was requested

Example

// Handle OAuth callback in popup window
eLabSDK.ready(function() {
  var urlParams = new URLSearchParams(window.location.search);
  var code = urlParams.get('code');
  var addonID = urlParams.get('sdkPluginID');
  
  if (code && addonID) {
    eLabSDK.Oauth.setAccessAndRefreshToken(addonID, code)
      .then(function(response) {
        console.log('Tokens saved successfully');
        alert('Authentication complete!');
        window.close(); // Close OAuth popup
      })
      .catch(function(error) {
        console.error('Token exchange failed:', error);
        alert('Authentication failed: ' + error);
      });
  }
});

Example

// Complete OAuth flow with scope
async function completeOAuthFlow() {
  var urlParams = new URLSearchParams(window.location.search);
  var code = urlParams.get('code');
  var addonID = parseInt(urlParams.get('sdkPluginID'));
  var scope = 'read.write';
  
  if (code && addonID) {
    try {
      await eLabSDK.Oauth.setAccessAndRefreshToken(addonID, code, scope);
      console.log('OAuth tokens stored successfully');
      
      // Verify token was saved
      var token = await eLabSDK.Oauth.getAccessToken(addonID, scope);
      if (token) {
        console.log('Token verified - authentication complete');
        window.opener.postMessage({ authenticated: true }, '*');
        window.close();
      }
    } catch (error) {
      console.error('OAuth error:', error);
    }
  }
}

handleTokenForRootVar(rootVar, [scope])

Automatically handle OAuth callback for a specific add-on root variable.

This convenience method automatically detects and processes OAuth callbacks for the
specified add-on. It checks URL parameters for an authorization code and matching rootVar,
then automatically exchanges the code for tokens and closes the window. Place this in your
add-on's initialization code to handle OAuth redirects automatically. This eliminates the
need to manually parse URL parameters and call setAccessAndRefreshToken().

Kind: global function

ParamTypeDescription
rootVarstringThe root variable identifier for your add-on
[scope]stringOptional OAuth scope that was requested during authentication

Example

// Auto-handle OAuth callbacks in add-on
(function(context) {
  var MY_ADDON_ROOT = 'MyExternalIntegration';
  
  // Initialize add-on
  context.init = function() {
    console.log('Initializing add-on');
    
    // Automatically handle OAuth callback if present
    eLabSDK.Oauth.handleTokenForRootVar(MY_ADDON_ROOT);
    
    // Rest of add-on initialization...
  };
  
  context.init();
})(window.MyAddon = {});

Example

// Handle OAuth with scope
(function(context) {
  var DROPBOX_ADDON = 'DropboxIntegration';
  
  eLabSDK.ready(function() {
    // Handle OAuth callback with file access scope
    eLabSDK.Oauth.handleTokenForRootVar(DROPBOX_ADDON, 'files.content.read');
    
    // If not callback, proceed with normal initialization
    initializeDropboxFeatures();
  });
})(window.DropboxAddon = {});

Example

// Complete OAuth flow in add-on
var MY_ADDON = {};
(function(context) {
  var ROOT_VAR = 'GoogleDriveIntegration';
  var SCOPE = 'drive.readonly';
  
  context.initialize = function() {
    // Step 1: Handle OAuth callback if present
    eLabSDK.Oauth.handleTokenForRootVar(ROOT_VAR, SCOPE);
    
    // Step 2: Check if authenticated
    eLabSDK.Oauth.getInstalledAddonID(ROOT_VAR).then(function(addon) {
      return eLabSDK.Oauth.getAccessToken(addon.sdkPluginID, SCOPE);
    }).then(function(token) {
      if (token) {
        console.log('Authenticated - initializing features');
        context.startIntegration(token);
      } else {
        console.log('Not authenticated - showing connect button');
        context.showConnectButton();
      }
    });
  };
  
  context.initialize();
})(MY_ADDON);

© 2023 eLabNext