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

feat(dashboard): add login redirect from old link #134

Merged
merged 1 commit into from
Sep 3, 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
18 changes: 9 additions & 9 deletions dashboard/app/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ export type ClientOptions<
body: Body extends ComponentSchema ? components['schemas'][Body] : undefined;
query: Record<string, string | number | boolean | undefined>;
method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
noRedirect: boolean;
noThrow: boolean;
shouldRedirect: boolean;
shouldThrow: boolean;
pathKey: string;
}>;

Expand All @@ -54,8 +54,8 @@ const client = async (
{
body,
method = 'GET',
noRedirect,
noThrow = false,
shouldRedirect = true,
shouldThrow = true,
pathKey,
query,
}: ClientOptions,
Expand Down Expand Up @@ -88,15 +88,15 @@ const client = async (
...(body !== undefined && { body: JSON.stringify(body) }),
});

if (!res.ok && !noThrow) {
if (!res.ok && shouldThrow) {
// If the user is not logged in, redirect to the login page
if (res.status === 401 && !noRedirect) {
throw expireSession(noRedirect);
if (res.status === 401 && shouldRedirect) {
throw expireSession(shouldRedirect);
}

// If it is 401 and noRedirect is true, do not throw anything but expire the invalid session
if (res.status === 401 && noRedirect) {
expireSession(noRedirect);
if (res.status === 401 && !shouldRedirect) {
expireSession(!shouldRedirect);
return res;
}

Expand Down
17 changes: 1 addition & 16 deletions dashboard/app/api/user.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { hasSession } from '@/utils/cookies';
import { redirect } from '@remix-run/react';
import { type ClientOptions, type DataResponse, client } from './client';

const userGet = async (
Expand All @@ -23,17 +21,4 @@ const userUpdate = async (
return { data: await res.json(), res };
};

const userLoggedIn = async () => {
// If the user is already logged in, redirect them to the dashboard.
if (hasSession()) {
// Check if session hasn't been revoked.
const res = await client('/user', { method: 'GET' });
if (res.ok) {
return;
}
}

throw redirect('/login');
};

export { userGet, userLoggedIn, userUpdate, userUsageGet };
export { userGet, userUpdate, userUsageGet };
3 changes: 0 additions & 3 deletions dashboard/app/routes/$hostname.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
} from '@remix-run/react';
import { useMemo } from 'react';

import { userLoggedIn } from '@/api/user';
import { websiteList } from '@/api/websites';
import { Chart } from '@/components/stats/Chart';
import { Filters } from '@/components/stats/Filter';
Expand All @@ -25,8 +24,6 @@ export const clientLoader = async ({
request,
params,
}: ClientLoaderFunctionArgs) => {
await userLoggedIn();

// Check chart param for the chart data to display
const searchParams = new URL(request.url).searchParams;
const chart = searchParams.get('chart[stat]');
Expand Down
3 changes: 0 additions & 3 deletions dashboard/app/routes/_index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import * as v from 'valibot';
import isFQDN from 'validator/lib/isFQDN';

import type { components } from '@/api/types';
import { userLoggedIn } from '@/api/user';
import { websiteCreate, websiteList } from '@/api/websites';
import { Button } from '@/components/Button';
import { TextInput } from '@/components/Input';
Expand All @@ -36,8 +35,6 @@ export const meta: MetaFunction = () => {
};

export const clientLoader = async () => {
await userLoggedIn();

const { data, res } = await websiteList({ query: { summary: true } });

if (!res.ok || !data) {
Expand Down
13 changes: 10 additions & 3 deletions dashboard/app/routes/login._index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const clientLoader = async () => {
username: 'admin',
password: 'CHANGE_ME_ON_FIRST_LOGIN',
},
noThrow: true,
shouldThrow: false,
});

if (!res.ok) {
Expand All @@ -46,7 +46,7 @@ export const clientLoader = async () => {
// If the user is already logged in, redirect them to the dashboard.
if (hasSession()) {
// Check if session hasn't been revoked
await userGet({ noRedirect: true });
await userGet({ shouldRedirect: false });
return redirect('/');
}

Expand Down Expand Up @@ -74,7 +74,7 @@ export const clientAction = async ({ request }: ClientActionFunctionArgs) => {
username,
password,
},
noThrow: true,
shouldThrow: false,
});

if (!res.ok) {
Expand All @@ -98,6 +98,13 @@ export const clientAction = async ({ request }: ClientActionFunctionArgs) => {
// Set logged in cookie
document.cookie = LOGGED_IN_COOKIE;

// If user has redirect query param, redirect them to that URL
const url = new URL(request.url);
const redirectPathname = url.searchParams.get('redirect');
if (redirectPathname) {
return redirect(redirectPathname);
}

return redirect('/');
};

Expand Down
2 changes: 1 addition & 1 deletion dashboard/app/routes/settings.account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const clientAction = async ({ request }: ClientActionFunctionArgs) => {
language: 'en',
},
},
noThrow: true,
shouldThrow: false,
});
res = update.res;
break;
Expand Down
2 changes: 1 addition & 1 deletion dashboard/app/routes/settings.tracker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export const clientAction = async ({ request }: ClientActionFunctionArgs) => {
) as components['schemas']['UserGet']['settings']['script_type'],
},
},
noThrow: true,
shouldThrow: false,
});
res = update.res;
break;
Expand Down
6 changes: 0 additions & 6 deletions dashboard/app/routes/settings.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import { Outlet } from '@remix-run/react';

import { userLoggedIn } from '@/api/user';
import { InnerHeader } from '@/components/layout/InnerHeader';
import { SettingsLayout } from '@/components/settings/Layout';

export const clientLoader = async () => {
await userLoggedIn();
return null;
};

export default function Index() {
return (
<>
Expand Down
2 changes: 1 addition & 1 deletion dashboard/app/routes/settings.websites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const clientAction = async ({ request }: ClientActionFunctionArgs) => {
case 'delete': {
const deleteWebsite = await websiteDelete({
pathKey: getString(body, 'hostname'),
noThrow: true,
shouldThrow: false,
});

res = deleteWebsite.res;
Expand Down
15 changes: 13 additions & 2 deletions dashboard/app/utils/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,20 @@ const hasSession = () =>
.split(';')
.some((c) => c.trim().startsWith(`${LOGGED_IN_NAME}=`));

const expireSession = (noRedirect?: boolean) => {
const expireSession = (shouldRedirect = true) => {
// Expire the logged-in cookie
document.cookie = EXPIRE_LOGGED_IN;
if (!noRedirect) redirect('/login');

// Check if we should redirect the user to the login page
// and whether to include the current path as a redirect parameter
if (shouldRedirect) {
const currentPath = window.location.pathname;
if (currentPath !== '/' && currentPath !== '/login') {
return redirect(`/login?redirect=${currentPath}`);
}

return redirect('/login');
}
};

export { EXPIRE_LOGGED_IN, expireSession, hasSession, LOGGED_IN_COOKIE };
Loading