Presupuestador_web/client/src/lib/axios/createAxiosAuthActions.ts

100 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-07-12 17:29:28 +00:00
import { IGetProfileResponse_DTO, ILogin_DTO, ILogin_Response_DTO } from "@shared/contexts";
2024-06-06 11:05:54 +00:00
import secureLocalStorage from "react-secure-storage";
import { IAuthActions } from "../hooks";
import { createAxiosInstance } from "./axiosInstance";
export const createAxiosAuthActions = (
apiUrl: string,
httpClient = createAxiosInstance()
): IAuthActions => ({
login: async ({ email, password }: ILogin_DTO) => {
try {
2024-06-09 20:04:46 +00:00
const result = await httpClient.request<ILogin_Response_DTO>({
2024-06-06 11:05:54 +00:00
url: `${apiUrl}/auth/login`,
method: "POST",
data: {
email,
password,
},
});
2024-06-09 20:04:46 +00:00
const { data } = result;
secureLocalStorage.setItem("uecko.auth", data);
2024-06-06 11:05:54 +00:00
return {
success: true,
data,
2024-08-29 14:59:33 +00:00
redirectTo: "/quotes",
2024-06-06 11:05:54 +00:00
};
} catch (error) {
return {
success: false,
error: {
message: "Login failed",
name: "Invalid email or password",
},
};
}
},
2024-06-09 20:04:46 +00:00
2024-06-06 11:05:54 +00:00
logout: () => {
2024-06-09 20:04:46 +00:00
secureLocalStorage.clear();
2024-06-06 11:05:54 +00:00
return Promise.resolve({
success: true,
redirectTo: "/login",
});
},
2024-06-09 20:04:46 +00:00
2024-06-06 11:05:54 +00:00
check: () => {
2024-07-12 17:29:28 +00:00
const authUser = secureLocalStorage.getItem("uecko.auth") as ILogin_Response_DTO;
2024-06-09 20:04:46 +00:00
2024-06-06 11:05:54 +00:00
return Promise.resolve(
2024-07-12 17:29:28 +00:00
authUser?.token
2024-06-06 11:05:54 +00:00
? {
authenticated: true,
}
2024-07-09 16:21:12 +00:00
: {
authenticated: false,
redirectTo: "/login",
}
2024-06-06 11:05:54 +00:00
);
},
2024-06-09 20:04:46 +00:00
2024-07-12 16:13:53 +00:00
getProfile: async () => {
/**
* id: string;
* name: string;
* email: string;
* lang_code: string;
* roles: string[];
*/
2024-06-09 20:04:46 +00:00
try {
2024-07-12 17:29:28 +00:00
const result = await httpClient.request<IGetProfileResponse_DTO>({
2024-07-12 16:13:53 +00:00
url: `${apiUrl}/profile`,
2024-06-09 20:04:46 +00:00
method: "GET",
});
2024-07-12 17:29:28 +00:00
const { data: profile } = result;
const authUser = secureLocalStorage.getItem("uecko.auth") as ILogin_Response_DTO;
2024-06-09 20:04:46 +00:00
2024-07-12 17:29:28 +00:00
if (authUser?.id === profile?.id) {
secureLocalStorage.setItem("uecko.profile", profile);
return Promise.resolve(profile);
2024-06-09 20:04:46 +00:00
}
2024-07-09 16:21:12 +00:00
return Promise.resolve(null);
2024-06-09 20:04:46 +00:00
} catch (error) {
2024-07-09 16:21:12 +00:00
return Promise.resolve(null);
2024-06-09 20:04:46 +00:00
}
},
2024-06-06 11:05:54 +00:00
onError: (error: any) => {
2024-06-09 20:04:46 +00:00
secureLocalStorage.clear();
2024-06-06 11:05:54 +00:00
return Promise.resolve({
error,
logout: true,
});
},
});