cityssm/parking-ticket-system

View on GitHub
helpers/functions.authentication.ts

Summary

Maintainability
A
0 mins
Test Coverage
import {
  ActiveDirectoryAuthenticator,
  type BaseAuthenticator,
  PlainTextAuthenticator
} from '@cityssm/authentication-helper'

import { useTestDatabases } from '../data/databasePaths.js'

import { getConfigProperty } from './functions.config.js'

const userDomain = getConfigProperty('application.userDomain')

const activeDirectoryConfig = getConfigProperty('activeDirectory')

const adAuthenticator =
  activeDirectoryConfig === undefined
    ? undefined
    : new ActiveDirectoryAuthenticator(activeDirectoryConfig)

let authenticator: BaseAuthenticator

if (useTestDatabases) {
  const testingUsersList = getConfigProperty('users.testing')

  const testingUsers: Record<string, string> = {}

  for (const user of testingUsersList) {
    testingUsers[`${userDomain}\\${user}`] = user
  }

  authenticator = new PlainTextAuthenticator(testingUsers, adAuthenticator)
} else if (adAuthenticator === undefined) {
  throw new Error('No authenticator available.')
} else {
  authenticator = adAuthenticator
}

export async function authenticate(
  userName: string,
  password: string
): Promise<boolean> {
  return await authenticator.authenticate(userName, password)
}

const safeRedirects = new Set([
  '/tickets',
  '/tickets/new',
  '/tickets/reconcile',
  '/tickets-ontario/convict',
  '/plates',
  '/plates-ontario/mtoExport',
  '/plates-ontario/mtoImport',
  '/reports',
  '/admin/cleanup',
  '/admin/offences',
  '/admin/locations',
  '/admin/bylaws'
])

export function getSafeRedirectURL(possibleRedirectURL = ''): string {
  const urlPrefix = getConfigProperty('reverseProxy.urlPrefix')

  if (typeof possibleRedirectURL === 'string') {
    const urlToCheck = possibleRedirectURL.startsWith(urlPrefix)
      ? possibleRedirectURL.slice(urlPrefix.length)
      : possibleRedirectURL

    const urlToCheckLowerCase = urlToCheck.toLowerCase()

    if (safeRedirects.has(urlToCheckLowerCase)) {
      return urlPrefix + urlToCheck
    }
  }

  return `${urlPrefix}/dashboard/`
}