File size: 2,581 Bytes
09aa14c
05b0bc2
09aa14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea91fea
 
 
 
 
 
 
 
 
09aa14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05b0bc2
 
 
 
 
 
 
 
 
 
 
 
 
09aa14c
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { useEffect, useState, type ImgHTMLAttributes, type ReactNode } from 'react';
import { Loader2 } from 'lucide-react';
import api from '../services/api';

interface AuthImageProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {
  src: string | null | undefined;
  fallback?: ReactNode;
}

/**
 * Renders an authenticated image. The `<img src>` tag cannot send our JWT
 * Authorization header, so a direct URL to a protected endpoint (e.g.
 * `/api/v1/photos/...`) returns 401 and shows broken in the browser.
 * AuthImage fetches the bytes through the axios instance (which injects
 * the auth header), converts the response to a blob URL, and renders that.
 *
 * For dataURLs and blob URLs we render directly without fetching.
 */
export default function AuthImage({ src, fallback = null, ...imgProps }: AuthImageProps) {
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    if (!src) {
      setBlobUrl(null);
      setError(false);
      return;
    }

    // Pass-through for data: and blob: URLs, and for absolute http(s) URLs
    // (e.g. Supabase signed URLs already carry their own auth token in the
    // query string and are fetchable directly by the browser).
    if (
      src.startsWith('data:') ||
      src.startsWith('blob:') ||
      src.startsWith('http://') ||
      src.startsWith('https://')
    ) {
      setBlobUrl(src);
      setError(false);
      return;
    }

    let cancelled = false;
    let createdUrl: string | null = null;
    setError(false);

    // Strip our axios baseURL prefix so the path doesn't double up.
    const relative = src.replace(/^\/api\/v1/, '');

    api
      .get(relative, { responseType: 'blob' })
      .then((res) => {
        if (cancelled) return;
        createdUrl = URL.createObjectURL(res.data);
        setBlobUrl(createdUrl);
      })
      .catch(() => {
        if (!cancelled) setError(true);
      });

    return () => {
      cancelled = true;
      if (createdUrl) URL.revokeObjectURL(createdUrl);
    };
  }, [src]);

  if (error || !src) return <>{fallback}</>;
  if (!blobUrl) {
    const { className = '', ...rest } = imgProps;
    return (
      <div
        {...(rest as React.HTMLAttributes<HTMLDivElement>)}
        className={`${className} flex items-center justify-center bg-gray-100`}
        aria-busy="true"
        aria-label="Cargando imagen"
      >
        <Loader2 size={16} className="animate-spin text-gray-400" />
      </div>
    );
  }
  return <img src={blobUrl} {...imgProps} />;
}