Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

6.1 KB
Raw Blame
import { Alert, Button, Input, Space, Spin, Collapse } from 'antd';
import React, { FC, useEffect, useState } from 'react';
import dynamic from 'next/dynamic';
import styles from './FediAuthModal.module.scss';
import { isValidFediverseAccount } from '../../../utils/validators';
import {
  getPendingFediverseAuth,
  setPendingFediverseAuth,
  clearPendingFediverseAuth,
} from '../../../utils/fediverseAuthSession';

// Lazy loaded components

const CheckCircleOutlined = dynamic(() => import('@ant-design/icons/CheckCircleOutlined'), {
  ssr: false,
});

export type FediAuthModalProps = {
  authenticated: boolean;
  displayName: string;
  accessToken: string;
};

export const FediAuthModal: FC<FediAuthModalProps> = ({
  authenticated,
  displayName,
  accessToken,
}) => {
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [valid, setValid] = useState(false);
  const [account, setAccount] = useState('');
  const [code, setCode] = useState('');
  const [verifyingCode, setVerifyingCode] = useState(false);

  // Restore an in-progress verification if the viewer left and came back (e.g.
  // backgrounded the tab to copy their code) within the OTP lifetime.
  useEffect(() => {
    const pending = getPendingFediverseAuth();
    if (pending) {
      setAccount(pending.account);
      setValid(isValidFediverseAccount(pending.account));
      setVerifyingCode(true);
    }
  }, []);

  const message = !authenticated ? (
    <span>
      Receive a direct message on the Fediverse to link your account to{' '}
      <strong>{displayName}</strong>, or login as a previously linked chat user.
    </span>
  ) : (
    <span>
      <b>You are already authenticated</b>. However, you can add other domains or log in as a
      different user.
    </span>
  );

  let errorMessageText = errorMessage;
  if (errorMessageText) {
    if (errorMessageText.includes('url does not support indieauth')) {
      errorMessageText = 'The provided URL is either invalid or does not support IndieAuth.';
    }
  }

  const validate = (acct: string) => {
    setValid(isValidFediverseAccount(acct));
  };

  const onInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAccount(e.target.value);
    validate(e.target.value);
  };

  const makeRequest = async (url, data) => {
    const rawResponse = await fetch(url, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    let content: { message?: string } = {};
    try {
      content = await rawResponse.json();
    } catch {
      // Non-JSON response; the status check below handles it.
    }

    if (content.message) {
      // Callers set the error message, so just surface it.
      setLoading(false);
      throw new Error(content.message);
    }
    if (!rawResponse.ok) {
      setLoading(false);
      throw new Error('Something went wrong. Please try again.');
    }
  };

  const submitCodePressed = async () => {
    setLoading(true);
    const url = `/api/auth/fediverse/verify?accessToken=${accessToken}`;
    const data = { code };

    try {
      await makeRequest(url, data);

      // Verified. Drop the persisted state and reload the page.
      clearPendingFediverseAuth();
      window.location.href = '/';
    } catch (e) {
      console.error(e);
      setErrorMessage(e.message);
    }
    setLoading(false);
  };

  const submitAccountPressed = async () => {
    if (!valid) {
      return;
    }

    setLoading(true);
    setErrorMessage(null);
    const url = `/api/auth/fediverse?accessToken=${accessToken}`;
    const normalizedAccount = account.replace(/^@+/, '');
    const data = { account: normalizedAccount };

    try {
      await makeRequest(url, data);
      setPendingFediverseAuth(normalizedAccount);
      setVerifyingCode(true);
    } catch (e) {
      console.error(e);
      setErrorMessage(e.message);
    }
    setLoading(false);
  };

  const inputCodeStep = (
    <div>
      Paste in the code that was sent to your Fediverse account. If you did not receive a code, make
      sure you can accept direct messages.
      <div className={styles.codeInputContainer}>
        <Input
          value={code}
          onChange={e => setCode(e.target.value)}
          className={styles.codeInput}
          placeholder="123456"
          maxLength={6}
        />
        <Button
          type="primary"
          onClick={submitCodePressed}
          disabled={code.length < 6}
          className={styles.submitButton}
        >
          Verify Code
        </Button>
      </div>
    </div>
  );

  const inputAccountStep = (
    <>
      <div>Your Fediverse Account</div>
      <Input.Search
        addonBefore="@"
        onInput={onInput}
        value={account}
        placeholder="[email protected]"
        status={!valid && account.length > 0 ? 'error' : undefined}
        onSearch={submitAccountPressed}
        enterButton={
          <Button type={valid ? 'primary' : 'default'} disabled={!valid || account.length === 0}>
            <CheckCircleOutlined />
          </Button>
        }
      />
    </>
  );

  return (
    <Spin spinning={loading}>
      <Space orientation="vertical">
        {message}
        {errorMessageText && (
          <Alert message="Error" description={errorMessageText} type="error" showIcon />
        )}
        {verifyingCode ? inputCodeStep : inputAccountStep}
        <Collapse
          ghost
          items={[
            {
              key: 'header',
              label: 'Learn more about using the Fediverse to authenticate with chat.',
              children: (
                <p>
                  You can link your chat identity with your Fediverse identity. Next time you want
                  to use this chat identity you can again go through the Fediverse authentication.
                </p>
              ),
            },
          ]}
        />
        <div>
          <strong>Note</strong>: This is for authentication purposes only, and no personal
          information will be accessed or stored.
        </div>
      </Space>
    </Spin>
  );
};