added http provider

This commit is contained in:
Carter 2024-10-23 08:49:33 -06:00
parent 99ea402bad
commit a7b417abdf
8 changed files with 575 additions and 23 deletions

View file

@ -0,0 +1,14 @@
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
const LoginButton = () => {
const { loginWithRedirect } = useAuth0();
return (
<button onClick={() => loginWithRedirect()}>
Log In
</button>
);
};
export default LoginButton;

30
src/providers/auth.tsx Normal file
View file

@ -0,0 +1,30 @@
import { useAuth0 } from "@auth0/auth0-react";
import { PropsWithChildren, useEffect } from "react";
export default function AuthWrapper(props: PropsWithChildren<{}>) {
const { children } = props;
const { isLoading, loginWithRedirect, isAuthenticated, user } = useAuth0();
useEffect(() => {
if (!isAuthenticated && !isLoading) {
loginWithRedirect();
}
}, [isAuthenticated, loginWithRedirect]);
useEffect(() => {
console.log(user)
console.log(user?.sub)
console.log(user?.picture)
}, [user])
// if (isAuthenticated) return (
// children
// )
return (children)
}

128
src/providers/http.tsx Normal file
View file

@ -0,0 +1,128 @@
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
// import { useAuth } from "hooks";
import moment from "moment";
import { createContext, PropsWithChildren, useContext, useEffect, useState } from "react";
// import BillingProvider from "./billing";
// import GitlabProvider from "./gitlab";
import PondProvider from "./pond/pond";
// import SecurityProvider from "./security";
import { useAuth0 } from "@auth0/auth0-react";
interface IHTTPContext {
get: <T>(url: string, spreadOptions?: AxiosRequestConfig) => Promise<AxiosResponse<T>>;
put: <T>(
url: string,
data?: any,
spreadOptions?: AxiosRequestConfig
) => Promise<AxiosResponse<T>>;
post: <T>(
url: string,
data?: any,
spreadOptions?: AxiosRequestConfig
) => Promise<AxiosResponse<T>>;
del: <T>(url: string, spreadOptions?: AxiosRequestConfig) => Promise<AxiosResponse<T>>;
options: (demo?: boolean) => AxiosRequestConfig;
}
export const HTTPContext = createContext<IHTTPContext>({} as IHTTPContext);
export default function HTTPProvider(props: PropsWithChildren<any>) {
const { children } = props;
const { isAuthenticated, /*token,*/ getAccessTokenSilently } = useAuth0();
const [token, setToken] = useState("");
useEffect(() => {
if (isAuthenticated) getAccessTokenSilently().then(t => {
setToken(t)
})
}, [setToken, isAuthenticated])
useEffect(() => {
console.log(token)
}, [token])
const defaultOptions = (demo: boolean = false) => {
if (demo || !isAuthenticated || !token) {
return {
headers: {
"Content-Type": "application/json"
}
};
}
return {
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json"
}
};
};
function get<T>(url: string, spreadOptions?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return axios.get(url, { ...defaultOptions(), ...spreadOptions });
}
function put<T>(
url: string,
data?: any,
spreadOptions?: AxiosRequestConfig
): Promise<AxiosResponse<T>> {
return axios.put(url, data, { ...defaultOptions(), ...spreadOptions });
}
function post<T>(
url: string,
data?: any,
spreadOptions?: AxiosRequestConfig
): Promise<AxiosResponse<T>> {
return axios.post(url, data, { ...defaultOptions(), ...spreadOptions });
}
function del<T>(url: string, spreadOptions?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return axios.delete(url, { ...defaultOptions(), ...spreadOptions });
}
return (
<HTTPContext.Provider
value={{
get,
put,
post,
del,
options: defaultOptions
}}>
{/* <BillingProvider> */}
<PondProvider>
{children}
{/* <SecurityProvider> */}
{/* <GitlabProvider>{children}</GitlabProvider> */}
{/* </SecurityProvider> */}
</PondProvider>
{/* </BillingProvider> */}
</HTTPContext.Provider>
);
}
export const useHTTP = () => useContext(HTTPContext);
//returns a string depending on the given start and end to be used in a url query
export function dateRange(start: any, end: any): string {
start = moment(start).toISOString();
end = moment(end).toISOString();
var queryRange = "";
if (
typeof start !== "undefined" &&
start !== null &&
typeof end !== "undefined" &&
end !== null
) {
queryRange = "?start=" + start + "&end=" + end;
} else if (typeof start !== "undefined" && start !== null) {
queryRange = "?start=" + start;
} else if (typeof end !== "undefined" && end !== null) {
queryRange += "?end=" + end;
}
return queryRange;
}

View file

@ -0,0 +1,26 @@
import { PropsWithChildren } from "react";
import UserProvider, { useUserAPI } from "./userAPI";
export const pondURL = (partial: string, demo: boolean = false): string => {
let url = process.env.REACT_APP_API_URL + (demo ? "/demo" : "") + partial;
// if (isStaging()) url = process.env.REACT_APP_STAGING_API_URL + (demo ? "/demo" : "") + partial;
return url;
};
// export const objectQueryParams = (scope: Scope) => {
// return "?" + scope.kind + "_id=" + scope.key;
// };
export default function PondProvider(props: PropsWithChildren<any>) {
const { children } = props;
return (
<UserProvider>
{children}
</UserProvider>
);
}
export {
useUserAPI,
};

View file

@ -0,0 +1,236 @@
// import { useHTTP } from "hooks";
// import { Scope, User } from "models";
// import { pond } from "protobuf-ts/pond";
import { createContext, PropsWithChildren, useContext } from "react";
// import { objectQueryParams, pondURL } from "./pond";
// import { or } from "utils";
// import { useGlobalState } from "providers";
import { AxiosResponse } from "axios";
import { useHTTP } from "../http";
import { pondURL } from "./pond";
// export interface ListUsersResponse {
// users: User[];
// nextOffset: number;
// total: number;
// }
export interface IUserAPIContext {
// listUsers: (
// limit: number,
// offset: number,
// order?: "asc" | "desc",
// by?: string,
// search?: string
// ) => Promise<ListUsersResponse>;
// listProfiles: () => Promise<pond.UserProfile[]>;
// listObjectUsers: (scope: Scope) => Promise<any>;
// updateObjectUsers: (scope: Scope, users: pond.IUser[]) => Promise<any>;
getUser: (id: string) => Promise<any>;
// getUserWithTeam: (
// id: string,
// team?: string,
// scope?: Scope
// ) => Promise<AxiosResponse<pond.GetUserWithTeamResponse>>;
// getProfile: (id: string) => Promise<pond.UserProfile>;
// getUsers: (ids: string[]) => Promise<User[]>;
// getProfiles: (ids: string[]) => Promise<pond.UserProfile[]>;
// getUserSettings: (userID: string) => Promise<any>;
// updateUserSettings: (userID: string, body: pond.IUserSettings) => Promise<any>;
// updateUserStatus: (userID: string, body: pond.IUserStatus) => Promise<any>;
// updateUser: (id: string, body: pond.User) => Promise<any>;
// getUserObjectHistory: (
// id: string,
// objects: number[],
// start: string,
// end: string
// ) => Promise<AxiosResponse<pond.GetUserObjectHistoriesResponse>>;
}
export const UserAPIContext = createContext<IUserAPIContext>({} as IUserAPIContext);
export default function UserProvider(props: PropsWithChildren<any>) {
const { children } = props;
const { get, put } = useHTTP();
// const [{ as }] = useGlobalState();
// const listUsers = (
// limit: number,
// offset: number,
// order?: "asc" | "desc",
// by?: string,
// search?: string
// ): Promise<ListUsersResponse> => {
// return new Promise((resolve, reject) => {
// get(
// pondURL(
// "/users?limit=" +
// limit +
// "&offset=" +
// offset +
// ("&order=" + (order ? order : "asc")) +
// ("&by=" + (by ? by : "name")) +
// (search ? "&search=" + search : "")
// )
// )
// .then((res: any) => {
// let users: User[] = [];
// if (res && res.data && res.data.users) {
// res.data.users.forEach((raw: any) => users.push(User.any(raw)));
// }
// resolve({
// users: users,
// nextOffset: or(res.data.nextOffset, 0),
// total: or(res.data.total, 0)
// });
// })
// .catch((err: any) => reject(err));
// });
// };
// const listProfiles = (): Promise<pond.UserProfile[]> => {
// return new Promise((resolve, reject) => {
// get(pondURL("/profiles/"))
// .then((res: any) => {
// let profiles: pond.UserProfile[] = [];
// if (res && res.data && res.data.users) {
// res.data.users.forEach((raw: any) => profiles.push(pond.UserProfile.fromObject(raw)));
// }
// resolve(profiles);
// })
// .catch((err: any) => reject(err));
// });
// };
// const listObjectUsers = (scope: Scope) => {
// let sql = "/" + scope.kind + "s/" + scope.key + "/users";
// if (as) sql = sql + "?as=" + as;
// return get(pondURL(sql));
// };
// const updateObjectUsers = (scope: Scope, users: pond.IUser[]) => {
// return put(pondURL("/users" + objectQueryParams(scope)), { users });
// };
// const getUser = (id: string): Promise<User> => {
const getUser = (id: string): Promise<any> => {
let partial = "/users/" + id;
// if (scope) partial += "?kind=" + scope.kind + "&key=" + scope.key;
return new Promise(function(resolve, reject) {
get(pondURL(partial))
.then((response: any) => resolve(response.data))
.catch((error: any) => reject(error));
});
};
// const getUserWithTeam = (
// id: string,
// team?: string,
// scope?: Scope
// ): Promise<AxiosResponse<pond.GetUserWithTeamResponse>> => {
// let partial = "/userWithTeam/" + id;
// if (scope) partial += "?kind=" + scope.kind + "&key=" + scope.key;
// if (team) {
// if (partial.includes("?")) {
// partial += "&team=" + team;
// } else {
// partial += "?team=" + team;
// }
// }
// return new Promise(function(resolve, reject) {
// get(pondURL(partial))
// .then((response: any) => resolve(response))
// .catch((error: any) => reject(error));
// });
// };
// const getProfile = (id: string): Promise<pond.UserProfile> => {
// return new Promise((resolve, reject) => {
// get(pondURL("/profiles/" + id))
// .then((res: any) => resolve(pond.UserProfile.fromObject(res.data)))
// .catch((err: any) => reject(err));
// });
// };
// const getUsers = (ids: string[]): Promise<User[]> => {
// return new Promise((resolve, reject) => {
// get(pondURL("/users/?ids=" + ids.join(",")))
// .then((res: any) => {
// let users: User[] = [];
// if (res && res.data && res.data.users) {
// users = res.data.users.map((data: any) => User.any(data));
// }
// resolve(users);
// })
// .catch((err: any) => reject(err));
// });
// };
// const getProfiles = (ids: string[]): Promise<pond.UserProfile[]> => {
// return new Promise((resolve, reject) => {
// get(pondURL("/profiles/?ids=" + ids.join(",")))
// .then((res: any) => {
// let profiles: pond.UserProfile[] = [];
// if (res && res.data && res.data.users) {
// profiles = res.data.users.map((raw: any) => pond.UserProfile.fromObject(raw));
// }
// resolve(profiles);
// })
// .catch((err: any) => reject(err));
// });
// };
// const getUserSettings = (userID: string) => {
// return get(pondURL("/users/" + userID + "/settings"));
// };
// const updateUserSettings = (userID: string, body: pond.IUserSettings) => {
// return put(pondURL("/users/" + userID + "/settings"), body);
// };
// const updateUserStatus = (userID: string, body: pond.IUserStatus) => {
// return put(pondURL("/users/" + userID + "/status"), body);
// };
// const updateUser = (id: string, body: pond.User) => {
// return put(pondURL("/users/" + id), body);
// };
// const getUserObjectHistory = (id: string, objects: number[], start: string, end: string) => {
// return get<pond.GetUserObjectHistoriesResponse>(
// pondURL(
// "/users/" +
// id +
// "/objectHistories/?objects=" +
// objects.toString() +
// "&start=" +
// start +
// "&end=" +
// end
// )
// );
// };
return (
<UserAPIContext.Provider
value={{
// listUsers,
// listProfiles,
// listObjectUsers,
// updateObjectUsers,
getUser,
// getUserWithTeam,
// getProfile,
// getUsers,
// getProfiles,
// getUserSettings,
// updateUserSettings,
// updateUserStatus,
// updateUser,
// getUserObjectHistory
}}>
{children}
</UserAPIContext.Provider>
);
}
export const useUserAPI = () => useContext(UserAPIContext);