feat: add auth using next-auth and discord provider

This commit is contained in:
M1000 2024-11-24 02:35:27 +01:00
parent ca096f02ec
commit 7af42ef5d6
17 changed files with 3468 additions and 0 deletions

7
.env.example Normal file
View File

@ -0,0 +1,7 @@
NEXT_PUBLIC_API_URL=http://localhost:3000
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=

3
.eslintrc.json Normal file
View File

@ -0,0 +1,3 @@
{
"extends": ["next/core-web-vitals", "next/typescript"]
}

40
.gitignore vendored Normal file
View File

@ -0,0 +1,40 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# env files (can opt-in for committing if needed)
.env
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

7
next.config.ts Normal file
View File

@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

29
package.json Normal file
View File

@ -0,0 +1,29 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"jsonwebtoken": "^9.0.2",
"next": "15.0.3",
"next-auth": "^4.24.10",
"react": "19.0.0-rc-66855b96-20241106",
"react-dom": "19.0.0-rc-66855b96-20241106"
},
"devDependencies": {
"@types/jsonwebtoken": "^9.0.7",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "15.0.3",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}

8
postcss.config.mjs Normal file
View File

@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

View File

@ -0,0 +1,40 @@
import NextAuth from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
import jwt from "jsonwebtoken";
const handler = NextAuth({
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
}),
],
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: "jwt",
},
callbacks: {
async jwt({ token, account, user }) {
if (account) {
token.accessToken = jwt.sign(
{
userId: user?.id,
provider: account.provider,
timestamp: Date.now(),
},
process.env.NEXTAUTH_SECRET!,
{ expiresIn: "1h" }
);
}
return token;
},
async session({ session, token }) {
console.log(token);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
session.accessToken = token.accessToken;
return session;
},
},
});
export { handler as GET, handler as POST };

56
src/app/auth/page.tsx Normal file
View File

@ -0,0 +1,56 @@
"use client"
import { signIn, signOut, useSession } from "next-auth/react";
const LoginPage = () => {
const { data: session } = useSession();
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
marginTop: "50px",
}}
>
<h1>NextAuth Login</h1>
{!session ? (
<div>
<p>You are not signed in.</p>
<button
style={{
padding: "10px 20px",
backgroundColor: "#7289DA",
color: "white",
border: "none",
borderRadius: "5px",
cursor: "pointer",
}}
onClick={() => signIn("discord")} // Modifier selon votre provider
>
Sign in with Discord
</button>
</div>
) : (
<div>
<p>Welcome, {session.user?.name || "User"}!</p>
<button
style={{
padding: "10px 20px",
backgroundColor: "red",
color: "white",
border: "none",
borderRadius: "5px",
cursor: "pointer",
}}
onClick={() => signOut()}
>
Sign out
</button>
</div>
)}
</div>
);
};
export default LoginPage;

View File

@ -0,0 +1,63 @@
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
const FetchWithSession = () => {
const { data: session, status } = useSession(); // Récupère la session utilisateur
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
if (status === "authenticated" && session) {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Authorization: `Bearer ${session.accessToken}`, // Exemple : inclure un token JWT si nécessaire
},
}
);
if (!response.ok) {
throw new Error("Failed to fetch data");
}
const result = await response.json();
setData(result);
} catch (err) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
setError(err.message);
}
}
};
fetchData();
}, [status, session]);
if (status === "loading") {
return <div>Loading...</div>;
}
if (status === "unauthenticated") {
return <div>You must log in to access this data.</div>;
}
return (
<div>
{error && <p>Error: {error}</p>}
{data ? (
<pre>{JSON.stringify(data, null, 2)}</pre>
) : (
<p>Fetching data...</p>
)}
</div>
);
};
export default FetchWithSession;

View File

@ -0,0 +1,11 @@
"use client"; // Indique que ce composant est un Client Component
import { SessionProvider } from "next-auth/react";
export default function SessionProviderWrapper({
children,
}: {
children: React.ReactNode;
}) {
return <SessionProvider>{children}</SessionProvider>;
}

21
src/app/globals.css Normal file
View File

@ -0,0 +1,21 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
}

16
src/app/layout.tsx Normal file
View File

@ -0,0 +1,16 @@
import SessionProviderWrapper from "./components/SessionProviderWrapper";
import "./globals.css";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<SessionProviderWrapper>{children}</SessionProviderWrapper>
</body>
</html>
);
}

16
src/app/page.tsx Normal file
View File

@ -0,0 +1,16 @@
"use client";
import { useSession } from "next-auth/react";
import FetchWithSession from "./components/FetchWithSession";
export default function Home() {
const { data } = useSession(); // Récupère la session
console.log(data);
return (
<>
<h1>Home</h1>
<FetchWithSession />
</>
);
}

18
tailwind.config.ts Normal file
View File

@ -0,0 +1,18 @@
import type { Config } from "tailwindcss";
export default {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
} satisfies Config;

27
tsconfig.json Normal file
View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

3070
yarn.lock Normal file

File diff suppressed because it is too large Load Diff