Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ui): prevent reload after logout #3149

Merged
merged 3 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
941 changes: 941 additions & 0 deletions ui/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"package-changed": "^3.0.0",
"playwright": "^1.43.1",
"postcss": "^8.4.33",
Expand Down
4 changes: 3 additions & 1 deletion ui/src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Bars3BottomLeftIcon } from '@heroicons/react/24/outline';
import { useSelector } from 'react-redux';
import { selectConfig, selectInfo, selectReadonly } from '~/app/meta/metaSlice';
import { useSession } from '~/data/hooks/session';
import { getUser } from '~/data/user';
import Notifications from './header/Notifications';
import ReadOnly from './header/ReadOnly';
import UserProfile from './header/UserProfile';
Expand All @@ -18,6 +19,7 @@ export default function Header(props: HeaderProps) {
const { session } = useSession();
const { ui } = useSelector(selectConfig);
const topbarStyle = { backgroundColor: ui.topbar?.color };
const user = getUser(session);

return (
<div className="sticky top-0 z-20 flex h-16 flex-shrink-0 bg-gray-950 dark:border-b dark:border-b-white/20 dark:md:border-b-0">
Expand All @@ -44,7 +46,7 @@ export default function Header(props: HeaderProps) {
{info && info.updateAvailable && <Notifications info={info} />}

{/* user profile */}
{session && session.self && <UserProfile session={session.self} />}
{user && <UserProfile user={user} />}
</div>
</div>
</div>
Expand Down
34 changes: 14 additions & 20 deletions ui/src/components/SessionProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,43 +35,37 @@ export default function SessionProvider({
};

const loadSession = async () => {
try {
await getInfo();
} catch (err) {
// if we can't get the info, we're not logged in
// or there was an error, either way, clear the session so we redirect
// to the login page
clearSession();
return;
}

if (session) {
clearSessionIfNecessary();
if (session) {
return;
}
}

let newSession = {
const newSession = {
required: true,
authenticated: false
} as Session;

try {
await getInfo();
} catch (err) {
// if we can't get the info, we're not logged in
// or there was an error, either way, clear the session so we redirect
// to the login page
clearSession();
return;
}

try {
const self: IAuthOIDCInternal | IAuthGithubInternal | IAuthJWTInternal =
await getAuthSelf();
newSession = {
authenticated: true,
required: true,
self: self
};
newSession.authenticated = true;
newSession.self = self;
} catch (err) {
// if we can't get the self info and we got here then auth is likely not enabled
// so we can just return
newSession = {
authenticated: false,
required: false
};
newSession.required = false;
} finally {
if (newSession) {
setSession(newSession);
Expand Down
75 changes: 22 additions & 53 deletions ui/src/components/header/UserProfile.tsx
Original file line number Diff line number Diff line change
@@ -1,65 +1,32 @@
import { Menu, Transition } from '@headlessui/react';
import { UserCircleIcon } from '@heroicons/react/24/solid';
import { Fragment } from 'react';
import { expireAuthSelf } from '~/data/api';
import { useError } from '~/data/hooks/error';
import { useSession } from '~/data/hooks/session';
import { IAuthGithubInternal } from '~/types/auth/Github';
import { IAuthJWTInternal } from '~/types/auth/JWT';
import { IAuthOIDCInternal } from '~/types/auth/OIDC';
import { User } from '~/types/auth/User';
import { cls } from '~/utils/helpers';
import { useNavigate } from 'react-router-dom';
import { expireAuthSelf } from '~/data/api';

type UserProfileProps = {
session?: IAuthOIDCInternal | IAuthGithubInternal | IAuthJWTInternal;
user: User;
};

export default function UserProfile(props: UserProfileProps) {
const { session } = props;
const { user } = props;
const { setError } = useError();
const { clearSession } = useSession();

let name: string | undefined;
let login: string | undefined;
let imgURL: string | undefined;
let logoutURL = '';

if (session) {
const authMethods = ['github', 'oidc', 'jwt'];
const authMethod = authMethods.find(
(method) => `METHOD_${method.toLocaleUpperCase()}` === session.method
);

if (authMethod) {
const metadata = session.metadata;

const authMethodNameKey = `io.flipt.auth.${authMethod}.name`;
name = metadata[authMethodNameKey as keyof typeof metadata] ?? 'User';

const authMethodPictureKey = `io.flipt.auth.${authMethod}.picture`;
if (metadata[authMethodPictureKey as keyof typeof metadata]) {
imgURL = metadata[authMethodPictureKey as keyof typeof metadata];
}

const authMethodPreferredUsernameKey = `io.flipt.auth.${authMethod}.preferred_username`;
if (metadata[authMethodPreferredUsernameKey as keyof typeof metadata]) {
login =
metadata[authMethodPreferredUsernameKey as keyof typeof metadata];
}

const authMethodIssuerKey = `io.flipt.auth.${authMethod}.issuer`;
if (metadata[authMethodIssuerKey as keyof typeof metadata]) {
const logoutURI =
metadata[authMethodIssuerKey as keyof typeof metadata];
logoutURL = `//${logoutURI}`;
}
erka marked this conversation as resolved.
Show resolved Hide resolved
}
}

const navigate = useNavigate();
const logout = async () => {
try {
await expireAuthSelf();
clearSession();
window.location.href = logoutURL;
if (user?.issuer) {
window.location.href = `//${user.issuer}`;
} else {
navigate('/login');
}
} catch (err) {
setError(err);
}
Expand All @@ -70,16 +37,16 @@ export default function UserProfile(props: UserProfileProps) {
<div>
<Menu.Button className="nightwind-prevent bg-white flex max-w-xs items-center rounded-full text-sm ring-1 ring-white hover:ring-2 hover:ring-violet-500/80 focus:outline-none focus:ring-1 focus:ring-violet-500 focus:ring-offset-2">
<span className="sr-only">Open user menu</span>
{imgURL && (
{user.imgURL && (
<img
className="h-7 w-7 rounded-full"
src={imgURL}
alt={name}
title={name}
src={user.imgURL}
alt={user.name}
title={user.name}
referrerPolicy="no-referrer"
/>
)}
{!imgURL && (
{!user.imgURL && (
<UserCircleIcon
className="nightwind-prevent text-gray-800 h-6 w-6 rounded-full"
aria-hidden="true"
Expand All @@ -97,7 +64,7 @@ export default function UserProfile(props: UserProfileProps) {
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items className="bg-white absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
{(name || login) && (
{(user.name || user.login) && (
<Menu.Item disabled>
{({ active }) => (
<span
Expand All @@ -106,9 +73,11 @@ export default function UserProfile(props: UserProfileProps) {
{ 'bg-gray-100': active }
)}
>
<span className="text-gray-600 flex-1 text-sm">{name}</span>
{login && (
<span className="text-gray-400 text-xs">{login}</span>
<span className="text-gray-600 flex-1 text-sm">
{user.name}
</span>
{user.login && (
<span className="text-gray-400 text-xs">{user.login}</span>
)}
</span>
)}
Expand Down
59 changes: 59 additions & 0 deletions ui/src/data/api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* @jest-environment jsdom
* @jest-environment-options {"url": "https://test/"}
*/

import { checkResponse, sessionKey } from './api';

describe('checkResponse', () => {
let originalLocation: Location;
beforeEach(() => {
originalLocation = window.location;
delete (window as any).location;
(window as any).location = {
href: '',
reload: () => {}
};

Object.defineProperty(window.location, 'href', {
writable: true,
value: 'https://test/'
});
jest.spyOn(window.location, 'reload').mockImplementation(() => {});
});

afterEach(() => {
window.location = originalLocation;
jest.restoreAllMocks();
});

it('should not change the state', () => {
window.localStorage.setItem(sessionKey, 'value');
checkResponse({ status: 200, ok: true } as Response);
expect(window.location.href).toEqual('https://test/');
checkResponse({ status: 404, ok: false } as Response);
expect(window.location.href).toEqual('https://test/');
expect(window.localStorage.getItem(sessionKey)).toEqual('value');
});

it('should reload if method oauth', () => {
window.localStorage.setItem(
sessionKey,
'{"authenticated":true,"required":true,"self":{"method":"METHOD_GITHUB", "metadata": {}}}'
);
checkResponse({ status: 401, ok: false } as Response);
expect(window.location.href).toEqual('https://test/');
expect(window.localStorage.getItem(sessionKey)).toBe(null);
expect(window.location.reload).toHaveBeenCalled();
});

it('should redirect back to issuer for jwt auth method', () => {
window.localStorage.setItem(
sessionKey,
'{"authenticated":true,"required":true,"self":{"method":"METHOD_JWT", "metadata": {"io.flipt.auth.jwt.issuer":"flipt.issuer"}}}'
);
checkResponse({ status: 401, ok: false } as Response);
expect(window.location.href).toEqual('//flipt.issuer');
expect(window.localStorage.getItem(sessionKey)).toBe(null);
});
});
25 changes: 24 additions & 1 deletion ui/src/data/api.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
import { FlagType } from '~/types/Flag';

import { IAuthGithubInternal } from '~/types/auth/Github';
import { IAuthJWTInternal } from '~/types/auth/JWT';
import { IAuthOIDCInternal } from '~/types/auth/OIDC';
import { getUser } from '~/data/user';

export const apiURL = 'api/v1';
export const authURL = 'auth/v1';
export const evaluateURL = 'evaluate/v1';
export const metaURL = 'meta';
export const internalURL = 'internal/v1';

const csrfTokenHeaderKey = 'x-csrf-token';
const sessionKey = 'session';
export const sessionKey = 'session';

export type Session = {
required: boolean;
authenticated: boolean;
self?: IAuthOIDCInternal | IAuthGithubInternal | IAuthJWTInternal;
};

export class APIError extends Error {
status: number;
Expand All @@ -33,8 +44,20 @@ function headerCsrf(): Record<string, string> {
export function checkResponse(response: Response) {
if (!response.ok) {
if (response.status === 401) {
const session = window.localStorage.getItem(sessionKey);
window.localStorage.removeItem(csrfTokenHeaderKey);
window.localStorage.removeItem(sessionKey);
if (session) {
try {
const user = getUser(JSON.parse(session));
if (user?.issuer) {
window.location.href = `//${user.issuer}`;
return;
}
} catch (e) {
//
}
}
window.location.reload();
}
}
Expand Down
1 change: 1 addition & 0 deletions ui/src/data/hooks/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ const useStorage = (
} catch (error) {
console.error(error);
}
setValue(initialValue);
};

return [storedValue, setValue, clearValue];
Expand Down
38 changes: 38 additions & 0 deletions ui/src/data/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Session } from '~/types/auth/Session';
import { User } from '~/types/auth/User';

export function getUser(session?: Session): User | undefined {
if (session?.self) {
const self = session.self;
const u = {} as User;
const authMethods = ['github', 'oidc', 'jwt'];
const authMethod = authMethods.find(
(method) => `METHOD_${method.toLocaleUpperCase()}` === self.method
);

if (authMethod) {
u.authMethod = authMethod;
const metadata = self.metadata;

const authMethodNameKey = `io.flipt.auth.${authMethod}.name`;
u.name = metadata[authMethodNameKey as keyof typeof metadata] ?? 'User';

const authMethodPictureKey = `io.flipt.auth.${authMethod}.picture`;
if (metadata[authMethodPictureKey as keyof typeof metadata]) {
u.imgURL = metadata[authMethodPictureKey as keyof typeof metadata];
}

const authMethodPreferredUsernameKey = `io.flipt.auth.${authMethod}.preferred_username`;
if (metadata[authMethodPreferredUsernameKey as keyof typeof metadata]) {
u.login =
metadata[authMethodPreferredUsernameKey as keyof typeof metadata];
}
const authMethodIssuerKey = `io.flipt.auth.${authMethod}.issuer`;
if (metadata[authMethodIssuerKey as keyof typeof metadata]) {
u.issuer = metadata[authMethodIssuerKey as keyof typeof metadata];
}
}
return u;
}
return undefined;
}
9 changes: 9 additions & 0 deletions ui/src/types/auth/Session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { IAuthGithubInternal } from '~/types/auth/Github';
import { IAuthJWTInternal } from '~/types/auth/JWT';
import { IAuthOIDCInternal } from '~/types/auth/OIDC';

export type Session = {
required: boolean;
authenticated: boolean;
self?: IAuthOIDCInternal | IAuthGithubInternal | IAuthJWTInternal;
};
7 changes: 7 additions & 0 deletions ui/src/types/auth/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export type User = {
name: string | undefined;
login: string | undefined;
imgURL: string | undefined;
issuer: string | undefined;
authMethod: string | undefined;
};
Loading