Options
All
  • Public
  • Public/Protected
  • All
Menu

Namespace authService

Helper functions for handling user authentication and authorisation.

NOTE: init() must be called before using some of the functions in this service.

import { authService } from '@oneblink/apps'

Index

Type aliases

LoginAttemptResponse: { mfaCodeCallback?: any; resetPasswordCallback?: any }

Type declaration

Functions

  • changePassword(existingPassword: string, newPassword: string): Promise<void>
  • Allow the currently logged in user to change their password by passing their existing password and a new password.

    Example

    const currentPassword = 'P@$5w0rd'
    const newPassword = 'P@$5w0rD'
    await authService.changePassword(currentPassword, newPassword)

    Parameters

    • existingPassword: string
    • newPassword: string

    Returns Promise<void>

  • checkIsMfaEnabled(): Promise<boolean>
  • Check if MFA is enabled for this current user.

    Example

    const isMfaEnabled = await authService.checkIsMfaEnabled()
    if (isMfaEnabled) {
    // Allow disabling MFA
    } else {
    // Allow enabling MFA
    }

    Returns Promise<boolean>

  • disableMfa(): Promise<void>
  • forgotPassword(username: string, formsAppId?: number): Promise<(code: string, password: string) => Promise<void>>
  • Allow a user to start the forgot password process. The user will be emailed a temporary code that must be passed with a new password to the function returned.

    Example

    const username = 'user@email.io'
    const finishForgotPassword = await authService.forgotPassword(username)

    // Prompt the user to enter the code and a new password
    const code = prompt(
    'You have been emailed a verification code, please enter it here.',
    )
    const newPassword = prompt('Please enter a new password to continue.')
    await finishForgotPassword(code, newPassword)

    Parameters

    • username: string
    • Optional formsAppId: number

      Used to give the resulting email sent to the user associated forms app branding and sending address

    Returns Promise<(code: string, password: string) => Promise<void>>

  • getCurrentFormsAppUser(formsAppId: number, abortSignal?: AbortSignal): Promise<{ formsAppId: number; groups: string[]; userProfile?: UserProfile } | undefined>
  • Get the current user's App User details for a OneBlink Forms App. Returns undefined if the current user is not logged in.

    Example

    const formsAppId = 1
    const formsAppUserDetails =
    await authService.getCurrentFormsAppUser(formsAppId)
    if (!formsAppUserDetails) {
    // handle unauthorised user
    }

    Parameters

    • formsAppId: number
    • Optional abortSignal: AbortSignal

    Returns Promise<{ formsAppId: number; groups: string[]; userProfile?: UserProfile } | undefined>

  • getFormsKeyId(): string | void
  • Can be used to extract the keyId from the Forms Key token passed to setFormsKeyToken(). Will be undefined if the token has not been set yet.

    Example

    const keyId = authService.getFormsKeyId()
    if (keyId) {
    // Use keyId here...
    }

    Returns string | void

  • getIdToken(): Promise<undefined | string>
  • Get the Id Token used to make requests to the OneBlink API. This will return undefined if the current user is not logged in.

    Example

    const idToken = await authService.getIdToken()
    if (idToken) {
    await fetch(url, {
    headers: {
    Authorization: `Bearer ${idToken}`,
    },
    })
    } else {
    // Handle user not being logged in
    }

    Returns Promise<undefined | string>

  • getUserFriendlyName(): string | undefined
  • A friendly string that represents the current user. Uses first name, last name, full name and username. This will return null the current user is not logged in.

    Example

    const name = authService.getUserFriendlyName()
    if (name) {
    // Display current user's name
    }

    Returns string | undefined

  • Get current users profile based on there Id Token payload. This will return null if the the current user is not logged in.

    Example

    const profile = authService.getUserProfile()
    if (profile) {
    // Use profile here
    }

    Returns UserProfile | null

  • getUserToken(): undefined | null | string
  • Can be used to retrieve the userToken passed to setUserToken(). Will be undefined if the token has not been set yet.

    Example

    const userToken = authService.getUserToken()
    if (userToken) {
    // Use token here...
    }

    Returns undefined | null | string

  • handleAuthentication(): Promise<string>
  • This function should be called when the user is redirected back to your app after a login attempt. It will use the query string add the redirect URL to create a session for the current user. It will return a URL as a string that should be redirected to within your app.

    Example

    try {
    const continueTo = await authService.handleAuthentication()
    // Redirect the user back to where they were before attempting to login
    window.location.href = continueTo
    } catch (error) {
    // handle failed login attempts here.
    }

    Returns Promise<string>

  • init(options: { oAuthClientId: string }): void
  • Initialize the service with required configuration. This must be done before using before some of the function in this service.

    Example

    authService.init({
    oAuthClientId: 'YOUR_OAUTH_CLIENT_ID',
    })

    Parameters

    • options: { oAuthClientId: string }
      • oAuthClientId: string

    Returns void

  • isAdministrator(formsAppId: number, abortSignal: AbortSignal): Promise<boolean>
  • Determine if the current user is a OneBlink App User administrator for a OneBlink Forms App. Returns false if the current user is not.

    Example

    const formsAppId = 1
    const isAdministrator = await authService.isAdministrator(formsAppId)
    if (isAdministrator) {
    // handle administator user
    }

    Parameters

    • formsAppId: number
    • abortSignal: AbortSignal

    Returns Promise<boolean>

  • isAuthorised(formsAppId: number): Promise<boolean>
  • Determine if the current user is a OneBlink App User for a OneBlink Forms App. Returns false if the current user is not logged in.

    Example

    const formsAppId = 1
    const isAuthorised = await authService.isAuthorised(formsAppId)
    if (!isAuthorised) {
    // handle unauthorised user
    }

    Parameters

    • formsAppId: number

    Returns Promise<boolean>

  • isLoggedIn(): boolean
  • Check if the user is currently logged in

    Example

    const isLoggedIn = authService.isLoggedIn()
    // handle user being logged in or not

    Returns boolean

  • loginHostedUI(identityProviderName?: string): Promise<void>
  • Redirect the user to the login screen. Passing an identityProvider is optionally, it will allow users to skip the login page and be directed straight to that providers login page

    Example

    // OPtionally pass a
    const identityProvider = 'Google'
    await authService.loginHostedUI(identityProvider)
    // User will be redirected to login page or promise will resolve

    Parameters

    • Optional identityProviderName: string

    Returns Promise<void>

  • Create a session for a user by entering a username and password. If the user requires a password reset, the "resetPasswordCallback" property will be returned. This function should be called with the new password once entered by the user. If the user requires an MFA token, the "mfaCodeCallback" property will be returned. This function should be called with a one-time token generated from an authenticator app. The functions returned are recursive and the result from each of them is the same result from the loginUsernamePassword() function. Each time the response includes a callback, you will need to begin the process again until all callbacks are handled.

    Example

    async function handleLoginAttemptResponse({
    resetPasswordCallback,
    mfaCodeCallback,
    }) {
    // "resetPasswordCallback" will be undefined if a password reset was not required.
    if (resetPasswordCallback) {
    // Prompt the user to enter a new password
    const newPassword = prompt(
    'The password you entered was only temporary, and must be reset for security purposes. Please enter your new password below to continue.',
    )
    const resetPasswordResponse =
    await resetPasswordCallback(newPassword)
    return await handleLoginAttemptResponse(resetPasswordResponse)
    }

    // "mfaCodeCallback" will be undefined if MFA is not setup.
    if (mfaCodeCallback) {
    // Prompt the user to enter an MFA code
    const code = prompt(
    'Please enter a one-time code from your MFA app.',
    )
    const mfaCodeResponse = await mfaCodeCallback(code)
    return await handleLoginAttemptResponse(mfaCodeResponse)
    }
    }

    const username = 'user@email.io'
    const password = 'P@$5w0rd'

    const loginAttemptResponse = await authService.loginUsernamePassword(
    username,
    password,
    )

    await handleLoginAttemptResponse(loginAttemptResponse)

    Parameters

    • username: string
    • password: string

    Returns Promise<LoginAttemptResponse>

  • logout(): Promise<void>
  • Log the current user out and remove an data stored locally by the user e.g. drafts.

    Example

    await authService.logout()
    

    Returns Promise<void>

  • logoutHostedUI(): void
  • Redirect the user to the logout screen to clear the users session on the hosted login page. User will then be redirected to /logout. After being redirected back to the application, the logout() function should be called to clear the session data from browser storage.

    Example

    authService.logoutHostedUI()
    

    Returns void

  • registerAuthListener(listener: () => unknown): () => void
  • Register a listener function that will be call when authentication tokens are updated or removed.

    Example

    const listener = async () => {
    // Check if the user is logged in still
    const isLoggedIn = authService.isLoggedIn()
    }
    const deregister = await authService.registerAuthListener(listener)

    // When no longer needed, remember to deregister the listener
    deregister()

    Parameters

    • listener: () => unknown
        • (): unknown
        • Returns unknown

    Returns () => void

      • (): void
      • Register a listener function that will be call when authentication tokens are updated or removed.

        Example

        const listener = async () => {
        // Check if the user is logged in still
        const isLoggedIn = authService.isLoggedIn()
        }
        const deregister = await authService.registerAuthListener(listener)

        // When no longer needed, remember to deregister the listener
        deregister()

        Returns void

  • requestAccess(formsAppId: number): Promise<void>
  • If the current user is not a Forms App User, this function will send a request on behalf of the current user to the OneBlink Forms App administrators to request access.

    Example

    const formsAppId = 1
    await authService.requestAccess(formsAppId)
    // Display a message to user indicating a request has been sent to the application administrators

    Parameters

    • formsAppId: number

    Returns Promise<void>

  • setFormsKeyToken(jwtToken: undefined | null | string): void
  • Set the Forms Key token being used to make requests to the OneBlink API on behalf of the user.

    Example

    authService.setFormsKeyToken('a valid json web token')
    

    Parameters

    • jwtToken: undefined | null | string

    Returns void

  • setUserToken(token: undefined | null | string): void
  • Set the User token being included in requests to the OneBlink API on behalf of the user.

    Example

    authService.setUserToken('a value')
    

    Parameters

    • token: undefined | null | string

    Returns void

  • setupMfa(): Promise<undefined | { mfaCodeCallback: (code: string) => Promise<void>; secretCode: undefined | string }>
  • Setup MFA for the current user. The result will include a callback that should be called with the valid TOTP from an authenticator app.

    Example

    const { secretCode, mfaCodeCallback } = await authService.setupMfa()
    // Prompt the user to enter an MFA code
    const code = prompt(
    `Please enter a one-time code from your MFA app after creating a new entry with secret: ${secretCode}.`,
    )
    await mfaCodeCallback(code)

    Returns Promise<undefined | { mfaCodeCallback: (code: string) => Promise<void>; secretCode: undefined | string }>

  • signUp(__namedParameters: { email: string; firstName?: string; formsAppId: number; lastName?: string }): Promise<void>
  • Allow a user to sign up to a forms app.

    Example

    await authService.signUp({
    formsAppId: 1,
    email: 'test@oneblink.io',
    firstName: 'first',
    lastName: 'last',
    })

    Parameters

    • __namedParameters: { email: string; firstName?: string; formsAppId: number; lastName?: string }
      • email: string
      • Optional firstName?: string
      • formsAppId: number
      • Optional lastName?: string

    Returns Promise<void>