Initial commit

This commit is contained in:
Iceberg
2026-04-20 17:59:24 +00:00
commit a43f8de3e4
51 changed files with 9695 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
node_modules
.git
.gitea
.gitignore
README.md
Dockerfile
*.log
docker-compose.yml
.env*
.next/cache
+38
View File
@@ -0,0 +1,38 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
name: CI - Validation Technique
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20 # Vite recommande Node 18+ ou 20
- name: Install dependencies
run: npm ci
- name: Lint check
run: npm run lint || echo "Pas de script lint trouvé, on continue."
- name: Build project
run: npm run build
+82
View File
@@ -0,0 +1,82 @@
name: Publish & Deploy (Versioned)
on:
push:
tags:
- 'v*' # Se déclenche uniquement pour les tags commençant par 'v' (ex: v1.0)
jobs:
build-and-push:
name: Build and Push Docker Image
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Prepare Repo Name
id: repo_name
run: |
echo "REPO_LOWER=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV
- name: Login to Gitea Registry
uses: https://github.com/docker/login-action@v3
with:
registry: gitea.iceberg.black
username: docker-bot
password: ${{ secrets.CONTAINER_REGISTRY_TOKEN }}
- name: Build and Push
uses: https://github.com/docker/build-push-action@v5
with:
context: .
push: true
tags: |
gitea.iceberg.black/${{ env.REPO_LOWER }}:${{ github.ref_name }}
gitea.iceberg.black/${{ env.REPO_LOWER }}:latest
- name: Link package to repository
run: |
PKG_NAME=${REPO_LOWER#*/}
OWNER=${REPO_LOWER%/*}
RESPONSE=$(curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST \
"https://gitea.iceberg.black/api/v1/packages/${OWNER}/container/${PKG_NAME}/-/link/${PKG_NAME}" \
-H "Authorization: token ${{ secrets.CONTAINER_REGISTRY_TOKEN }}")
echo "Link response: $RESPONSE"
deploy:
name: Deploy via SSH
needs: build-and-push
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Copy docker-compose to server
run: |
echo "${{ secrets.SSH_PRIVATE_KEY }}" > key.pem
chmod 600 key.pem
scp -i key.pem -o StrictHostKeyChecking=no \
docker-compose.yml \
bot@${{ secrets.SSH_HOST }}:/home/shared/iceberg/.../docker-compose.yml # [TO CHANGE]
- name: Execute remote deployment
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.SSH_HOST }}
username: bot
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
REPO_LOWER=$(echo "${{ github.repository }}" | tr '[:upper:]' '[:lower:]')
TAG=${{ github.ref_name }}
echo "${{ secrets.CONTAINER_REGISTRY_TOKEN }}" | docker login gitea.iceberg.black -u "docker-bot" --password-stdin
docker pull gitea.iceberg.black/$REPO_LOWER:$TAG
docker logout gitea.iceberg.black
docker stop ... || true # [TO CHANGE]
docker rm ... || true # [TO CHANGE]
cd /home/shared/iceberg/... # [TO CHANGE]
REPO_LOWER=$REPO_LOWER TAG=$TAG docker compose up -d
docker image prune -af
+41
View File
@@ -0,0 +1,41 @@
# 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*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# husky
.husky
# typescript
*.tsbuildinfo
next-env.d.ts
+6
View File
@@ -0,0 +1,6 @@
{
"semi": true,
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
}
+32
View File
@@ -0,0 +1,32 @@
# =========================
# Build stage
# =========================
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# =========================
# Runtime stage
# =========================
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
# Copy only minimal Next standalone output
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]
+73
View File
@@ -0,0 +1,73 @@
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 2026 Iceberg
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.
+145
View File
@@ -0,0 +1,145 @@
# Getting Started
## Create .env.local file
Before starting make sure .env.local file exists and contains
```bash
# Only needed if using keycloak
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET= # you can generate it using "openssl rand -base64 32"
# If you plan to use keycloak (only openid issuer implemented) you have to create a client on your app
KEYCLOAK_CLIENT_ID=...
KEYCLOAK_CLIENT_SECRET=...
KEYCLOAK_ISSUER=https://<KEYCLOAK_DOMAIN>/realms/<REALM_NAME>
```
## Launch development server
First, run the development server:
```bash
npm ci
npm run dev
```
Or use another package manager
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.
# Add features
## Add page
Create src/app/[locale]/{your-page}/page.tsx
Or src/app/{your-page}/page.tsx if you don't want to use locales
Add your code and there you go !
## Add API endpoint
Create src/app/api/your/endpoints/route.ts or src/app/api/your-endpoints/route.ts
## Add Locale
Copy messages/en.json and rename it messages/{your-locale}.json, then translate it.
Add locale flag at svg format in public/flags
Update src/i18n/routing.ts with your new locale
# Protect a Page route or an API route
Add your Page or API in src/proxy.ts
```typescript
'/example': ['admin'], # Page only accessible to users with admin role
'/dashboard': [], # Page accessible to all users connected
```
# Git
## Before Commit
### Setup
If you use this template by using git clone, remove .git and link directory to a repo
Then run
```bash
git init
git remote add origin https://gitea.iceberg.black/user/repo.git
git branch -M main
git push -u origin main
```
### Lint and format
Install Husky to link and format code before commit
```bash
npx husky init
```
Copy
```bash
npx lint-staged
```
Or whatever you want in .husky/pre-commit
### Project related informations
Change all lines with [TO CHANGE] + public/manifest.json
## Before Push
- Ensure all git secrets or variables exist
- Ensure all docker links exist on distant machine
- Ensure env file exists on remote machine
## Auto deploy
To run auto deploy you have to check for the "Before Push" section and then:
Push Tag with format v\* to trigger Deploy CI
```bash
git tag -a vX.X.X -m "Release vX.X.X" # Locally
git push origin vX.X.X # On remote
```
Optionnal Delete tag:
```bash
git tag -d vX.X.X # Locally
git push origin :refs/tags/vX.X.X # On remote
```
Useful command with all to reset
```bash
git tag -d v1.0.0; git push origin :refs/tags/v1.0.0; git tag -a v1.0.0 -m "Release v1.0.0"; git push origin v1.0.0
```
# Features
## Implemented
- Clean gitea CI
- Locale handling
- Authentification with keycloak
- Routes an API role protections
- Auto deploy
## To implement
- Better Tailwind CSS classes
- See keycloak user infos
+12
View File
@@ -0,0 +1,12 @@
services:
chat:
image: gitea.iceberg.black/${REPO_LOWER}:${TAG}
container_name: ... # [TO CHANGE]
env_file:
- .env # You SHOULD upload env file on vps before
ports:
- '...:...' # [TO CHANGE]
restart: unless-stopped
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from 'eslint/config';
import nextVitals from 'eslint-config-next/core-web-vitals';
import nextTs from 'eslint-config-next/typescript';
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
]),
]);
export default eslintConfig;
+31
View File
@@ -0,0 +1,31 @@
{
"notFound": {
"title": "404",
"description": "Page not found",
"link": "Go home"
},
"forbidden": {
"title": "403",
"description": "You don’t have permission to access this page",
"link": "Go home"
},
"auth": {
"myaccount": "My account",
"login": "Login",
"logout": "Logout"
},
"theme": {
"light": "Light mode",
"dark": "Dark mode"
},
"nav": {
"label1": "Home",
"label2": "Example",
"label3": "Home 2"
},
"home": {
"name": "Iceberg Server",
"welcome": "Welcome to your Vite + React + Tailwind app",
"start": "Get Started"
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"notFound": {
"title": "404",
"description": "Page introuvable",
"link": "Retour à l'accueil"
},
"forbidden": {
"title": "403",
"description": "Vous n’avez pas la permission d’accéder à cette page",
"link": "Retour à l'accueil"
},
"auth": {
"myaccount": "Mon compte",
"login": "Connexion",
"logout": "Déconnexion"
},
"theme": {
"light": "Mode clair",
"dark": "Mode sombre"
},
"nav": {
"label1": "Accueil",
"label2": "Exemple",
"label3": "Accueil 2"
},
"home": {
"name": "Iceberg Server",
"welcome": "Bienvenue sur votre application Vite + React + Tailwind",
"start": "Commencer"
}
}
+14
View File
@@ -0,0 +1,14 @@
import type { NextConfig } from 'next';
import createNextIntlPlugin from 'next-intl/plugin';
const withNextIntl = createNextIntlPlugin();
const nextConfig: NextConfig = {
// reactCompiler: true,
output: 'standalone',
compiler: {
removeConsole: process.env.NODE_ENV === 'production',
},
};
export default withNextIntl(nextConfig);
+7990
View File
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
{
"name": "chat-website-n",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
"prepare": "husky"
},
"dependencies": {
"keycloak-js": "^26.2.3",
"next": "^16.2.4",
"next-auth": "^4.24.14",
"next-intl": "^4.9.1",
"react": "^19.2.5",
"react-dom": "^19.2.5"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"autoprefixer": "^10.5.0",
"babel-plugin-react-compiler": "1.0.0",
"eslint": "^9.39.4",
"eslint-config-next": "16.2.3",
"husky": "^9.1.7",
"lint-staged": "^16.4.0",
"postcss": "^8.5.10",
"tailwindcss": "^4.2.2",
"typescript": "^5"
},
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"eslint --fix",
"npx prettier --write"
],
"*.{json,css,md}": [
"npx prettier --write"
]
}
}
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
'@tailwindcss/postcss': {},
},
};
export default config;
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 30" width="1000" height="600">
<clipPath id="t">
<path d="M25,15h25v15zv15h-25zh-25v-15zv-15h25z"/>
</clipPath>
<path d="M0,0v30h50v-30z" fill="#012169"/>
<path d="M0,0 50,30M50,0 0,30" stroke="#fff" stroke-width="6"/>
<path d="M0,0 50,30M50,0 0,30" clip-path="url(#t)" stroke="#C8102E" stroke-width="4"/>
<path d="M-1 11h22v-12h8v12h22v8h-22v12h-8v-12h-22z" fill="#C8102E" stroke="#FFF" stroke-width="2"/>
</svg>

After

Width:  |  Height:  |  Size: 477 B

+2
View File
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#ED2939"/><rect width="600" height="600" fill="#fff"/><rect width="300" height="600" fill="#002395"/></svg>

After

Width:  |  Height:  |  Size: 249 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 340 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 340 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 KiB

+48
View File
@@ -0,0 +1,48 @@
{
"name": "Iceberg Server",
"short_name": "Iceberg",
"description": "Serveur personnel Iceberg - Petit mais costaud",
"start_url": "/",
"scope": "/",
"id": "/",
"display": "standalone",
"display_override": ["window-controls-overlay", "standalone"],
"background_color": "#000000",
"theme_color": "#00d4ff",
"orientation": "portrait-primary",
"icons": [
{
"src": "/icons/favicon-16x16.png",
"sizes": "16x16",
"type": "image/png"
},
{
"src": "/icons/favicon-32x32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "/icons/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/icons/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/icons/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
+14
View File
@@ -0,0 +1,14 @@
import { useTranslations } from 'next-intl';
import ErrorPage from '@/components/layout/ErrorPage';
export default function Forbidden() {
const t = useTranslations('forbidden');
return (
<ErrorPage
title={t('title')}
description={t('description')}
linkLabel={t('link')}
/>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { notFound } from 'next/navigation';
export default function CatchAllPage() {
notFound();
}
+8
View File
@@ -0,0 +1,8 @@
export default function AboutPage() {
return (
<div className="p-6">
<h1>About</h1>
<p>This is an example</p>
</div>
);
}
+54
View File
@@ -0,0 +1,54 @@
import '../../globals.css';
import Navbar from '@/components/layout/Navbar';
import Footer from '@/components/layout/Footer';
import { hasLocale } from 'next-intl';
import { notFound } from 'next/navigation';
import { routing } from '@/i18n/routing';
import { getMessages } from 'next-intl/server';
import { Providers } from '../providers';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { cookies } from 'next/headers';
export const metadata = {
title: 'Iceberg template',
description: 'Template for Iceberg websites',
icons: {
icon: [
{ url: '/icons/favicon-32x32.png', sizes: '32x32' },
{ url: '/icons/favicon-16x16.png', sizes: '16x16' },
],
apple: '/icons/apple-touch-icon.png',
},
manifest: '/manifest.json',
};
export default async function RootLayout(props: {
children: React.ReactNode;
params: Promise<{ locale: string }>;
}) {
const { locale } = await props.params;
const theme = (await cookies()).get('theme')?.value ?? 'light';
if (!hasLocale(routing.locales, locale)) {
notFound();
}
const messages = await getMessages();
const session = await getServerSession(authOptions);
return (
<html lang={locale} className={theme === 'dark' ? 'dark' : 'light-mode'}>
<body className="min-h-screen flex flex-col bg-primary text-primary transition-theme">
<Providers locale={locale} messages={messages} session={session}>
<Navbar />
<main className="flex-1 pt-20 flex flex-col">{props.children}</main>
<Footer />
</Providers>
</body>
</html>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { useTranslations } from 'next-intl';
import ErrorPage from '@/components/layout/ErrorPage';
export default function NotFoundPage() {
const t = useTranslations('notFound');
return (
<ErrorPage
title={t('title')}
description={t('description')}
linkLabel={t('link')}
/>
);
}
+17
View File
@@ -0,0 +1,17 @@
import { useTranslations } from 'next-intl';
export default function Home() {
const t = useTranslations('home');
return (
<div className="min-h-screen flex flex-col items-center justify-center">
<h1 className="text-5xl font-bold text-cyan-400">{t('name')}</h1>
<p className="mt-4 text-gray-400">{t('welcome')}</p>
<button className="mt-6 px-6 py-3 bg-cyan-500 hover:bg-cyan-600 rounded-xl">
{t('start')}
</button>
</div>
);
}
+6
View File
@@ -0,0 +1,6 @@
import NextAuth from 'next-auth';
import { authOptions } from '@/lib/auth';
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
+29
View File
@@ -0,0 +1,29 @@
'use client';
import { SessionProvider } from 'next-auth/react';
import { Session } from 'next-auth';
import { NextIntlClientProvider, AbstractIntlMessages } from 'next-intl';
export function Providers({
children,
session,
locale,
messages,
}: {
children: React.ReactNode;
session?: Session | null;
locale: string;
messages: AbstractIntlMessages;
}) {
return (
<SessionProvider session={session}>
<NextIntlClientProvider
locale={locale}
messages={messages}
timeZone="Europe/Paris"
>
{children}
</NextIntlClientProvider>
</SessionProvider>
);
}
@@ -0,0 +1,91 @@
import React from 'react';
import { useTranslations } from 'next-intl';
type Props = {
authenticated: boolean;
profileOpen: boolean;
setProfileOpen: React.Dispatch<React.SetStateAction<boolean>>;
profileRef: React.RefObject<HTMLDivElement | null>;
signIn: (provider: string) => void;
signOut: () => void;
toggleProfile: () => void;
};
export default function AuthProfileButton({
authenticated,
profileOpen,
setProfileOpen,
profileRef,
signIn,
signOut,
toggleProfile,
}: Props) {
const t = useTranslations('auth');
if (!authenticated) {
return (
<button
onClick={() => signIn('keycloak')}
className="px-3 py-1 rounded-md hover:opacity-80 transition-theme text-xs sm:text-sm md:text-base"
>
{t('login')}
</button>
);
}
return (
<div className="relative" ref={profileRef}>
{/* Avatar button */}
<button
onClick={toggleProfile}
className="w-9 h-9 flex items-center justify-center hover:opacity-80 transition-theme"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="var(--accent)"
strokeWidth="1.6"
strokeLinecap="round"
strokeLinejoin="round"
className="w-7 h-7 transition-theme"
>
{/* outer circle */}
<circle cx="12" cy="12" r="10" />
{/* head */}
<circle cx="12" cy="10" r="3" />
{/* shoulders */}
<path d="M7.5 18c1.5-2.5 7.5-2.5 9 0" />
</svg>
</button>
{/* Dropdown */}
<div
ref={profileRef}
className={`
fixed bg-primary text-primary top-[75px] left-0 z-40
w-full md:w-64 md:left-auto md:right-6 md:rounded-xl md:shadow-lg
origin-top transition-all duration-100 border px-6
${profileOpen ? 'opacity-100 scale-y-100' : 'opacity-0 scale-y-0 pointer-events-none'}
`}
>
<a
href="https://auth.iceberg.black/realms/iceberg/account"
className="hover:opacity-80 transition-theme py-4 block"
>
{t('myaccount')}
</a>
<button
onClick={() => {
signOut();
setProfileOpen(false);
}}
className="w-full text-left hover:opacity-80 transition-theme pb-4"
>
{t('logout')}
</button>
</div>
</div>
);
}
+28
View File
@@ -0,0 +1,28 @@
import Link from 'next/link';
export default function ErrorPage({
title,
description,
linkLabel,
}: {
title: string;
description: string;
linkLabel: string;
}) {
return (
<div className="flex-1 flex flex-col items-center justify-center text-center p-8 bg-primary transition-theme">
<h1 className="text-6xl md:text-8xl font-bold text-accent transition-theme">
{title}
</h1>
<p className="mt-4 text-secondary transition-theme">{description}</p>
<Link
href="/"
className="mt-6 text-accent hover:opacity-70 underline underline-offset-4 transition-theme"
>
{linkLabel}
</Link>
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
export default function Footer() {
const year = new Date().getFullYear();
return (
<footer className="bg-primary border-t border-border py-6 transition-theme">
<div className="max-w-6xl mx-auto px-6 flex flex-col sm:flex-row justify-between items-center gap-3 transition-theme">
<div className="flex items-center gap-1 font-bold text-accent text-sm transition-theme">
<span className="bg-logo-light text-logo-dark px-1.5 py-0.5 rounded-l-md transition-theme">
iceberg.
</span>
<span className="bg-logo-dark text-logo-light px-1.5 py-0.5 rounded-r-md transition-theme">
black
</span>
</div>
<p className="text-secondary text-sm text-center transition-theme">
© {year} Iceberg Server
</p>
</div>
</footer>
);
}
+37
View File
@@ -0,0 +1,37 @@
type Props = {
open: boolean;
burgerRef: React.RefObject<HTMLButtonElement | null>;
toggleBurger: () => void;
};
export default function HamburgerButton({
open,
toggleBurger,
burgerRef,
}: Props) {
return (
<button
ref={burgerRef}
onClick={toggleBurger}
className="flex flex-col justify-center items-center w-10 h-10 hover:opacity-80"
>
<span
className={`w-6 h-[2px] bg-current block transition-transform duration-300 ${
open ? 'rotate-45 translate-y-[6px]' : ''
}`}
/>
<span
className={`w-6 h-[2px] bg-current block my-1 transition-all duration-300 ${
open ? 'opacity-0 scale-x-0' : ''
}`}
/>
<span
className={`w-6 h-[2px] bg-current block transition-transform duration-300 ${
open ? '-rotate-45 -translate-y-[6px]' : ''
}`}
/>
</button>
);
}
+41
View File
@@ -0,0 +1,41 @@
'use client';
import { useState } from 'react';
import { useLocale } from 'next-intl';
import { useRouter, usePathname } from '@/i18n/navigation';
import { locales } from '@/i18n/routing';
export function LocaleSwitcher() {
const locale = useLocale();
const router = useRouter();
const pathname = usePathname();
const [currentLocale, setCurrentLocale] = useState(locale);
function switchLocale(next: string) {
setCurrentLocale(next);
router.replace(pathname, { locale: next });
}
return (
<div className="flex items-center gap-2 w-full py-2 hover:opacity-80">
<img
src={`/flags/${currentLocale}.svg`}
alt={currentLocale}
className="w-5 h-5 rounded-sm object-cover"
/>
<select
value={currentLocale}
onChange={(e) => switchLocale(e.target.value)}
className="bg-transparent text-current cursor-pointer outline-none w-full"
>
{locales.map(({ code, label }) => (
<option value={code} key={code}>
{label}
</option>
))}
</select>
</div>
);
}
+24
View File
@@ -0,0 +1,24 @@
import Image from 'next/image';
export default function Logo() {
return (
<div className="flex items-center gap-1 sm:gap-2 font-bold text-accent text-xs sm:text-base md:text-lg">
<Image
src="/logo/logo-nobg.png"
alt="Iceberg Logo"
width={36}
height={36}
className="h-6 sm:h-8 md:h-9 w-auto flex-shrink-0"
priority
/>
<span className="bg-logo-light text-logo-dark px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-l-md transition-theme">
iceberg.
</span>
<span className="bg-logo-dark text-logo-light px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-r-md transition-theme">
black
</span>
</div>
);
}
+159
View File
@@ -0,0 +1,159 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { useSession, signIn, signOut } from 'next-auth/react';
import { LocaleSwitcher } from '@/components/layout/LocaleSwitcher';
import { ThemeSwitcher } from '@/components/layout/ThemeSwitcher';
import HamburgerButton from '@/components/layout/HamburgerButton';
import AuthProfileButton from '@/components/layout/AuthProfileButton';
import ScrollProgressBar from '@/components/layout/ScrollProgressBar';
import Logo from '@/components/layout/Logo';
export default function Navbar() {
const t = useTranslations('nav');
const [open, setOpen] = useState(false);
const [profileOpen, setProfileOpen] = useState(false);
const menuRef = useRef<HTMLDivElement | null>(null);
const burgerRef = useRef<HTMLButtonElement | null>(null);
const profileRef = useRef<HTMLDivElement | null>(null);
const { data: session, status } = useSession();
const authenticated =
status === 'authenticated' && session?.error !== 'RefreshAccessTokenError';
// const username = session?.user?.name || session?.user?.email;
// const roles = (session as any)?.roles || [];
const links = [
{ to: '/', label: t('label1') },
{ to: '/example', label: t('label2') },
{ to: '/3', label: t('label3') },
];
useEffect(() => {
if (session?.error === 'RefreshAccessTokenError') {
signOut({ callbackUrl: '/' });
}
}, [session]);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
const clickedBurger = burgerRef.current?.contains(e.target as Node);
const clickedProfile = profileRef.current?.contains(e.target as Node);
const clickedMenu = menuRef.current?.contains(e.target as Node);
const clickedInsideUI = clickedBurger || clickedProfile || clickedMenu;
if (!clickedInsideUI) {
setOpen(false);
setProfileOpen(false);
}
};
document.addEventListener('click', handleClickOutside);
return () => document.removeEventListener('click', handleClickOutside);
}, [open, profileOpen]);
const toggleProfile = () => {
setProfileOpen((v) => {
const next = !v;
if (next) setOpen(false);
return next;
});
};
const toggleBurger = () => {
setOpen((v) => {
const next = !v;
if (next) setProfileOpen(false);
return next;
});
};
return (
<>
<nav className="fixed top-0 w-full z-50 bg-primary text-primary transition-theme">
<div className="w-full flex justify-between items-center px-4 sm:px-6 py-4 transition-theme">
{/* Logo */}
<Link
href="/"
className="flex items-center gap-1 sm:gap-2 font-bold text-accent text-sm sm:text-base md:text-lg"
>
<Logo />
</Link>
{/* Desktop Links */}
<ul className="hidden md:flex gap-8 transition-theme">
{links.map((link) => (
<li key={link.to}>
<Link href={link.to} className="hover:opacity-80">
{link.label}
</Link>
</li>
))}
</ul>
{/* Right actions */}
<div className="flex items-center">
<AuthProfileButton
authenticated={authenticated}
profileOpen={profileOpen}
setProfileOpen={setProfileOpen}
profileRef={profileRef}
signIn={signIn}
signOut={signOut}
toggleProfile={toggleProfile}
/>
{/* Hamburger */}
<HamburgerButton
open={open}
toggleBurger={toggleBurger}
burgerRef={burgerRef}
/>
</div>
</div>
<ScrollProgressBar />
</nav>
{/* Dropdown menu */}
<div
ref={menuRef}
className={`
fixed top-[75px] left-0 z-40
w-full md:w-64 md:left-auto md:right-6
origin-top transition-all duration-100
${open ? 'opacity-100 scale-y-100' : 'opacity-0 scale-y-0 pointer-events-none'}
`}
>
<div className="overflow-hidden bg-primary border border-border md:rounded-xl md:shadow-lg transition-theme">
<ul className="flex flex-col px-6 py-4 gap-4 transition-theme">
{links.map((link) => (
<li key={link.to}>
<Link
className="hover:text-accent hover:opacity-80"
href={link.to}
onClick={() => setOpen(false)}
>
{link.label}
</Link>
</li>
))}
{/* Theme + Language switch */}
<li className="pt-2 border-t border-border">
<LocaleSwitcher />
<ThemeSwitcher />
</li>
</ul>
</div>
</div>
</>
);
}
@@ -0,0 +1,40 @@
'use client';
import { useEffect, useState } from 'react';
export default function ScrollProgressBar() {
const [scroll, setScroll] = useState(0);
useEffect(() => {
const handleScroll = () => {
const totalHeight =
document.documentElement.scrollHeight -
document.documentElement.clientHeight;
if (totalHeight <= 0) {
setScroll(100);
return;
}
const percent = (window.scrollY / totalHeight) * 100;
setScroll(percent);
};
handleScroll(); // initial run
window.addEventListener('scroll', handleScroll, { passive: true });
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return (
<div className="top-0 left-0 w-full h-[3px] z-10">
<div
className="h-full transition-[width] duration-100 ease-out"
style={{
width: `${scroll}%`,
background: 'linear-gradient(to right, var(--accent), #7b2ff7)',
}}
/>
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
'use client';
import { useTheme } from '@/hooks/useTheme';
import { useTranslations } from 'next-intl';
export function ThemeSwitcher() {
const { dark, toggleTheme } = useTheme();
const t = useTranslations('theme');
return (
<button
onClick={toggleTheme}
className="flex items-center gap-2 w-full py-2 hover:opacity-80 cursor-pointer hover:text-accent"
>
<span className="text-lg">{dark ? '🌙' : '☀️'}</span>
<span>{dark ? t('dark') : t('light')}</span>
</button>
);
}
+117
View File
@@ -0,0 +1,117 @@
@import 'tailwindcss';
/* =========================
GLOBAL BASE STYLES
========================= */
html,
body {
background: var(--bg-primary);
color: var(--text-primary);
font-family: theme('fontFamily.sans');
overflow-x: hidden;
}
/* =========================
THEME VARIABLES (DARK DEFAULT)
========================= */
:root {
--bg-primary: #000000;
--text-primary: #ffffff;
--accent: #00d4ff;
--color-base: #000000;
--color-inverse: #ffffff;
--transition-fast: 200ms ease-in-out;
--transition-normal: 300ms ease-in-out;
--transition-slow: 500ms ease-in-out;
}
/* =========================
LIGHT MODE OVERRIDE
========================= */
.light-mode {
--bg-primary: #e0e0e0;
--text-primary: #111111;
--accent: #0077ff;
--color-base: #ffffff;
--color-inverse: #000000;
}
/* =========================
UTILITY CLASSES (USE THESE INSTEAD OF bg-black etc)
========================= */
.bg-primary {
background: var(--bg-primary);
}
.text-primary {
color: var(--text-primary);
}
.text-accent {
color: var(--accent);
}
/* =========================
TRANSITIONS
========================= */
@layer utilities {
.transition-theme {
transition:
color 500ms ease,
background-color 500ms ease,
border-color 500ms ease;
}
}
/* =========================
LOGO
========================= */
.bg-logo-light {
background: var(--color-base);
}
.bg-logo-dark {
background: var(--color-inverse);
}
.text-logo-light {
color: var(--color-base);
}
.text-logo-dark {
color: var(--color-inverse);
}
/* =========================
SCROLLBAR (OPTIONAL NICE TOUCH)
========================= */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-primary);
}
::-webkit-scrollbar-thumb {
background: var(--accent);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #0099cc;
}
+61
View File
@@ -0,0 +1,61 @@
'use client';
import { useEffect, useState } from 'react';
type Theme = 'light' | 'dark';
function getCookie(name: string) {
if (typeof document === 'undefined') return null;
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop()?.split(';').shift();
return null;
}
function setCookie(value: Theme) {
document.cookie = `theme=${value}; path=/; max-age=31536000`;
}
export function useTheme() {
const [theme, setTheme] = useState<Theme>('dark');
useEffect(() => {
const cookieTheme = getCookie('theme') as Theme | null;
const rootTheme = document.documentElement.classList.contains('dark')
? 'dark'
: 'light';
const initial = cookieTheme || rootTheme || 'dark';
setTheme(initial);
document.documentElement.classList.toggle('dark', initial === 'dark');
document.documentElement.classList.toggle(
'light-mode',
initial === 'light',
);
}, []);
function applyTheme(t: Theme) {
document.documentElement.classList.toggle('dark', t === 'dark');
document.documentElement.classList.toggle('light-mode', t === 'light');
setCookie(t);
}
function toggleTheme() {
setTheme((prev) => {
const next = prev === 'dark' ? 'light' : 'dark';
applyTheme(next);
return next;
});
}
return {
theme,
dark: theme === 'dark',
toggleTheme,
};
}
+5
View File
@@ -0,0 +1,5 @@
import { createNavigation } from 'next-intl/navigation';
import { routing } from './routing';
export const { Link, redirect, usePathname, useRouter, getPathname } =
createNavigation(routing);
+15
View File
@@ -0,0 +1,15 @@
import { getRequestConfig } from 'next-intl/server';
import { hasLocale } from 'next-intl';
import { routing } from './routing';
export default getRequestConfig(async ({ requestLocale }) => {
const requested = await requestLocale;
const locale = hasLocale(routing.locales, requested)
? requested
: routing.defaultLocale;
return {
locale,
messages: (await import(`../../messages/${locale}.json`)).default,
};
});
+16
View File
@@ -0,0 +1,16 @@
import { defineRouting } from 'next-intl/routing';
export const routing = defineRouting({
locales: ['en', 'fr'],
defaultLocale: 'en',
});
const localeLabels = {
en: 'English',
fr: 'Français',
} as const;
export const locales = routing.locales.map((code) => ({
code,
label: localeLabels[code],
}));
+149
View File
@@ -0,0 +1,149 @@
import { NextAuthOptions } from 'next-auth';
import KeycloakProvider from 'next-auth/providers/keycloak';
import { JWT } from 'next-auth/jwt';
declare module 'next-auth' {
interface Session {
accessToken?: string;
roles?: string[];
error?: string;
}
}
declare module 'next-auth/jwt' {
interface JWT {
accessToken?: string;
refreshToken?: string;
accessTokenExpires?: number;
error?: string;
roles?: string[];
}
}
function decode(token: string) {
try {
const base64 = token.split('.')[1];
return JSON.parse(Buffer.from(base64, 'base64').toString('utf-8'));
} catch {
return null;
}
}
async function refreshAccessToken(token: JWT): Promise<JWT> {
try {
if (!token.refreshToken) {
throw new Error('No refresh token');
}
const response = await fetch(
`${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/token`,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: process.env.KEYCLOAK_CLIENT_ID!,
client_secret: process.env.KEYCLOAK_CLIENT_SECRET!,
grant_type: 'refresh_token',
refresh_token: token.refreshToken,
}),
},
);
if (!response.ok) {
throw new Error('Refresh failed');
}
const refreshed = await response.json();
const decoded = decode(refreshed.access_token);
return {
...token,
accessToken: refreshed.access_token,
refreshToken: refreshed.refresh_token ?? token.refreshToken,
accessTokenExpires: decoded?.exp
? decoded.exp * 1000
: Date.now() + 5 * 60 * 1000,
error: undefined,
};
} catch {
return {
...token,
error: 'RefreshAccessTokenError',
};
}
}
export const authOptions: NextAuthOptions = {
providers: [
KeycloakProvider({
clientId: process.env.KEYCLOAK_CLIENT_ID!,
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,
issuer: process.env.KEYCLOAK_ISSUER!,
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async jwt({ token, account }) {
if (token.error === 'RefreshAccessTokenError') return token;
// initial login
if (account) {
const decoded = decode(account.access_token!);
const clientId = process.env.KEYCLOAK_CLIENT_ID!;
const realmRoles = decoded?.realm_access?.roles ?? [];
const clientRoles = decoded?.resource_access?.[clientId]?.roles ?? [];
token.roles = [...new Set([...realmRoles, ...clientRoles])];
token.accessToken = account.access_token;
token.refreshToken = account.refresh_token;
token.accessTokenExpires = decoded?.exp
? decoded.exp * 1000
: Date.now() + 5 * 60 * 1000;
return token;
}
// stop loop if refresh already failed
if (
token.accessTokenExpires &&
Date.now() > token.accessTokenExpires - 60_000
) {
return { ...token, error: 'RefreshAccessTokenError' };
}
// still valid
if (token.accessTokenExpires && Date.now() < token.accessTokenExpires) {
return token;
}
// refresh expired token
return await refreshAccessToken(token);
},
async session({ session, token }) {
session.accessToken = token.accessToken;
session.error = token.error;
if (!token.accessToken) {
session.roles = [];
return session;
}
const payload = decode(token.accessToken);
const clientId = process.env.KEYCLOAK_CLIENT_ID!;
const realmRoles = payload?.realm_access?.roles ?? [];
const clientRoles = payload?.resource_access?.[clientId]?.roles ?? [];
session.roles = [...new Set([...realmRoles, ...clientRoles])];
return session;
},
},
};
+56
View File
@@ -0,0 +1,56 @@
import createIntlMiddleware from 'next-intl/middleware';
import { routing } from './i18n/routing';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
const protectedRoutes: Record<string, string[]> = {
'/example': ['ad'],
'/dashboard': [],
};
const intlMiddleware = createIntlMiddleware(routing);
export default async function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname;
const segments = pathname.split('/');
const locale = segments[1];
const pathWithoutLocale = '/' + segments.slice(2).join('/');
const matchedRoute = Object.keys(protectedRoutes).find((route) => {
return (
pathWithoutLocale === route || pathWithoutLocale.startsWith(route + '/')
);
});
// Short-circuit: skip token fetch entirely for public routes
if (!matchedRoute) {
return intlMiddleware(req);
}
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
if (!token) {
const url = req.nextUrl.clone();
url.pathname = '/api/auth/signin';
url.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(url);
}
const requiredRoles = protectedRoutes[matchedRoute];
if (requiredRoles.length > 0) {
const userRoles = token.roles ?? [];
const hasRole = requiredRoles.some((role) => userRoles.includes(role));
if (!hasRole) {
const url = req.nextUrl.clone();
url.pathname = `/${locale}/403`;
return NextResponse.redirect(url);
}
}
return intlMiddleware(req);
}
export const config = {
matcher: ['/((?!api|trpc|_next|_vercel|.*\\..*).*)'],
};
+34
View File
@@ -0,0 +1,34 @@
{
"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": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}