File size: 1,533 Bytes
7d29959
 
 
 
 
31f62e8
7d29959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63bd9dc
7d29959
 
 
 
 
 
 
 
 
 
 
 
 
31f62e8
 
 
 
 
 
 
 
7d29959
 
 
 
 
 
 
 
 
 
 
 
 
 
31f62e8
 
7d29959
 
 
 
31f62e8
 
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
"use client";

import { useCookie, useUpdateEffect } from "react-use";
import { useQuery } from "@tanstack/react-query";

export const useUser = () => {
  const [value, setValue, remove] = useCookie("auth_hf_token");

  const {
    data: user,
    refetch,
    isLoading: loading,
    remove: clear,
  }: any = useQuery(
    ["user.me"],
    async () => {
      if (!value) return null;
      const request = await fetch("/api/me", {
        method: "GET",
        headers: {
          Authorization: `Bearer ${value}`,
        },
      })

      const res = await request.clone().json().catch(() => ({}));

      if (res.status === 401) {
        remove();
        clear();
        return null;
      }
      return res?.user;
    },
    {
      refetchOnWindowFocus: false,
    }
  );
  
  useUpdateEffect(() => {
    if (value) {
      refetch()
    }
  }
  , [value]);

  const openWindowLogin = async () => {
    const response = await fetch(`/api/login`);
    const { ok, redirect } = await response.json();
    if (ok && redirect) {
      window.open(redirect, "_blank");
    }
  };

  const getAuthorization = async (code: string) => {
    const request = await fetch("/api/auth", {
      method: "POST",
      body: JSON.stringify({
        code,
      }),
    });
    const res = await request.clone().json().catch(() => ({}));
    if (!res.ok) return
    setValue(res.access_token, {
      expires: res.experes_in,
    });
  }

  return {
    openWindowLogin,
    user,
    refetch,
    loading,
    getAuthorization
  }
}