Skip to content

Commit

Permalink
fix(admin): handle error login status (#7646)
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmFly committed Aug 13, 2024
1 parent 0256130 commit fe7825f
Show file tree
Hide file tree
Showing 9 changed files with 107 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export function CreateUserPanel() {

return (
<div className="flex flex-col h-full gap-1">
<div className="flex-grow-0 flex-shrink-0 h-[56px] flex justify-between items-center py-[10px] px-6">
<div className=" flex justify-between items-center py-[10px] px-6">
<Button
type="button"
size="icon"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function EditPanel({

return (
<div className="flex flex-col h-full gap-1">
<div className="flex-grow-0 flex-shrink-0 h-[56px] flex justify-between items-center py-[10px] px-6 ">
<div className=" flex justify-between items-center py-[10px] px-6 ">
<Button
type="button"
size="icon"
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/admin/src/modules/accounts/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function AccountPage() {

return (
<div className=" h-screen flex-1 flex-col flex">
<div className="flex items-center justify-between px-6 py-3 max-md:ml-9 max-md:mt-[2px]">
<div className="flex items-center justify-between px-6 py-3 my-[2px] max-md:ml-9 max-md:mt-[2px]">
<div className="text-base font-medium">Accounts</div>
</div>
<Separator />
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/admin/src/modules/ai/edit-prompt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function EditPrompt({ item }: { item: Prompt }) {

return (
<div className="flex flex-col h-full gap-1">
<div className="flex-grow-0 flex-shrink-0 h-[56px] flex justify-between items-center py-[10px] px-6 ">
<div className="flex justify-between items-center py-[10px] px-6 ">
<Button
type="button"
size="icon"
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/admin/src/modules/ai/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function Ai() {
export function AiPage() {
return (
<div className=" h-screen flex-1 flex-col flex">
<div className="flex items-center justify-between px-6 py-3 max-md:ml-9 max-md:mt-[2px]">
<div className="flex items-center justify-between px-6 py-3 my-[2px] max-md:ml-9 max-md:mt-[2px]">
<div className="text-base font-medium">AI</div>
</div>
<Separator />
Expand Down
53 changes: 47 additions & 6 deletions packages/frontend/admin/src/modules/auth/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
import { Button } from '@affine/admin/components/ui/button';
import { Input } from '@affine/admin/components/ui/input';
import { Label } from '@affine/admin/components/ui/label';
import { FeatureType, getUserFeaturesQuery } from '@affine/graphql';
import { useCallback, useRef } from 'react';
import { useMutateQueryResource } from '@affine/core/hooks/use-mutation';
import { useQuery } from '@affine/core/hooks/use-query';
import {
FeatureType,
getCurrentUserFeaturesQuery,
getUserFeaturesQuery,
serverConfigQuery,
} from '@affine/graphql';
import { useCallback, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';

import logo from './logo.svg';

export function Auth() {
const {
data: { currentUser },
} = useQuery({
query: getCurrentUserFeaturesQuery,
});

const {
data: { serverConfig },
} = useQuery({
query: serverConfigQuery,
});
const revalidate = useMutateQueryResource();
const emailRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
const navigate = useNavigate();
Expand All @@ -24,6 +43,14 @@ export function Auth() {
'Content-Type': 'application/json',
},
})
.then(async response => {
if (!response.ok) {
const data = await response.json();
throw new Error(data.message || 'Failed to login');
}
await revalidate(getCurrentUserFeaturesQuery);
return response.json();
})
.then(() =>
fetch('/graphql', {
method: 'POST',
Expand All @@ -45,6 +72,7 @@ export function Auth() {
},
}) => {
if (features.includes(FeatureType.Admin)) {
toast.success('Logged in successfully');
navigate('/admin');
} else {
toast.error('You are not an admin');
Expand All @@ -54,9 +82,22 @@ export function Auth() {
.catch(err => {
toast.error(`Failed to login: ${err.message}`);
});
}, [navigate]);
}, [navigate, revalidate]);

useEffect(() => {
if (serverConfig.initialized === false) {
navigate('/admin/setup');
return;
} else if (!currentUser) {
return;
} else if (!currentUser?.features.includes?.(FeatureType.Admin)) {
toast.error('You are not an admin, please login the admin account.');
return;
}
}, [currentUser, navigate, serverConfig.initialized]);

return (
<div className="w-full lg:grid lg:min-h-[600px] lg:grid-cols-2 xl:min-h-[800px]">
<div className="w-full lg:grid lg:min-h-[600px] lg:grid-cols-2 xl:min-h-[800px] h-screen">
<div className="flex items-center justify-center py-12">
<div className="mx-auto grid w-[350px] gap-6">
<div className="grid gap-2 text-center">
Expand Down Expand Up @@ -88,11 +129,11 @@ export function Auth() {
</div>
</div>
</div>
<div className="hidden bg-muted lg:block">
<div className="hidden bg-muted lg:flex lg:justify-center">
<img
src={logo}
alt="Image"
className="w-1/2 h-1/2 object-cover dark:brightness-[0.2] dark:grayscale relative top-1/4 left-1/4"
className="h-1/2 object-cover dark:brightness-[0.2] dark:grayscale relative top-1/4 "
/>
</div>
</div>
Expand Down
38 changes: 38 additions & 0 deletions packages/frontend/admin/src/modules/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import {
import { Separator } from '@affine/admin/components/ui/separator';
import { TooltipProvider } from '@affine/admin/components/ui/tooltip';
import { cn } from '@affine/admin/utils';
import { useQuery } from '@affine/core/hooks/use-query';
import {
FeatureType,
getCurrentUserFeaturesQuery,
serverConfigQuery,
} from '@affine/graphql';
import { AlignJustifyIcon } from 'lucide-react';
import type { ReactNode, RefObject } from 'react';
import {
Expand All @@ -17,6 +23,8 @@ import {
useState,
} from 'react';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';

import { Button } from '../components/ui/button';
import {
Expand Down Expand Up @@ -114,6 +122,36 @@ export function Layout({ content }: LayoutProps) {
[closePanel, openPanel]
);

const {
data: { serverConfig },
} = useQuery({
query: serverConfigQuery,
});
const {
data: { currentUser },
} = useQuery({
query: getCurrentUserFeaturesQuery,
});
const navigate = useNavigate();

useEffect(() => {
if (serverConfig.initialized === false) {
navigate('/admin/setup');
return;
} else if (!currentUser) {
navigate('/admin/auth');
return;
} else if (!currentUser?.features.includes?.(FeatureType.Admin)) {
toast.error('You are not an admin, please login the admin account.');
navigate('/admin/auth');
return;
}
}, [currentUser, navigate, serverConfig.initialized]);

if (serverConfig.initialized === false || !currentUser) {
return null;
}

return (
<RightPanelContext.Provider
value={{
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/admin/src/modules/nav/user-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export function UserDropdown() {
method: 'POST',
})
.then(() => {
toast.success('Logged out successfully');
navigate('/admin/auth');
})
.catch(err => {
Expand Down
22 changes: 16 additions & 6 deletions packages/frontend/admin/src/modules/setup/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
CarouselItem,
} from '@affine/admin/components/ui/carousel';
import { validateEmailAndPassword } from '@affine/admin/utils';
import { useMutateQueryResource } from '@affine/core/hooks/use-mutation';
import { useQuery } from '@affine/core/hooks/use-query';
import { serverConfigQuery } from '@affine/graphql';
import { useCallback, useEffect, useState } from 'react';
Expand Down Expand Up @@ -81,6 +82,8 @@ export const Form = () => {
const disableContinue =
(!nameValue || !emailValue || !passwordValue) && isCreateAdminStep;

const revalidate = useMutateQueryResource();

useEffect(() => {
if (!api) {
return;
Expand All @@ -92,11 +95,9 @@ export const Form = () => {
api.on('select', () => {
setCurrent(api.selectedScrollSnap() + 1);
});
}, [api]);
}, [api, data.serverConfig.initialized, navigate]);

const createAdmin = useCallback(async () => {
if (invalidEmail || invalidPassword) return;

try {
const createResponse = await fetch('/api/setup/create-admin-user', {
method: 'POST',
Expand All @@ -115,13 +116,14 @@ export const Form = () => {
}

await createResponse.json();
await revalidate(serverConfigQuery);
toast.success('Admin account created successfully.');
} catch (err) {
toast.error((err as Error).message);
console.error(err);
throw err;
}
}, [emailValue, invalidEmail, invalidPassword, passwordValue]);
}, [emailValue, passwordValue, revalidate]);

const onNext = useCallback(async () => {
if (isCreateAdminStep) {
Expand All @@ -138,8 +140,12 @@ export const Form = () => {
} else {
try {
await createAdmin();
setInvalidEmail(false);
setInvalidPassword(false);
} catch (e) {
console.error(e);
setInvalidEmail(true);
setInvalidPassword(true);
return;
}
}
Expand All @@ -164,10 +170,14 @@ export const Form = () => {

const onPrevious = useCallback(() => {
if (current === count) {
return navigate('/admin', { replace: true });
if (data.serverConfig.initialized === true) {
return navigate('/admin', { replace: true });
}
toast.error('Goto Admin Panel failed, please try again.');
return;
}
api?.scrollPrev();
}, [api, count, current, navigate]);
}, [api, count, current, data.serverConfig.initialized, navigate]);

return (
<div className="flex flex-col justify-between h-full w-full lg:pl-36 max-lg:items-center ">
Expand Down

0 comments on commit fe7825f

Please sign in to comment.