link-stack/apps/metamigo-frontend/app/_components/AdminLogin.tsx

89 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-06-28 12:55:24 +00:00
"use client";
2023-02-13 12:41:30 +00:00
import { FC, useEffect } from "react";
2023-05-25 07:03:57 +00:00
import { CircularProgress, Typography, Grid } from "@mui/material";
2023-02-13 12:41:30 +00:00
import { signIn, signOut, getSession } from "next-auth/react";
import { useLogin, useTranslate } from "react-admin";
export const authProvider = {
2023-03-15 12:17:43 +00:00
login(o: any) {
2023-02-13 12:41:30 +00:00
if (o.ok) return Promise.resolve();
return Promise.reject();
},
2023-03-15 12:17:43 +00:00
async logout() {
2023-02-13 12:41:30 +00:00
const session = await getSession();
if (session) {
await signOut();
}
},
2023-03-15 12:17:43 +00:00
checkError(e: any) {
2023-02-13 12:41:30 +00:00
if (e.graphQLErrors && e.graphQLErrors.length > 0) {
2023-03-15 12:17:43 +00:00
const permDenied = e.graphQLErrors.some((e: any) =>
e.message.match(/.*permission denied.*/)
);
2023-02-13 12:41:30 +00:00
if (permDenied)
// eslint-disable-next-line prefer-promise-reject-errors
return Promise.reject({ message: "auth.permissionDenied" });
}
if (e.networkError && e.networkError.statusCode === 401) {
return Promise.reject();
}
2023-03-14 17:40:24 +00:00
return Promise.resolve();
2023-02-13 12:41:30 +00:00
},
2023-03-15 12:17:43 +00:00
async checkAuth() {
2023-02-13 12:41:30 +00:00
const session = await getSession();
if (!session) {
2023-03-15 12:17:43 +00:00
throw new Error("Invalid session");
2023-02-13 12:41:30 +00:00
}
},
2023-03-15 12:17:43 +00:00
async getIdentity() {
2023-02-13 12:41:30 +00:00
const session = await getSession();
2023-03-15 12:17:43 +00:00
if (!session) throw new Error("Invalid session");
2023-02-13 12:41:30 +00:00
return {
id: session.user?.email,
fullName: session.user?.name,
avatar: session.user?.image,
};
},
getPermissions: () => Promise.resolve(),
};
export const AdminLogin: FC = () => {
const reactAdminLogin = useLogin();
const translate = useTranslate();
useEffect(() => {
(async () => {
const session = await getSession();
2023-03-15 12:17:43 +00:00
if (session) {
2023-02-13 12:41:30 +00:00
reactAdminLogin({ ok: true });
2023-03-15 12:17:43 +00:00
} else {
signIn();
2023-02-13 12:41:30 +00:00
}
})();
});
return (
<Grid
container
spacing={5}
direction="column"
alignItems="center"
2023-03-13 22:14:52 +00:00
justifyContent="center"
2023-02-13 12:41:30 +00:00
style={{ minHeight: "100vh" }}
>
<Grid item xs={3}>
<Typography variant="h4" color="textSecondary">
{translate("auth.loggingIn")}
</Typography>
</Grid>
<Grid item xs={3}>
<CircularProgress size={80} />
</Grid>
</Grid>
);
};