Revert "Add: tRPC + register on first time login"

This reverts commit cb5f9017a9a3e1e0886bfa67b9b9f5554f527d35.
This commit is contained in:
Sonny
2023-04-16 19:24:22 +02:00
parent 7074901dcb
commit 056a398f25
12 changed files with 1767 additions and 4403 deletions

View File

@@ -1,12 +1,12 @@
import Head from "next/head";
import Link from "next/link";
import { FormEvent } from "react";
import { config } from "../config";
import MessageManager from "./MessageManager";
import styles from "../styles/create.module.scss";
import { config } from "../config";
interface FormProps {
title: string;
errorMessage?: string;
@@ -14,7 +14,7 @@ interface FormProps {
infoMessage?: string;
canSubmit: boolean;
handleSubmit: (event: FormEvent<HTMLFormElement>) => void;
handleSubmit: (event) => void;
textBtnConfirm?: string;
classBtnConfirm?: string;

5659
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,11 +10,6 @@
"dependencies": {
"@prisma/client": "^4.10.0",
"@svgr/webpack": "^6.5.1",
"@tanstack/react-query": "^4.24.6",
"@trpc/client": "^10.11.1",
"@trpc/next": "^10.11.1",
"@trpc/react-query": "^10.11.1",
"@trpc/server": "^10.11.1",
"axios": "^1.3.2",
"next": "^13.1.6",
"next-auth": "^4.19.2",
@@ -26,8 +21,7 @@
"react-select": "^5.7.0",
"sass": "^1.58.0",
"sharp": "^0.31.3",
"toastr": "^2.1.4",
"zod": "^3.20.6"
"toastr": "^2.1.4"
},
"devDependencies": {
"@types/node": "^18.13.0",

View File

@@ -1,49 +1,44 @@
import { SessionProvider } from "next-auth/react";
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
import nProgress from "nprogress";
import { useEffect } from "react";
import { useEffect } from 'react';
import { SessionProvider } from 'next-auth/react';
import AuthRequired from "../components/AuthRequired";
import { useRouter } from 'next/router';
import { trpc } from "../utils/trpc";
import nProgress from 'nprogress';
import 'nprogress/nprogress.css';
import "nprogress/nprogress.css";
import "../styles/globals.scss";
import AuthRequired from '../components/AuthRequired';
import '../styles/globals.scss';
interface MyAppProps extends AppProps {
Component: any; // TODO: fix type
}
function MyApp({
Component,
pageProps: { session, ...pageProps },
}: MyAppProps) {
const router = useRouter();
Component,
pageProps: { session, ...pageProps }
}) {
const router = useRouter();
useEffect(() => {
// Chargement pages
router.events.on("routeChangeStart", nProgress.start);
router.events.on("routeChangeComplete", nProgress.done);
router.events.on("routeChangeError", nProgress.done);
useEffect(() => { // Chargement pages
router.events.on('routeChangeStart', nProgress.start);
router.events.on('routeChangeComplete', nProgress.done);
router.events.on('routeChangeError', nProgress.done);
return () => {
router.events.off("routeChangeStart", nProgress.start);
router.events.off("routeChangeComplete", nProgress.done);
router.events.off("routeChangeError", nProgress.done);
};
});
return () => {
router.events.off('routeChangeStart', nProgress.start);
router.events.off('routeChangeComplete', nProgress.done);
router.events.off('routeChangeError', nProgress.done);
}
});
return (
<SessionProvider session={session}>
{Component.authRequired ? (
<AuthRequired>
<Component {...pageProps} />
</AuthRequired>
) : (
<Component {...pageProps} />
)}
</SessionProvider>
);
return (
<SessionProvider session={session}>
{Component.authRequired ? (
<AuthRequired>
<Component {...pageProps} />
</AuthRequired>
) : (
<Component {...pageProps} />
)}
</SessionProvider>
);
}
export default trpc.withTRPC(MyApp);
export default MyApp;

View File

@@ -1,101 +1,64 @@
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { PrismaClient } from "@prisma/client";
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code",
},
},
}),
],
callbacks: {
async signIn({ account: accountParam, profile }) {
// TODO: Auth
console.log(
"Connexion via",
accountParam.provider,
accountParam.providerAccountId,
profile.email,
profile.name
);
if (accountParam.provider !== "google") {
return (
"/signin?error=" + encodeURI("Authentitifcation via Google requise")
);
}
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: {
params: {
prompt: 'consent',
access_type: 'offline',
response_type: 'code'
}
}
})
],
callbacks: {
async signIn({ account: accountParam, profile }) { // TODO: Auth
console.log('Connexion via', accountParam.provider, accountParam.providerAccountId, profile.email, profile.name)
if (accountParam.provider !== 'google') {
return '/signin?error=' + encodeURI('Authentitifcation via Google requise');
}
const email = profile?.email;
if (email === "") {
return (
"/signin?error=" +
encodeURI(
"Impossible de récupérer l'email associé à ce compte Google"
)
);
}
const email = profile?.email;
if (email === '') {
return '/signin?error=' + encodeURI('Impossible de récupérer l\'email associé à ce compte Google');
}
const googleId = profile?.sub;
if (googleId === "") {
return (
"/signin?error=" +
encodeURI(
"Impossible de récupérer l'identifiant associé à ce compte Google"
)
);
}
const googleId = profile?.sub;
if (googleId === '') {
return '/signin?error=' + encodeURI('Impossible de récupérer l\'identifiant associé à ce compte Google');
}
try {
const account = await prisma.user.findFirst({
where: {
google_id: googleId,
email,
},
});
const accountCount = await prisma.user.count();
try {
const account = await prisma.user.findFirst({
where: {
google_id: googleId,
email
}
});
if (!account) {
if (accountCount === 0) {
await prisma.user.create({
data: {
email,
google_id: googleId,
},
});
return true;
}
return (
"/signin?error=" +
encodeURI(
"Vous n'êtes pas autorisé à vous connecter avec ce compte Google"
)
);
} else {
return true;
if (!account) {
return '/signin?error=' + encodeURI('Vous n\'êtes pas autorisé à vous connecter avec ce compte Google');
} else {
return true;
}
} catch (error) {
console.error(error);
return '/signin?error=' + encodeURI('Une erreur est survenue lors de l\'authentification');
}
}
} catch (error) {
console.error(error);
return (
"/signin?error=" +
encodeURI("Une erreur est survenue lors de l'authentification")
);
}
},
},
pages: {
signIn: "/signin",
error: "/signin",
},
session: {
maxAge: 60 * 60 * 6, // Session de 6 heures
},
pages: {
signIn: '/signin',
error: '/signin'
},
session: {
maxAge: 60 * 60 * 6 // Session de 6 heures
}
});

View File

@@ -1,10 +0,0 @@
import * as trpcNext from "@trpc/server/adapters/next";
import { appRouter } from "../../../server/routers/_app";
// export API handler
// @see https://trpc.io/docs/api-handler
export default trpcNext.createNextApiHandler({
router: appRouter,
createContext: () => ({}),
});

View File

@@ -1,72 +1,64 @@
import axios, { AxiosResponse } from "axios";
import { useRouter } from "next/router";
import nProgress from "nprogress";
import { FormEvent, useMemo, useState } from "react";
import { useEffect, useState } from 'react';
import FormLayout from "../../components/FormLayout";
import TextBox from "../../components/TextBox";
import nProgress from 'nprogress';
import axios, { AxiosResponse } from 'axios';
import { Category } from "../../types";
import { HandleAxiosError } from "../../utils/front";
import { trpc } from "../../utils/trpc";
import FormLayout from '../../components/FormLayout';
import TextBox from '../../components/TextBox';
import styles from "../../styles/create.module.scss";
import styles from '../../styles/create.module.scss';
import { HandleAxiosError } from '../../utils/front';
import { useRouter } from 'next/router';
function CreateCategory() {
const hello = trpc.hello.useQuery({ text: "client" });
const info = useRouter().query?.info as string;
const [name, setName] = useState<string>("");
const info = useRouter().query?.info as string;
const [name, setName] = useState<string>('');
const [error, setError] = useState<string | undefined>();
const [success, setSuccess] = useState<string | undefined>();
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [canSubmit, setCanSubmit] = useState<boolean>(false);
const canSubmit = useMemo<boolean>(
() => name.length !== 0 && !loading,
[loading, name.length]
);
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSuccess(undefined);
setError(undefined);
setLoading(true);
nProgress.start();
useEffect(() => setCanSubmit(name.length !== 0), [name]);
try {
const payload = { name };
const { data }: AxiosResponse<{ success: string; category: Category }> =
await axios.post("/api/category/create", payload);
const handleSubmit = async (event) => {
event.preventDefault();
setSuccess(null);
setError(null);
setCanSubmit(false);
nProgress.start();
console.log(data);
setSuccess(data.success);
} catch (error) {
setError(HandleAxiosError(error));
} finally {
setLoading(false);
nProgress.done();
try {
const payload = { name };
const { data }: AxiosResponse<any> = await axios.post('/api/category/create', payload);
setSuccess(data?.success || 'Categorie créée avec succès');
setCanSubmit(false);
} catch (error) {
setError(HandleAxiosError(error));
setCanSubmit(true);
} finally {
nProgress.done();
}
}
};
return (
<FormLayout
title="Créer une catégorie"
errorMessage={error}
successMessage={success}
infoMessage={info}
canSubmit={canSubmit}
handleSubmit={handleSubmit}
>
<TextBox
name="name"
label="Nom de la catégorie"
onChangeCallback={(value) => setName(value)}
value={name}
fieldClass={styles["input-field"]}
placeholder="Nom..."
/>
{JSON.stringify(hello)}
</FormLayout>
);
return (<>
<FormLayout
title='Créer une catégorie'
errorMessage={error}
successMessage={success}
infoMessage={info}
canSubmit={canSubmit}
handleSubmit={handleSubmit}
>
<TextBox
name='name'
label='Nom de la catégorie'
onChangeCallback={(value) => setName(value)}
value={name}
fieldClass={styles['input-field']}
placeholder='Nom...'
/>
</FormLayout>
</>);
}
CreateCategory.authRequired = true;

View File

@@ -13,64 +13,67 @@ import { prisma } from "../utils/back";
import { config } from "../config";
interface HomeProps {
categories: Category[];
favorites: Link[];
categories: Category[];
favorites: Link[];
}
function Home({ categories, favorites }: HomeProps) {
const { data } = useSession({ required: true });
const [categoryActive, setCategoryActive] = useState<Category | null>(
categories?.[0]
);
const { data } = useSession({ required: true });
const [categoryActive, setCategoryActive] = useState<Category | null>(
categories?.[0]
);
const handleSelectCategory = (category: Category) =>
setCategoryActive(category);
const handleSelectCategory = (category: Category) =>
setCategoryActive(category);
return (
<>
<Head>
<title>{config.siteName}</title>
</Head>
<div className="App">
<Menu
categories={categories}
favorites={favorites}
handleSelectCategory={handleSelectCategory}
categoryActive={categoryActive}
session={data}
/>
<Links category={categoryActive} />
</div>
</>
);
return (
<>
<Head>
<title>{config.siteName}</title>
</Head>
<div className="App">
<Menu
categories={categories}
favorites={favorites}
handleSelectCategory={handleSelectCategory}
categoryActive={categoryActive}
session={data}
/>
<Links category={categoryActive} />
</div>
</>
);
}
export async function getServerSideProps() {
const categoriesDB = await prisma.category.findMany({
include: { links: true },
});
const categoriesDB = await prisma.category.findMany({
include: { links: true },
});
const favorites = [] as Link[];
const categories = categoriesDB.map((categoryDB) => {
const category = BuildCategory(categoryDB);
category.links.map((link) => (link.favorite ? favorites.push(link) : null));
return category;
});
const favorites = [] as Link[];
const categories = categoriesDB.map((categoryDB) => {
const category = BuildCategory(categoryDB);
category.links.map((link) =>
link.favorite ? favorites.push(link) : null
);
return category;
});
if (categories.length === 0) {
return {
redirect: {
destination:
"/category/create?info=Veuillez créer une catégorie",
},
};
}
if (categories.length === 0) {
return {
redirect: {
destination: "/category/create",
},
props: {
categories: JSON.parse(JSON.stringify(categories)),
favorites: JSON.parse(JSON.stringify(favorites)),
},
};
}
return {
props: {
categories: JSON.parse(JSON.stringify(categories)),
favorites: JSON.parse(JSON.stringify(favorites)),
},
};
}
Home.authRequired = true;

View File

@@ -1,19 +0,0 @@
import { z } from "zod";
import { procedure, router } from "../trpc";
export const appRouter = router({
hello: procedure
.input(
z.object({
text: z.string(),
})
)
.query(({ input }) => {
return {
greeting: `hello ${input.text}`,
};
}),
});
// export type definition of API
export type AppRouter = typeof appRouter;

View File

@@ -1,9 +0,0 @@
import { initTRPC } from "@trpc/server";
// Avoid exporting the entire t-object
// since it's not very descriptive.
// For instance, the use of a t variable
// is common in i18n libraries.
const t = initTRPC.create();
// Base router and procedure helpers
export const router = t.router;
export const procedure = t.procedure;

View File

@@ -1,5 +1,5 @@
{
"compilerOptions": {
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
@@ -8,7 +8,7 @@
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
@@ -18,13 +18,14 @@
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": [
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
],
"exclude": [
"node_modules"
]
}

View File

@@ -1,21 +0,0 @@
import { httpBatchLink } from "@trpc/client";
import { createTRPCNext } from "@trpc/next";
import type { AppRouter } from "../server/routers/_app";
const getBaseUrl = () =>
typeof window !== "undefined"
? ""
: `http://localhost:${process.env.PORT ?? 3000}`;
export const trpc = createTRPCNext<AppRouter>({
config({ ctx }) {
return {
links: [
httpBatchLink({
url: `${getBaseUrl()}/api/trpc`,
}),
],
};
},
ssr: false,
});