Spaces:
Runtime error
Runtime error
File size: 1,899 Bytes
7d29959 be213e2 7d29959 31f62e8 7d29959 be213e2 7d29959 486f5c7 7d29959 63bd9dc 7d29959 486f5c7 7d29959 31f62e8 bcb1927 31f62e8 7d29959 63fef5b be213e2 63fef5b 7d29959 4cc6b33 721e8fe 4cc6b33 7d29959 31f62e8 7d29959 03138b9 be213e2 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
"use client";
import { useCookie, useUpdateEffect } from "react-use";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
export const useUser = () => {
const [value, setValue, remove] = useCookie("auth_hf_token");
const [error, setError] = useState(null);
const {
data: user,
refetch,
isLoading: loading,
remove: clear,
}: any = useQuery(
["user.me"],
async () => {
if (!value) return null;
if (user) return user;
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,
refetchOnMount: false,
refetchOnReconnect: 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) {
setError(res);
return null;
}
setValue(res.access_token, {
expires: new Date(
res.experes_in * 1000 + new Date().getTime()
),
path: "/",
secure: true,
httpOnly: true,
});
}
return {
openWindowLogin,
user,
refetch,
loading,
token: `Bearer ${value}`,
error,
getAuthorization
}
} |