useAuth.ts 1.21 KB
import { useState, useCallback } from "react";
import ky from "ky";

interface LoginResponse {
  status: number;
  data: {
    access_token: string;
    refresh_token: string;
    expiration: string;
  };
}

interface Token {
  accessToken: string;
  refreshToken: string;
  expiration: Date;
}

export function useAuth() {
  const [token, setToken] = useState<Token | null>(() => {
    const item = localStorage.getItem("token");
    if (item) {
      const token = JSON.parse(item);
      token.expiration = new Date(token.expiration);
      return token;
    }
    return null;
  });

  const login = useCallback(
    async (username: string, password: string, remember: boolean) => {
      const response = await ky
        .post("/users/login", {
          json: {
            user_id: username,
            password: password,
          },
        })
        .json<LoginResponse>();

      const token = {
        accessToken: response.data.access_token,
        refreshToken: response.data.refresh_token,
        expiration: new Date(response.data.expiration),
      };

      setToken(token);

      if (remember) {
        localStorage.setItem("token", JSON.stringify(token));
      }
    },
    []
  );

  return { token, login };
}