update who am i on realm create as we need the accessTypes (#276)

* whoAmI has the realm access information
so when a new realm is created the whoAmI request has to be done again

* fixed "add realm" button

* remove debug

* refactor

* also force token update

* refresh realm list on realm change
This commit is contained in:
Erik Jan de Wit 2021-01-12 13:39:37 +01:00 committed by GitHub
parent be2268df2f
commit dba53a01b3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 74 additions and 59 deletions

View file

@ -133,7 +133,7 @@ export const Header = () => {
};
const UserDropdown = () => {
const whoami = useContext(WhoAmIContext);
const { whoAmI } = useContext(WhoAmIContext);
const [isDropdownOpen, setDropdownOpen] = useState(false);
const onDropdownToggle = () => {
@ -147,7 +147,7 @@ export const Header = () => {
isOpen={isDropdownOpen}
toggle={
<DropdownToggle onToggle={onDropdownToggle}>
{whoami.getDisplayName()}
{whoAmI.getDisplayName()}
</DropdownToggle>
}
dropdownItems={userDropdownItems}

View file

@ -18,6 +18,7 @@ import { routes } from "./route-config";
export const PageNav: React.FunctionComponent = () => {
const { t } = useTranslation("common");
const { hasAccess, hasSomeAccess } = useAccess();
const { realm } = useRealm();
const adminClient = useAdminClient();
const realmLoader = async () => {
return await adminClient.realms.find();
@ -81,10 +82,10 @@ export const PageNav: React.FunctionComponent = () => {
nav={
<Nav onSelect={onSelect}>
<NavList>
<DataLoader loader={realmLoader}>
<DataLoader loader={realmLoader} deps={[realm]}>
{(realmList) => (
<NavItem className="keycloak__page_nav__nav_item__realm-selector">
<RealmSelector realmList={realmList.data || []} />
<RealmSelector realmList={realmList || []} />
</NavItem>
)}
</DataLoader>

View file

@ -137,7 +137,7 @@ export const ServiceAccount = ({ clientId }: ServiceAccountProps) => {
</>
}
>
<DataLoader loader={loader}>
<DataLoader loader={loader} deps={[clientId]}>
{(clientRoles) => (
<>
{hide ? "" : " "}
@ -152,7 +152,7 @@ export const ServiceAccount = ({ clientId }: ServiceAccountProps) => {
},
{ title: t("description"), cellFormatters: [emptyFormatter()] },
]}
rows={clientRoles.data}
rows={clientRoles}
aria-label="roleList"
>
<TableHeader />

View file

@ -1,37 +1,26 @@
import React, { useEffect, useState } from "react";
import React, { DependencyList, useEffect, useState } from "react";
import { Spinner } from "@patternfly/react-core";
import { asyncStateFetch } from "../../context/auth/AdminClient";
type DataLoaderProps<T> = {
loader: () => Promise<T>;
deps?: any[];
children: ((arg: Result<T>) => any) | React.ReactNode;
};
type Result<T> = {
data: T;
refresh: () => void;
deps?: DependencyList;
children: ((arg: T) => any) | React.ReactNode;
};
export function DataLoader<T>(props: DataLoaderProps<T>) {
const [data, setData] = useState<{ result: T } | undefined>(undefined);
const [key, setKey] = useState(0);
const refresh = () => setKey(new Date().getTime());
const [data, setData] = useState<T | undefined>();
useEffect(() => {
return asyncStateFetch(
() => props.loader(),
(result) => setData({ result })
(result) => setData(result)
);
}, [key]);
}, props.deps || []);
if (data) {
if (props.children instanceof Function) {
return props.children({
data: data.result,
refresh: refresh,
});
return props.children(data);
}
return props.children;
}

View file

@ -22,7 +22,7 @@ describe("<DataLoader />", () => {
<DataLoader loader={loader}>
{(result) => (
<div>
{result.data.map((d, i) => (
{result.map((d, i) => (
<i key={i}>{d}</i>
))}
</div>

View file

@ -14,7 +14,9 @@ describe("<FormAccess />", () => {
const Form = ({ realm }: { realm: string }) => {
const { register, control } = useForm();
return (
<WhoAmIContext.Provider value={new WhoAmI("master", whoami)}>
<WhoAmIContext.Provider
value={{ refresh: () => {}, whoAmI: new WhoAmI("master", whoami) }}
>
<RealmContext.Provider value={{ realm, setRealm: () => {} }}>
<AccessContextProvider>
<FormAccess role="manage-clients">

View file

@ -1,5 +1,5 @@
import React, { useState, useContext, useEffect } from "react";
import { useHistory, useRouteMatch } from "react-router-dom";
import { useHistory } from "react-router-dom";
import { useTranslation } from "react-i18next";
import {
@ -27,13 +27,12 @@ type RealmSelectorProps = {
export const RealmSelector = ({ realmList }: RealmSelectorProps) => {
const { realm, setRealm } = useRealm();
const whoami = useContext(WhoAmIContext);
const { whoAmI } = useContext(WhoAmIContext);
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
const [filteredItems, setFilteredItems] = useState(realmList);
const history = useHistory();
const { t } = useTranslation("common");
const { url } = useRouteMatch();
const toUpperCase = (realmName: string) =>
realmName.charAt(0).toUpperCase() + realmName.slice(1);
@ -49,7 +48,10 @@ export const RealmSelector = ({ realmList }: RealmSelectorProps) => {
<Button
component="div"
isBlock
onClick={() => history.push(`${url}/add-realm"`)}
onClick={() => {
history.push(`/${realm}/add-realm`);
setOpen(!open);
}}
className={className}
>
{t("createRealm")}
@ -85,7 +87,7 @@ export const RealmSelector = ({ realmList }: RealmSelectorProps) => {
const addRealmComponent = (
<React.Fragment key="Add Realm">
{whoami.canCreateRealm() && (
{whoAmI.canCreateRealm() && (
<>
<Divider key="divider" />
<DropdownItem key="add">

View file

@ -1,4 +1,4 @@
import React, { createContext, useContext } from "react";
import React, { createContext, useContext, useEffect, useState } from "react";
import { AccessType } from "keycloak-admin/lib/defs/whoAmIRepresentation";
import { RealmContext } from "../../context/realm-context/RealmContext";
@ -18,17 +18,20 @@ export const useAccess = () => useContext(AccessContext);
type AccessProviderProps = { children: React.ReactNode };
export const AccessContextProvider = ({ children }: AccessProviderProps) => {
const whoami = useContext(WhoAmIContext);
const { whoAmI } = useContext(WhoAmIContext);
const realmCtx = useContext(RealmContext);
const [access, setAccess] = useState<readonly AccessType[]>([]);
const access = () => whoami.getRealmAccess()[realmCtx.realm];
useEffect(() => {
setAccess(whoAmI.getRealmAccess()[realmCtx.realm]);
}, [whoAmI]);
const hasAccess = (...types: AccessType[]) => {
return types.every((type) => type === "anyone" || access().includes(type));
return types.every((type) => type === "anyone" || access.includes(type));
};
const hasSomeAccess = (...types: AccessType[]) => {
return types.some((type) => type === "anyone" || access().includes(type));
return types.some((type) => type === "anyone" || access.includes(type));
};
return (

View file

@ -23,7 +23,7 @@ export const ServerInfoProvider = ({ children }: { children: ReactNode }) => {
return (
<DataLoader loader={loader}>
{(serverInfo) => (
<ServerInfoContext.Provider value={serverInfo.data}>
<ServerInfoContext.Provider value={serverInfo}>
{children}
</ServerInfoContext.Provider>
)}

View file

@ -1,8 +1,7 @@
import React, { useContext } from "react";
import React, { useContext, useEffect, useState } from "react";
import i18n from "../../i18n";
import { DataLoader } from "../../components/data-loader/DataLoader";
import { AdminClient } from "../auth/AdminClient";
import { AdminClient, asyncStateFetch } from "../auth/AdminClient";
import { RealmContext } from "../realm-context/RealmContext";
import WhoAmIRepresentation, {
AccessType,
@ -50,31 +49,42 @@ export class WhoAmI {
}
}
export const WhoAmIContext = React.createContext(new WhoAmI());
type WhoAmIProps = {
refresh: () => void;
whoAmI: WhoAmI;
};
export const WhoAmIContext = React.createContext<WhoAmIProps>({
refresh: () => {},
whoAmI: new WhoAmI(),
});
type WhoAmIProviderProps = { children: React.ReactNode };
export const WhoAmIContextProvider = ({ children }: WhoAmIProviderProps) => {
const adminClient = useContext(AdminClient)!;
const { realm, setRealm } = useContext(RealmContext);
const [whoAmI, setWhoAmI] = useState<WhoAmI>(new WhoAmI());
const [key, setKey] = useState(0);
const whoAmILoader = async () => {
const whoamiResponse = await adminClient.whoAmI.find({
useEffect(() => {
return asyncStateFetch(
() =>
adminClient.whoAmI.find({
realm: adminClient.keycloak?.realm,
});
const whoAmI = new WhoAmI(adminClient.keycloak?.realm, whoamiResponse);
}),
(me) => {
const whoAmI = new WhoAmI(adminClient.keycloak?.realm, me);
if (!realm) {
setRealm(whoAmI.getHomeRealm());
}
return whoAmI;
};
setWhoAmI(whoAmI);
}
);
}, [key]);
return (
<DataLoader loader={whoAmILoader}>
{(whoami) => (
<WhoAmIContext.Provider value={whoami.data}>
<WhoAmIContext.Provider value={{ refresh: () => setKey(key + 1), whoAmI }}>
{children}
</WhoAmIContext.Provider>
)}
</DataLoader>
);
};

View file

@ -1,4 +1,5 @@
import React from "react";
import React, { useContext } from "react";
import { useHistory } from "react-router-dom";
import { useTranslation } from "react-i18next";
import {
PageSection,
@ -17,9 +18,12 @@ import { useForm, Controller } from "react-hook-form";
import { ViewHeader } from "../../components/view-header/ViewHeader";
import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation";
import { useAdminClient } from "../../context/auth/AdminClient";
import { WhoAmIContext } from "../../context/whoami/WhoAmI";
export const NewRealmForm = () => {
const { t } = useTranslation("realm");
const history = useHistory();
const { refresh } = useContext(WhoAmIContext);
const adminClient = useAdminClient();
const { addAlert } = useAlerts();
@ -40,6 +44,10 @@ export const NewRealmForm = () => {
try {
await adminClient.realms.create(realm);
addAlert(t("Realm created"), AlertVariant.success);
refresh();
//force token update
await adminClient.keycloak?.updateToken(Number.MAX_VALUE);
history.push(`/${realm.realm}`);
} catch (error) {
addAlert(
`${t("Could not create realm:")} '${error}'`,