2021-05-04 17:58:18 +00:00
|
|
|
import type RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation";
|
2021-07-21 09:30:18 +00:00
|
|
|
import _ from "lodash";
|
|
|
|
import React, { useState } from "react";
|
2021-04-08 19:20:35 +00:00
|
|
|
import { RecentUsed } from "../../components/realm-selector/recent-used";
|
2021-07-15 09:50:01 +00:00
|
|
|
import environment from "../../environment";
|
2021-07-21 09:30:18 +00:00
|
|
|
import useRequiredContext from "../../utils/useRequiredContext";
|
|
|
|
import { useAdminClient, useFetch } from "../auth/AdminClient";
|
2020-09-17 11:37:30 +00:00
|
|
|
|
2021-01-05 19:49:33 +00:00
|
|
|
type RealmContextType = {
|
|
|
|
realm: string;
|
|
|
|
setRealm: (realm: string) => void;
|
2021-05-03 16:44:47 +00:00
|
|
|
realms: RealmRepresentation[];
|
|
|
|
refresh: () => Promise<void>;
|
2021-01-05 19:49:33 +00:00
|
|
|
};
|
|
|
|
|
2021-07-21 09:30:18 +00:00
|
|
|
export const RealmContext = React.createContext<RealmContextType | undefined>(
|
|
|
|
undefined
|
|
|
|
);
|
2020-09-17 11:37:30 +00:00
|
|
|
|
|
|
|
type RealmContextProviderProps = { children: React.ReactNode };
|
|
|
|
|
|
|
|
export const RealmContextProvider = ({
|
|
|
|
children,
|
|
|
|
}: RealmContextProviderProps) => {
|
2021-07-15 09:50:01 +00:00
|
|
|
const [realm, setRealm] = useState(environment.loginRealm);
|
2021-05-03 16:44:47 +00:00
|
|
|
const [realms, setRealms] = useState<RealmRepresentation[]>([]);
|
|
|
|
const adminClient = useAdminClient();
|
2021-04-08 19:20:35 +00:00
|
|
|
const recentUsed = new RecentUsed();
|
|
|
|
|
2021-05-03 16:44:47 +00:00
|
|
|
const updateRealmsList = (realms: RealmRepresentation[]) => {
|
|
|
|
setRealms(_.sortBy(realms, "realm"));
|
|
|
|
recentUsed.clean(realms.map((r) => r.realm!));
|
2021-04-08 19:20:35 +00:00
|
|
|
};
|
2020-09-17 11:37:30 +00:00
|
|
|
|
2021-04-29 06:28:59 +00:00
|
|
|
useFetch(
|
|
|
|
() => adminClient.realms.find(),
|
|
|
|
(realms) => updateRealmsList(realms),
|
2021-05-03 16:44:47 +00:00
|
|
|
[]
|
|
|
|
);
|
|
|
|
|
|
|
|
const set = (realm: string) => {
|
|
|
|
if (
|
|
|
|
realms.length === 0 ||
|
|
|
|
realms.findIndex((r) => r.realm == realm) !== -1
|
|
|
|
) {
|
|
|
|
recentUsed.setRecentUsed(realm);
|
|
|
|
setRealm(realm);
|
|
|
|
adminClient.setConfig({
|
|
|
|
realmName: realm,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
2020-09-17 11:37:30 +00:00
|
|
|
return (
|
2021-05-03 16:44:47 +00:00
|
|
|
<RealmContext.Provider
|
|
|
|
value={{
|
|
|
|
realm,
|
|
|
|
setRealm: set,
|
|
|
|
realms,
|
|
|
|
refresh: async () => {
|
|
|
|
const list = await adminClient.realms.find();
|
|
|
|
updateRealmsList(list);
|
|
|
|
},
|
|
|
|
}}
|
|
|
|
>
|
2020-09-17 11:37:30 +00:00
|
|
|
{children}
|
|
|
|
</RealmContext.Provider>
|
|
|
|
);
|
|
|
|
};
|
2021-01-05 19:49:33 +00:00
|
|
|
|
2021-07-21 09:30:18 +00:00
|
|
|
export const useRealm = () => useRequiredContext(RealmContext);
|