Skip to content

Commit

Permalink
Experiment use login api
Browse files Browse the repository at this point in the history
  • Loading branch information
mdellweg committed Dec 18, 2024
1 parent 5bf774d commit 891050e
Show file tree
Hide file tree
Showing 14 changed files with 209 additions and 102 deletions.
1 change: 1 addition & 0 deletions config/start.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ module.exports = webpackBase({
DEV_PROXY: {
'/api/': proxyTarget,
'/assets/': proxyTarget,
'/auth/': proxyTarget,
'/extensions/': proxyTarget,
'/pulp/': proxyTarget,
'/static/rest_framework/': proxyTarget,
Expand Down
6 changes: 4 additions & 2 deletions src/api/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ export class BaseAPI {

constructor() {
this.http = axios.create({
// adapter + withCredentials ensures no popup on http basic auth fail
adapter: 'fetch',
withCredentials: false,
// Allow session cookie to be used.
withCredentials: true,
// Don't let the browser ask for username/password.
headers: { 'X-Request-With': 'XMLHttpRequest' },

// baseURL gets set in PulpAPI
paramsSerializer: {
Expand Down
8 changes: 0 additions & 8 deletions src/api/pulp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,6 @@ export class PulpAPI extends BaseAPI {
super();

this.http.interceptors.request.use((request) => {
if (!request.auth) {
request.auth = JSON.parse(
window.sessionStorage.credentials ||
window.localStorage.credentials ||
'{}',
);
}

request.baseURL = config.API_BASE_PATH;
request.headers['X-CSRFToken'] = Cookies.get('csrftoken');

Expand Down
24 changes: 12 additions & 12 deletions src/app-context.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
import { type ReactNode, createContext, useContext, useState } from 'react';
import { type AlertType } from 'src/components';
import { useUserContext } from './user-context';

export interface IUser {
username?: string;
}
export interface IAppContextType {
alerts: AlertType[];
featureFlags; // deprecated
hasPermission: (name: string) => boolean;
queueAlert: (alert: AlertType) => void;
setAlerts: (alerts: AlertType[]) => void;
settings; // deprecated
user; // deprecated
user: IUser;
}

export const AppContext = createContext<IAppContextType>(undefined);
export const useAppContext = () => useContext(AppContext);

export const AppContextProvider = ({ children }: { children: ReactNode }) => {
export const AppContextProvider = ({
user,
children,
}: {
user: IUser;
children: ReactNode;
}) => {
const [alerts, setAlerts] = useState<AlertType[]>([]);
const { credentials } = useUserContext();

// hub compat for now
const featureFlags = {
Expand Down Expand Up @@ -49,14 +56,7 @@ export const AppContextProvider = ({ children }: { children: ReactNode }) => {
queueAlert,
setAlerts,
settings,
// FIXME: hack
user: credentials
? {
username: credentials.username,
groups: [],
model_permissions: {},
}
: null,
user,
}}
>
{children}
Expand Down
36 changes: 22 additions & 14 deletions src/app-routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Trans } from '@lingui/react/macro';
import { Banner, Flex, FlexItem } from '@patternfly/react-core';
import WrenchIcon from '@patternfly/react-icons/dist/esm/icons/wrench-icon';
import { type ElementType } from 'react';
import { Navigate, useLocation } from 'react-router';
import { Navigate, redirect, useLocation } from 'react-router';
import { ErrorBoundary, ExternalLink, NotFound } from 'src/components';
import {
AboutProject,
Expand Down Expand Up @@ -31,7 +31,6 @@ import {
ExecutionEnvironmentRegistryList,
GroupDetail,
GroupList,
LoginPage,
MultiSearch,
MyImports,
MyNamespaces,
Expand All @@ -50,11 +49,10 @@ import {
UserList,
UserProfile,
} from 'src/containers';
import { StandaloneLayout } from 'src/layout';
import { Paths, formatPath } from 'src/paths';
import { config } from 'src/ui-config';
import { loginURL } from 'src/utilities';
import { useUserContext } from './user-context';
import { useAppContext } from './app-context';

interface IRouteConfig {
beta?: boolean;
Expand Down Expand Up @@ -211,12 +209,6 @@ const routes: IRouteConfig[] = [
path: Paths.ansible.namespace.mine,
beta: true,
},
{
component: LoginPage,
path: Paths.meta.login,
noAuth: true,
beta: true,
},
{
component: CollectionDocs,
path: Paths.ansible.collection.docs_page,
Expand Down Expand Up @@ -301,10 +293,10 @@ const AuthHandler = ({
noAuth,
path,
}: IRouteConfig) => {
const { credentials } = useUserContext();
const { user } = useAppContext();
const { pathname } = useLocation();

if (!credentials && !noAuth) {
if (!user.username && !noAuth) {
// NOTE: also update LoginLink when changing this
if (config.UI_EXTERNAL_LOGIN_URI) {
window.location.replace(loginURL(pathname));
Expand Down Expand Up @@ -358,16 +350,32 @@ const appRoutes = () =>
...rest,
}));

const convert = (m) => {
const {
default: Component,
clientLoader: loader,
clientAction: action,
...rest
} = m;
return { ...rest, loader, action, Component };
};

export const dataRoutes = [
{
element: <StandaloneLayout />,
id: 'root',
lazy: () => import('src/routes/root').then((m) => convert(m)),
children: [
{
errorElement: <ErrorBoundary />,
children: [
{
index: true,
element: <Navigate to={formatPath(Paths.core.status)} />,
loader: () => redirect(formatPath(Paths.core.status)),
},
{
path: 'login',
id: 'login',
lazy: () => import('src/routes/login').then((m) => convert(m)),
},
...appRoutes(),
// "No matching route" is not handled by the error boundary.
Expand Down
8 changes: 4 additions & 4 deletions src/components/delete-user-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Trans } from '@lingui/react/macro';
import { useState } from 'react';
import { UserAPI, type UserType } from 'src/api';
import { DeleteModal } from 'src/components';
import { useUserContext } from 'src/user-context';
import { useAppContext } from 'src/app-context';
import { jsxErrorMessage, mapErrorMessages } from 'src/utilities';

interface IProps {
Expand All @@ -20,7 +20,7 @@ export const DeleteUserModal = ({
user,
}: IProps) => {
const [waiting, setWaiting] = useState(false);
const { credentials } = useUserContext();
const { user: currentUser } = useAppContext();

if (!user || !isOpen) {
return null;
Expand All @@ -30,11 +30,11 @@ export const DeleteUserModal = ({
<DeleteModal
cancelAction={() => closeModal(false)}
deleteAction={() => deleteUser()}
isDisabled={waiting || user.username === credentials.username}
isDisabled={waiting || user.username === currentUser.username}
spinner={waiting}
title={t`Delete user?`}
>
{user.username === credentials.username ? (
{user.username === currentUser.username ? (
t`Deleting yourself is not allowed.`
) : (
<Trans>
Expand Down
2 changes: 1 addition & 1 deletion src/components/error-boundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const ErrorBoundary = () => {
<h1>
{error.status} {error.statusText}
</h1>
<p>{error.data}</p>
<p>{error.data.toString()}</p>
</>
);
} else if (error instanceof Error) {
Expand Down
16 changes: 3 additions & 13 deletions src/containers/settings/user-profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Trans } from '@lingui/react/macro';
import { Button } from '@patternfly/react-core';
import { useEffect, useState } from 'react';
import { UserAPI, type UserType } from 'src/api';
import { useAppContext } from 'src/app-context';
import {
AlertList,
type AlertType,
Expand All @@ -11,7 +12,6 @@ import {
UserFormPage,
closeAlert,
} from 'src/components';
import { useUserContext } from 'src/user-context';
import {
type ErrorMessagesType,
type RouteProps,
Expand All @@ -28,10 +28,8 @@ function UserProfile(_props: RouteProps) {
const [user, setUser] = useState<UserType>();

const {
credentials: { username },
updateUsername,
updatePassword,
} = useUserContext();
user: { username },
} = useAppContext();

const addAlert = (alert: AlertType) => {
setAlerts([...alerts, alert]);
Expand Down Expand Up @@ -66,14 +64,6 @@ function UserProfile(_props: RouteProps) {
variant: 'success',
title: <Trans>Saved changes to user &quot;{username}&quot;.</Trans>,
});

// update saved credentials when password of logged user is changed
if (user.password) {
updatePassword(user.password);
}
if (username !== user.username) {
updateUsername(user.username);
}
})
.catch((err) => setErrorMessages(mapErrorMessages(err)));

Expand Down
17 changes: 0 additions & 17 deletions src/containers/user-management/user-edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
UserFormPage,
} from 'src/components';
import { Paths, formatPath } from 'src/paths';
import { useUserContext } from 'src/user-context';
import {
type ErrorMessagesType,
type RouteProps,
Expand All @@ -19,23 +18,15 @@ import {

function UserEdit(props: RouteProps) {
const [errorMessages, setErrorMessages] = useState<ErrorMessagesType>({});
const [initialState, setInitialState] = useState<UserType>();
const [redirect, setRedirect] = useState<string>();
const [unauthorized, setUnauthorized] = useState<boolean>(false);
const [user, setUser] = useState<UserType>();

const {
credentials: { username },
updateUsername,
updatePassword,
} = useUserContext();

const id = props.routeParams.user_id;
useEffect(() => {
UserAPI.get(id)
.then(({ data: result }) => {
const extendedResult = { ...result, password: '' };
setInitialState({ ...extendedResult });
setUser(extendedResult);
setUnauthorized(false);
})
Expand All @@ -45,14 +36,6 @@ function UserEdit(props: RouteProps) {
const saveUser = () =>
UserAPI.saveUser(user)
.then(() => {
// update saved credentials when password of logged user is changed
if (initialState.username === username && user.password) {
updatePassword(user.password);
}
if (initialState.username === username && username !== user.username) {
updateUsername(user.username);
}

setRedirect(formatPath(Paths.core.user.list));
})
.catch((err) => setErrorMessages(mapErrorMessages(err)));
Expand Down
10 changes: 1 addition & 9 deletions src/entrypoint.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,10 @@ import { StrictMode, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider, createBrowserRouter } from 'react-router';
import { Alert, LoadingSpinner } from 'src/components';
import { AppContextProvider } from './app-context';
import { dataRoutes } from './app-routes';
import './darkmode';
import './l10n';
import { configFallback, configPromise } from './ui-config';
import { UserContextProvider } from './user-context';

// App entrypoint

Expand Down Expand Up @@ -97,11 +95,5 @@ function LoadConfig(_props) {
basename: config.UI_BASE_PATH,
});

return (
<UserContextProvider>
<AppContextProvider>
<RouterProvider router={router} />
</AppContextProvider>
</UserContextProvider>
);
return <RouterProvider router={router} />;
}
Loading

0 comments on commit 891050e

Please sign in to comment.