81 lines
2.2 KiB
TypeScript
81 lines
2.2 KiB
TypeScript
import React, { useEffect } from "react";
|
|
import { useState } from "react";
|
|
import { Credentials, User, TokenData } from "../Types";
|
|
import { useNavigate } from "react-router-dom";
|
|
import { fetchUserById, logIn } from "../Api";
|
|
import { tokenStatus } from "../Api";
|
|
import jwt_decode from "jwt-decode";
|
|
|
|
export const useAuthenticateUser = () => {
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [isAirline, setIsAirline] = useState(false);
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [tokenValidated, setTokenValidated] = useState(false);
|
|
|
|
const navigate = useNavigate();
|
|
|
|
const authenticate = async (credentials: Credentials): Promise<void> => {
|
|
if (!user) {
|
|
try {
|
|
setIsLoading(true);
|
|
setError(null);
|
|
|
|
const tokens = await logIn(credentials);
|
|
localStorage.setItem("token", tokens.access_token);
|
|
const airline = (jwt_decode(tokens.access_token) as TokenData).airline;
|
|
setIsAirline(airline)
|
|
|
|
if (tokens.user_id) {
|
|
const user = await fetchUserById(tokens.user_id);
|
|
setUser(user);
|
|
} else {
|
|
setError(tokens.message!.split(".")[0] + ".");
|
|
setUser(null);
|
|
}
|
|
} catch (error) {
|
|
setError(error as string);
|
|
} finally {
|
|
setIsLoading(false);
|
|
navigate("/home")
|
|
}
|
|
}
|
|
};
|
|
|
|
const validateToken = async () => {
|
|
try {
|
|
setIsLoading(true);
|
|
const existingToken = localStorage.getItem("token");
|
|
if (existingToken && !tokenValidated) {
|
|
const response = await tokenStatus(existingToken);
|
|
|
|
const { message } = response;
|
|
if (message) throw new Error("Invalid token");
|
|
|
|
const airline = (jwt_decode(existingToken) as TokenData).airline;
|
|
setIsAirline(airline)
|
|
|
|
const user = await fetchUserById(response.id);
|
|
setUser(user);
|
|
}
|
|
|
|
setTokenValidated(true);
|
|
} catch (error) {
|
|
logout();
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
|
|
return user;
|
|
};
|
|
|
|
const logout = () => {
|
|
localStorage.removeItem("token");
|
|
setUser(null);
|
|
setTokenValidated(false)
|
|
navigate("/login");
|
|
};
|
|
|
|
return { user, isLoading, authenticate, validateToken, isAirline, logout, error };
|
|
};
|