File size: 817 Bytes
43370b3
 
 
 
 
 
6a685c7
 
 
 
 
 
43370b3
 
 
6a685c7
 
43370b3
 
 
 
6a685c7
43370b3
 
 
 
 
 
 
 
6a685c7
43370b3
 
 
 
 
 
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
import { useEffect, useState } from 'react'

export interface AuthUser {
  id: string
  name: string
  avatar?: string
  provider?: string
}

export interface AuthProvider {
  id: string
  label: string
}

export interface AuthInfo {
  providers: AuthProvider[]
  authRequired: boolean
  user: AuthUser | null
  collabToken: string | null
}

const FALLBACK: AuthInfo = { providers: [], authRequired: false, user: null, collabToken: null }

export function useAuth(): AuthInfo | null {
  const [auth, setAuth] = useState<AuthInfo | null>(null)
  useEffect(() => {
    let alive = true
    fetch('/api/auth/me')
      .then((r) => r.json() as Promise<AuthInfo>)
      .then((a) => alive && setAuth(a))
      .catch(() => alive && setAuth(FALLBACK))
    return () => {
      alive = false
    }
  }, [])
  return auth
}