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

View file

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

View file

@ -137,7 +137,7 @@ export const ServiceAccount = ({ clientId }: ServiceAccountProps) => {
</> </>
} }
> >
<DataLoader loader={loader}> <DataLoader loader={loader} deps={[clientId]}>
{(clientRoles) => ( {(clientRoles) => (
<> <>
{hide ? "" : " "} {hide ? "" : " "}
@ -152,7 +152,7 @@ export const ServiceAccount = ({ clientId }: ServiceAccountProps) => {
}, },
{ title: t("description"), cellFormatters: [emptyFormatter()] }, { title: t("description"), cellFormatters: [emptyFormatter()] },
]} ]}
rows={clientRoles.data} rows={clientRoles}
aria-label="roleList" aria-label="roleList"
> >
<TableHeader /> <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 { Spinner } from "@patternfly/react-core";
import { asyncStateFetch } from "../../context/auth/AdminClient"; import { asyncStateFetch } from "../../context/auth/AdminClient";
type DataLoaderProps<T> = { type DataLoaderProps<T> = {
loader: () => Promise<T>; loader: () => Promise<T>;
deps?: any[]; deps?: DependencyList;
children: ((arg: Result<T>) => any) | React.ReactNode; children: ((arg: T) => any) | React.ReactNode;
};
type Result<T> = {
data: T;
refresh: () => void;
}; };
export function DataLoader<T>(props: DataLoaderProps<T>) { export function DataLoader<T>(props: DataLoaderProps<T>) {
const [data, setData] = useState<{ result: T } | undefined>(undefined); const [data, setData] = useState<T | undefined>();
const [key, setKey] = useState(0);
const refresh = () => setKey(new Date().getTime());
useEffect(() => { useEffect(() => {
return asyncStateFetch( return asyncStateFetch(
() => props.loader(), () => props.loader(),
(result) => setData({ result }) (result) => setData(result)
); );
}, [key]); }, props.deps || []);
if (data) { if (data) {
if (props.children instanceof Function) { if (props.children instanceof Function) {
return props.children({ return props.children(data);
data: data.result,
refresh: refresh,
});
} }
return props.children; return props.children;
} }

View file

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

View file

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

View file

@ -1,5 +1,5 @@
import React, { useState, useContext, useEffect } from "react"; 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 { useTranslation } from "react-i18next";
import { import {
@ -27,13 +27,12 @@ type RealmSelectorProps = {
export const RealmSelector = ({ realmList }: RealmSelectorProps) => { export const RealmSelector = ({ realmList }: RealmSelectorProps) => {
const { realm, setRealm } = useRealm(); const { realm, setRealm } = useRealm();
const whoami = useContext(WhoAmIContext); const { whoAmI } = useContext(WhoAmIContext);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [filteredItems, setFilteredItems] = useState(realmList); const [filteredItems, setFilteredItems] = useState(realmList);
const history = useHistory(); const history = useHistory();
const { t } = useTranslation("common"); const { t } = useTranslation("common");
const { url } = useRouteMatch();
const toUpperCase = (realmName: string) => const toUpperCase = (realmName: string) =>
realmName.charAt(0).toUpperCase() + realmName.slice(1); realmName.charAt(0).toUpperCase() + realmName.slice(1);
@ -49,7 +48,10 @@ export const RealmSelector = ({ realmList }: RealmSelectorProps) => {
<Button <Button
component="div" component="div"
isBlock isBlock
onClick={() => history.push(`${url}/add-realm"`)} onClick={() => {
history.push(`/${realm}/add-realm`);
setOpen(!open);
}}
className={className} className={className}
> >
{t("createRealm")} {t("createRealm")}
@ -85,7 +87,7 @@ export const RealmSelector = ({ realmList }: RealmSelectorProps) => {
const addRealmComponent = ( const addRealmComponent = (
<React.Fragment key="Add Realm"> <React.Fragment key="Add Realm">
{whoami.canCreateRealm() && ( {whoAmI.canCreateRealm() && (
<> <>
<Divider key="divider" /> <Divider key="divider" />
<DropdownItem key="add"> <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 { AccessType } from "keycloak-admin/lib/defs/whoAmIRepresentation";
import { RealmContext } from "../../context/realm-context/RealmContext"; import { RealmContext } from "../../context/realm-context/RealmContext";
@ -18,17 +18,20 @@ export const useAccess = () => useContext(AccessContext);
type AccessProviderProps = { children: React.ReactNode }; type AccessProviderProps = { children: React.ReactNode };
export const AccessContextProvider = ({ children }: AccessProviderProps) => { export const AccessContextProvider = ({ children }: AccessProviderProps) => {
const whoami = useContext(WhoAmIContext); const { whoAmI } = useContext(WhoAmIContext);
const realmCtx = useContext(RealmContext); 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[]) => { 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[]) => { const hasSomeAccess = (...types: AccessType[]) => {
return types.some((type) => type === "anyone" || access().includes(type)); return types.some((type) => type === "anyone" || access.includes(type));
}; };
return ( return (

View file

@ -23,7 +23,7 @@ export const ServerInfoProvider = ({ children }: { children: ReactNode }) => {
return ( return (
<DataLoader loader={loader}> <DataLoader loader={loader}>
{(serverInfo) => ( {(serverInfo) => (
<ServerInfoContext.Provider value={serverInfo.data}> <ServerInfoContext.Provider value={serverInfo}>
{children} {children}
</ServerInfoContext.Provider> </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 i18n from "../../i18n";
import { DataLoader } from "../../components/data-loader/DataLoader"; import { AdminClient, asyncStateFetch } from "../auth/AdminClient";
import { AdminClient } from "../auth/AdminClient";
import { RealmContext } from "../realm-context/RealmContext"; import { RealmContext } from "../realm-context/RealmContext";
import WhoAmIRepresentation, { import WhoAmIRepresentation, {
AccessType, 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 }; type WhoAmIProviderProps = { children: React.ReactNode };
export const WhoAmIContextProvider = ({ children }: WhoAmIProviderProps) => { export const WhoAmIContextProvider = ({ children }: WhoAmIProviderProps) => {
const adminClient = useContext(AdminClient)!; const adminClient = useContext(AdminClient)!;
const { realm, setRealm } = useContext(RealmContext); const { realm, setRealm } = useContext(RealmContext);
const [whoAmI, setWhoAmI] = useState<WhoAmI>(new WhoAmI());
const [key, setKey] = useState(0);
const whoAmILoader = async () => { useEffect(() => {
const whoamiResponse = await adminClient.whoAmI.find({ return asyncStateFetch(
() =>
adminClient.whoAmI.find({
realm: adminClient.keycloak?.realm, realm: adminClient.keycloak?.realm,
}); }),
const whoAmI = new WhoAmI(adminClient.keycloak?.realm, whoamiResponse); (me) => {
const whoAmI = new WhoAmI(adminClient.keycloak?.realm, me);
if (!realm) { if (!realm) {
setRealm(whoAmI.getHomeRealm()); setRealm(whoAmI.getHomeRealm());
} }
return whoAmI; setWhoAmI(whoAmI);
}; }
);
}, [key]);
return ( return (
<DataLoader loader={whoAmILoader}> <WhoAmIContext.Provider value={{ refresh: () => setKey(key + 1), whoAmI }}>
{(whoami) => (
<WhoAmIContext.Provider value={whoami.data}>
{children} {children}
</WhoAmIContext.Provider> </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 { useTranslation } from "react-i18next";
import { import {
PageSection, PageSection,
@ -17,9 +18,12 @@ import { useForm, Controller } from "react-hook-form";
import { ViewHeader } from "../../components/view-header/ViewHeader"; import { ViewHeader } from "../../components/view-header/ViewHeader";
import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation"; import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation";
import { useAdminClient } from "../../context/auth/AdminClient"; import { useAdminClient } from "../../context/auth/AdminClient";
import { WhoAmIContext } from "../../context/whoami/WhoAmI";
export const NewRealmForm = () => { export const NewRealmForm = () => {
const { t } = useTranslation("realm"); const { t } = useTranslation("realm");
const history = useHistory();
const { refresh } = useContext(WhoAmIContext);
const adminClient = useAdminClient(); const adminClient = useAdminClient();
const { addAlert } = useAlerts(); const { addAlert } = useAlerts();
@ -40,6 +44,10 @@ export const NewRealmForm = () => {
try { try {
await adminClient.realms.create(realm); await adminClient.realms.create(realm);
addAlert(t("Realm created"), AlertVariant.success); addAlert(t("Realm created"), AlertVariant.success);
refresh();
//force token update
await adminClient.keycloak?.updateToken(Number.MAX_VALUE);
history.push(`/${realm.realm}`);
} catch (error) { } catch (error) {
addAlert( addAlert(
`${t("Could not create realm:")} '${error}'`, `${t("Could not create realm:")} '${error}'`,