Compare commits

..

15 Commits

Author SHA1 Message Date
54330f2137 Merge pull request 'feature/auth' (#2) from feature/auth into main
Reviewed-on: #2
2024-12-13 12:55:23 +00:00
M1000fr
7f0573dc0e refactor: Add Dockerfile, docker-compose.yml, and update next.config.ts 2024-12-13 13:54:25 +01:00
M1000fr
cb27acdbd9 refactor: .env.example 2024-12-13 13:35:54 +01:00
M1000fr
135d94c976 refactor: organise 2024-12-13 13:31:41 +01:00
M1000fr
1dbd24f2e6 refactor: change structure 2024-12-12 18:58:43 +01:00
M1000fr
716642142f refactor: Update login page and layout styles 2024-12-12 16:56:48 +01:00
M1000fr
2ff781feea feat: Auth implementation
- Add Login & Logout page
- Add middleware to protect pages
- Add Header Server Side Component
2024-12-12 15:13:12 +01:00
M1000fr
08a41e5e2b feat: refresh token when access token has expired 2024-12-12 00:45:32 +01:00
M1000fr
52f2c969cc feat: integrate openid well-known 2024-12-11 18:51:23 +01:00
M1000fr
2091aec376 feat: switch to JWKS verification 2024-12-11 00:41:55 +01:00
M1000fr
124a46e0d1 refactor: Add Apache License to the project 2024-11-26 18:33:11 +01:00
M1000fr
8806c38320 ref: move to auth page to an component 2024-11-25 17:30:44 +01:00
e257940129 ref: remove comments and styles 2024-11-24 22:24:18 +01:00
48e51a738b ref: remove comments, move authOptions, add somes Types 2024-11-24 18:22:28 +01:00
7af42ef5d6 feat: add auth using next-auth and discord provider 2024-11-24 02:35:27 +01:00
28 changed files with 3973 additions and 0 deletions

12
.env.example Normal file
View File

@ -0,0 +1,12 @@
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=

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

66
Dockerfile Normal file
View File

@ -0,0 +1,66 @@
# 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"]

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

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.

10
docker-compose.yml Normal file
View File

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

8
next.config.ts Normal file
View File

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

32
package.json Normal file
View File

@ -0,0 +1,32 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"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",
"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"
}
}

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,5 @@
import NextAuth from "next-auth";
import { authOptions } from "@/authOptions";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

View File

@ -0,0 +1,43 @@
"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

@ -0,0 +1,18 @@
"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

@ -0,0 +1,29 @@
"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

@ -0,0 +1,28 @@
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

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

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

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

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="fr">
<body>
<SessionProviderWrapper>{children}</SessionProviderWrapper>
</body>
</html>
);
}

28
src/app/lib/axios.ts Normal file
View File

@ -0,0 +1,28 @@
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

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

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

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

12
src/app/types/env.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
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;
}
}

42
src/app/types/next-auth.d.ts vendored Normal file
View File

@ -0,0 +1,42 @@
/* 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;
}
}

104
src/authOptions.ts Normal file
View File

@ -0,0 +1,104 @@
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,
};
};

25
src/middleware.ts Normal file
View File

@ -0,0 +1,25 @@
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).*)"],
};

28
tailwind.config.ts Normal file
View File

@ -0,0 +1,28 @@
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;

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"]
}

3122
yarn.lock Normal file

File diff suppressed because it is too large Load Diff