💾 Archived View for iich.space › src › util › identity.ts captured on 2022-03-01 at 16:00:12.

View Raw

More Information

⬅️ Previous capture (2021-12-03)

-=-=-=-=-=-=-

import { Request } from '@/gemini';

import { Identity } from '~/db/models';
import { getIdentity } from '~/db/queries';

import { generateHash } from './hash';

export interface IdentityDisplay extends Identity {
  display: string;
}

export const getFingerprint = (req: Request, signed: string): string | null =>
  signed === 'signed' ? prepareFingerprint(req.fingerprint!) : null;

export const prepareFingerprint = (raw: string): string =>
  raw.replaceAll(':', '');

export const generateIdentityHash = (fingerprint: string): string =>
  generateHash(prepareFingerprint(fingerprint), 'hex').slice(0, 8);

export const getDisplayIdentityFromFingerprintAndName = (
  fingerprint: string,
  name: string,
): IdentityDisplay => {
  const truncatedName = name.slice(0, 10);
  const hash = generateIdentityHash(fingerprint);
  const display = `${truncatedName}!${hash}`;

  return {
    display,
    fingerprint,
    name: truncatedName,
  };
};

export const getDisplayIdentityFromRequest = (
  req: Request,
): IdentityDisplay | null => {
  if (req.fingerprint === null) {
    return null;
  }

  const identity = getIdentity(req.fingerprint);

  return getDisplayIdentityFromFingerprintAndName(
    identity.fingerprint,
    identity.name,
  );
};