Compare commits

..

2 Commits

Author SHA1 Message Date
M1000fr
3aa3f6edc5 fix: oupsi 2024-12-05 00:52:06 +01:00
M1000fr
d8f5a353ce feat: Add initial project files and configuration 2024-12-05 00:49:42 +01:00
39 changed files with 1022 additions and 2560 deletions

View File

@ -1,12 +0,0 @@
NEXT_PUBLIC_API_URL=
NEXTAUTH_URL=
NEXTAUTH_SECRET=
OAUTH_PROVIDER_NAME=
OAUTH_CLIENT_ID=
OAUTH_CLIENT_SECRET=
OAUTH_ISSUER=
OAUTH_AUTHORIZATION_URL=
OAUTH_TOKEN_URL=
OAUTH_USERINFO_URL=
OAUTH_JWKS_ENDPOINT=

View File

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

54
.gitignore vendored
View File

@ -1,40 +1,24 @@
# 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
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# env files (can opt-in for committing if needed)
.env
node_modules
dist
dist-ssr
*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"tabWidth": 4,
"useTabs": true
}

View File

@ -1,66 +0,0 @@
# syntax=docker.io/docker/dockerfile:1
FROM node:18-alpine AS base
# Install dependencies only when needed
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* .npmrc* ./
RUN \
if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
elif [ -f package-lock.json ]; then npm ci; \
elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \
else echo "Lockfile not found." && exit 1; \
fi
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED=1
RUN \
if [ -f yarn.lock ]; then yarn run build; \
elif [ -f package-lock.json ]; then npm run build; \
elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \
else echo "Lockfile not found." && exit 1; \
fi
# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000
# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]

View File

@ -1,36 +1,2 @@
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).
# README
## 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.

View File

@ -1,10 +0,0 @@
services:
webapp:
image: toogether/webapp
ports:
- "80:3000"
build:
context: ./
dockerfile: Dockerfile
environment:
- NEXT_PUBLIC_API_URL=http://api:3000

28
eslint.config.js Normal file
View File

@ -0,0 +1,28 @@
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
},
},
);

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

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

View File

@ -1,32 +1,36 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"format": "prettier --write ."
},
"dependencies": {
"axios": "^1.7.9",
"jsonwebtoken": "^9.0.2",
"moment": "^2.30.1",
"next": "15.0.3",
"next-auth": "^4.24.10",
"react": "19.0.0-rc-66855b96-20241106",
"react-dom": "19.0.0-rc-66855b96-20241106",
"@types/node": "^22.10.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"zustand": "^5.0.2"
},
"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"
"@eslint/js": "^9.15.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"eslint": "^9.15.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
"globals": "^15.12.0",
"postcss": "^8.4.49",
"prettier": "^3.4.2",
"tailwindcss": "^3.4.16",
"typescript": "~5.6.2",
"typescript-eslint": "^8.15.0",
"vite": "^6.0.1"
}
}

6
postcss.config.js Normal file
View File

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

View File

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

20
src/App.tsx Normal file
View File

@ -0,0 +1,20 @@
import { useCounterStore } from "./stores/counterStore";
function App() {
const { count, incr } = useCounterStore();
return (
<>
<p>Hello World!</p>
<p>Count: {count}</p>
<button
className="p-2 bg-red-400 rounded text-white"
onClick={incr}
>
Increment
</button>
</>
);
}
export default App;

View File

@ -1,5 +0,0 @@
import NextAuth from "next-auth";
import { authOptions } from "@/authOptions";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

View File

@ -1,43 +0,0 @@
"use client";
import { authOptions } from "@/authOptions";
import { signIn } from "next-auth/react";
const LoginPage = () => {
const provider = authOptions.providers[0];
return (
<div className="flex flex-col h-screen items-center justify-center bg-gradient-to-br from-green-700 to-green-950 bg-[length:200%_200%] animate-gradient-x text-white">
<div className="flex flex-col justify-center items-center gap-6 bg-black bg-opacity-40 rounded-md p-5 mx-5 w-2/3">
<div className="flex items-center w-full gap-5">
<div className="border-t border-white flex-grow"></div>
<h1 className="text-3xl font-bold">Toogether</h1>
<div className="border-t border-white flex-grow"></div>
</div>
<div className="flex flex-col items-center gap-2">
<h2 className="font-bold text-2xl">Connexion</h2>
<p>
Pour accéder à la plateforme, merci de vous
authentifier.
</p>
</div>
<div className="w-full border-t border-white"></div>
<h3 className="font-bold text-xl">Via</h3>
<ul>
<li key={provider.id}>
<button
className="bg-white text-black p-2 rounded-md"
onClick={() => signIn(provider.id)}
>
{provider.name}
</button>
</li>
</ul>
</div>
</div>
);
};
export default LoginPage;

View File

@ -1,18 +0,0 @@
"use client";
import { useEffect } from "react";
import { signOut, useSession } from "next-auth/react";
const LogoutPage = () => {
const session = useSession();
useEffect(() => {
if (session) {
signOut();
}
}, [session]);
return null;
};
export default LogoutPage;

View File

@ -1,29 +0,0 @@
"use client";
import { axiosInstance } from "@/app/lib/axios";
import { useRef } from "react";
export const FetchApi = () => {
const listRef = useRef<HTMLUListElement>(null);
const handleFetch = async () => {
const response = await axiosInstance.get<{
message: string;
}>("/ping");
const li = document.createElement("li");
li.textContent = response.data.message;
listRef.current?.appendChild(li);
};
return (
<div>
<button
className="text-white px-2 py-2 bg-green-500 rounded-md"
onClick={handleFetch}
>
Fetch API
</button>
<ul ref={listRef}></ul>
</div>
);
};

View File

@ -1,28 +0,0 @@
import { getServerSession, Session } from "next-auth";
import Link from "next/link";
const Header = async () => {
const session = (await getServerSession()) as Session;
return (
<header className="bg-gray-900 text-white p-4">
<div className="container mx-auto flex justify-between items-center">
<h1 className="text-xl font-bold">Toogether</h1>
<div className="flex items-center gap-2">
<p>
Logged in as <strong>{session.user.name}</strong>
</p>
<nav className="space-x-4">
<Link href="/auth/logout">
<button className="bg-gray-800 px-4 py-2 rounded hover:scale-105 transition duration-200">
Logout
</button>
</Link>
</nav>
</div>
</div>
</header>
);
};
export default Header;

View File

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

View File

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

View File

@ -1,28 +0,0 @@
import axios from "axios";
import moment, { Moment } from "moment";
import { getSession } from "next-auth/react";
let cachedAccessToken: string | null = null;
let tokenExpirationAt: Moment | null = null;
export const axiosInstance = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
});
axiosInstance.interceptors.request.use(async (config) => {
if (tokenExpirationAt && moment().isBefore(tokenExpirationAt)) {
config.headers.Authorization = `Bearer ${cachedAccessToken}`;
return config;
}
const session = await getSession();
if (!session) {
throw new Error("User is not authenticated");
}
cachedAccessToken = session.accessToken;
tokenExpirationAt = moment(session.accessTokenExpires);
config.headers.Authorization = `Bearer ${cachedAccessToken}`;
return config;
});

View File

@ -1,3 +0,0 @@
export const UppercaseFirstLetter = (str: string) => {
return str.slice(0, 1).toLocaleUpperCase() + str.slice(1);
}

View File

@ -1,13 +0,0 @@
import Header from "./components/Header";
import { FetchApi } from "./components/FetchApi";
const HomePage = () => {
return (
<>
<Header />
<FetchApi />
</>
);
};
export default HomePage;

View File

@ -1,12 +0,0 @@
declare namespace NodeJS {
interface ProcessEnv {
OAUTH_PROVIDER_NAME: string;
OAUTH_CLIENT_ID: string;
OAUTH_CLIENT_SECRET: string;
OAUTH_AUTHORIZATION_URL: string;
OAUTH_TOKEN_URL: string;
OAUTH_USERINFO_URL: string;
OAUTH_ISSUER: string;
OAUTH_JWKS_ENDPOINT: string;
}
}

View File

@ -1,42 +0,0 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Moment } from "moment";
import NextAuth, { DefaultSession } from "next-auth";
import { JWT } from "next-auth/jwt";
interface User {
id: string;
sub: string;
name: string;
preferred_username: string;
given_name: string;
family_name: string;
}
declare module "next-auth" {
interface Session extends DefaultSession {
accessToken: string;
refreshToken: string;
accessTokenExpires: Moment;
error?: Error;
user: User;
}
interface Account {
expires_at: number;
access_token: string;
refresh_token: string;
}
}
declare module "next-auth/jwt" {
interface JWT {
accessToken: string;
accessTokenExpires: Moment;
refreshToken: string;
error?: Error;
user: User | AdapterUser;
iat: number;
exp: number;
jti: string;
}
}

View File

@ -1,104 +0,0 @@
import axios from "axios";
import moment from "moment";
import { AuthOptions, Session } from "next-auth";
import { JWT } from "next-auth/jwt";
export const authOptions: AuthOptions = {
providers: [
{
id: "oauth",
name: process.env.OAUTH_PROVIDER_NAME,
type: "oauth",
clientId: process.env.OAUTH_CLIENT_ID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
authorization: {
url: process.env.OAUTH_AUTHORIZATION_URL,
params: {
scope: "openid profile offline_access",
response_type: "code",
},
},
checks: ["pkce", "state"],
idToken: true,
token: process.env.OAUTH_TOKEN_URL,
userinfo: process.env.OAUTH_USERINFO_URL,
issuer: process.env.OAUTH_ISSUER,
jwks_endpoint: process.env.OAUTH_JWKS_ENDPOINT,
profile(profile: Session["user"]) {
return {
id: profile.sub || profile.id,
name:
profile.name ||
profile.preferred_username ||
`${profile.given_name} ${profile.family_name}`,
};
},
},
],
callbacks: {
async jwt({ token, account, user }) {
if (account && user) {
token.accessToken = account.access_token;
token.accessTokenExpires = moment(account.expires_at * 1000).subtract(5, "s");
token.refreshToken = account.refresh_token;
token.user = user;
return token;
}
if (moment().isBefore(moment(token.accessTokenExpires))) {
return token;
}
return refreshAccessToken(token);
},
async session({ session, token }) {
if (token) {
session.user = token.user;
session.accessToken = token.accessToken;
session.accessTokenExpires = token.accessTokenExpires;
session.error = token.error;
}
return session;
},
},
pages: {
signIn: "/auth/login",
signOut: "/auth/logout",
}
};
const refreshAccessToken = async (token: JWT): Promise<JWT> => {
const response = await axios.post<{
access_token: string;
expires_in: number;
refresh_token: string;
error_description?: string;
}>(
process.env.OAUTH_TOKEN_URL,
{
grant_type: "refresh_token",
refresh_token: token.refreshToken,
client_id: process.env.OAUTH_CLIENT_ID,
client_secret: process.env.OAUTH_CLIENT_SECRET,
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
);
if (response.status != 200) {
throw new Error(
response.data.error_description || "Failed to refresh access token"
);
}
return {
...token,
accessToken: response.data.access_token,
accessTokenExpires: moment().add(response.data.expires_in, "seconds").subtract(5, "s"),
refreshToken: response.data.refresh_token,
};
};

10
src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);

View File

@ -1,25 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
export async function middleware(req: NextRequest) {
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
const isAuth = !!token;
const url = req.nextUrl.clone();
if (isAuth && url.pathname === "/auth/login") {
url.pathname = "/";
return NextResponse.redirect(url);
}
if (!isAuth && url.pathname !== "/auth/login") {
url.pathname = "/auth/login";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next|static|favicon.ico).*)"],
};

View File

@ -0,0 +1,11 @@
import { create } from "zustand";
interface CounterStore {
count: number;
incr: () => void;
}
export const useCounterStore = create<CounterStore>((set) => ({
count: 0,
incr: () => set((state) => ({ count: state.count + 1 })),
}));

1
src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

8
tailwind.config.js Normal file
View File

@ -0,0 +1,8 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
};

View File

@ -1,28 +0,0 @@
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)",
},
animation: {
"gradient-x": "gradient-x 5s ease infinite",
},
keyframes: {
"gradient-x": {
"0%": { "background-position": "0% 50%" },
"50%": { "background-position": "100% 50%" },
"100%": { "background-position": "0% 50%" },
},
},
},
},
plugins: [],
} satisfies Config;

31
tsconfig.app.json Normal file
View File

@ -0,0 +1,31 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
"baseUrl": "./src",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"]
}

View File

@ -1,27 +1,7 @@
{
"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"]
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

24
tsconfig.node.json Normal file
View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

10
vite.config.ts Normal file
View File

@ -0,0 +1,10 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
host: "0.0.0.0",
},
});

2738
yarn.lock

File diff suppressed because it is too large Load Diff