@poadio/starter-next 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/.dockerignore +18 -0
  2. package/.env.example +8 -0
  3. package/Dockerfile +45 -0
  4. package/Dockerfile.dockerignore +18 -0
  5. package/README.md +197 -2
  6. package/bun.lock +156 -0
  7. package/gitignore +37 -0
  8. package/next.config.ts +14 -0
  9. package/package.json +72 -4
  10. package/public/logo.svg +1 -0
  11. package/public/providers/google.svg +1 -0
  12. package/public/providers/keycloak.svg +1 -0
  13. package/scripts/dev.mjs +92 -0
  14. package/scripts/env.mjs +160 -0
  15. package/scripts/env.test.mjs +93 -0
  16. package/src/app/(auth)/login/login-form.tsx +258 -0
  17. package/src/app/(auth)/login/page.tsx +16 -0
  18. package/src/app/(auth)/mfa/mfa-form.tsx +55 -0
  19. package/src/app/(auth)/mfa/page.tsx +16 -0
  20. package/src/app/(auth)/reset/page.tsx +16 -0
  21. package/src/app/(auth)/reset/reset-form.tsx +51 -0
  22. package/src/app/app/account/account.css +36 -0
  23. package/src/app/app/account/account.tsx +476 -0
  24. package/src/app/app/account/page.tsx +18 -0
  25. package/src/app/app/dashboard.tsx +58 -0
  26. package/src/app/app/hello/[name]/page.tsx +38 -0
  27. package/src/app/app/layout.tsx +12 -0
  28. package/src/app/app/page.tsx +18 -0
  29. package/src/app/app/public/page.tsx +15 -0
  30. package/src/app/app/public/public-content.tsx +31 -0
  31. package/src/app/globals.css +271 -0
  32. package/src/app/home.css +186 -0
  33. package/src/app/home.tsx +92 -0
  34. package/src/app/icon.svg +1 -0
  35. package/src/app/layout.tsx +59 -0
  36. package/src/app/not-found.tsx +6 -0
  37. package/src/app/page.tsx +6 -0
  38. package/src/app/providers.tsx +24 -0
  39. package/src/app/setup/page.tsx +39 -0
  40. package/src/app/shell.css +752 -0
  41. package/src/app.meta.ts +41 -0
  42. package/src/components/brand.tsx +15 -0
  43. package/src/components/captcha.tsx +93 -0
  44. package/src/components/link-button.tsx +9 -0
  45. package/src/components/rich.tsx +14 -0
  46. package/src/components/shell/app-menu.tsx +127 -0
  47. package/src/components/shell/app-shell.tsx +268 -0
  48. package/src/components/shell/page-title.tsx +29 -0
  49. package/src/components/shell/switches.tsx +35 -0
  50. package/src/components/shell/use-layout.ts +123 -0
  51. package/src/core/auth.tsx +228 -0
  52. package/src/core/env.server.ts +83 -0
  53. package/src/core/env.tsx +48 -0
  54. package/src/core/guards.tsx +74 -0
  55. package/src/core/messages.ts +18 -0
  56. package/src/core/providers.ts +32 -0
  57. package/src/core/theme-script.ts +7 -0
  58. package/src/core/theme.tsx +37 -0
  59. package/src/i18n/client.tsx +47 -0
  60. package/src/i18n/en.ts +228 -0
  61. package/src/i18n/fr.ts +251 -0
  62. package/src/i18n/index.ts +38 -0
  63. package/src/i18n/server.ts +19 -0
  64. package/tsconfig.json +21 -0
@@ -0,0 +1,92 @@
1
+ // bun start : tout ce qu'il faut pour travailler, y compris juste après un
2
+ // git clone sur un poste où rien n'est installé :
3
+ // 1. les dépendances, si node_modules manque ;
4
+ // 2. le projet poad local (poad/config.toml ici ou dans un dossier parent),
5
+ // s'il ne tourne pas : « poad start » crée les secrets de ce poste, la
6
+ // base, applique les migrations et le seed, remplace les ports déjà pris
7
+ // et lance les services du projet (Keycloak, Valkey…) ;
8
+ // 3. POAD_URL et POAD_ANON_KEY lus dans le projet poad, sauf s'ils sont déjà
9
+ // donnés (.env*, environnement), POAD_APP (nom d'application : poad.app
10
+ // du package.json), puis next dev sur un port libre.
11
+ // Le projet poad et les dépendances peuvent être dans un dossier parent
12
+ // (apps/<nom> d'un projet à plusieurs fronts).
13
+ // Les arguments sont passés à next dev : bun start --port 3300 (port fixe)
14
+ import { spawn, spawnSync } from 'node:child_process';
15
+ import { existsSync, readFileSync } from 'node:fs';
16
+ import { connect, createServer } from 'node:net';
17
+ import { dirname, join } from 'node:path';
18
+
19
+ const windows = process.platform === 'win32';
20
+ const { root, findPoadProject, poadDefaults } = await import('./env.mjs');
21
+ // node_modules du front, ou d'un dossier parent : dans un projet à plusieurs
22
+ // fronts (apps/<nom>, bun workspaces), les dépendances sont à la racine
23
+ const findBin = (name) => {
24
+ for (let dir = root; ; dir = dirname(dir)) {
25
+ const bin = join(dir, 'node_modules', '.bin', windows ? `${name}.cmd` : name);
26
+ if (existsSync(bin)) return bin;
27
+ if (dirname(dir) === dir) return null;
28
+ }
29
+ };
30
+ let nextBin = findBin('next');
31
+
32
+ // 1. Dépendances : bun s'il est là, sinon npm
33
+ if (!nextBin) {
34
+ console.log('Dependencies are missing: installing them.');
35
+ const tried = ['bun', 'npm'].some((cmd) => {
36
+ const r = spawnSync(cmd, ['install'], { cwd: root, stdio: 'inherit', shell: windows });
37
+ return !r.error && r.status === 0;
38
+ });
39
+ nextBin = findBin('next');
40
+ if (!tried || !nextBin) {
41
+ console.error('Dependencies could not be installed: run "bun install" (or "npm install"), then "bun start" again.');
42
+ process.exit(1);
43
+ }
44
+ }
45
+
46
+ // 2. Projet poad local : démarré s'il ne tourne pas (sans effet sinon) ;
47
+ // POAD_SKIP_START : déjà fait par le bun start de la racine du projet
48
+ const project = process.env.POAD_URL || process.env.POAD_SKIP_START ? null : findPoadProject(root);
49
+ if (project) {
50
+ const r = spawnSync('poad', ['start', '--quiet'], { cwd: project, stdio: 'inherit', shell: windows });
51
+ if (r.error && r.error.code === 'ENOENT') console.warn('The poad CLI is not installed: the local backend was not started (npm install -g poad, then "poad start").');
52
+ else if (r.error || r.status) console.warn('The local poad project did not start: the application will not reach its backend ("poad start" to see why).');
53
+ }
54
+
55
+ // 3. Variables : celles du projet poad, seulement si rien ne les donne déjà
56
+ const added = poadDefaults('development');
57
+ const given = Object.keys(added);
58
+ console.log(`[env] ${given.length ? `from the poad project: ${given.join(', ')}` : 'POAD_* from .env* or the environment'}`);
59
+
60
+ /** Premier port libre à partir de start */
61
+ // Rien n'y répond (IPv4 ni IPv6 : un serveur sur [::1] seul n'empêche pas
62
+ // d'écouter sur 127.0.0.1, mais localhost peut y mener) et on peut y écouter
63
+ const answers = (port, host) =>
64
+ new Promise((ok) => {
65
+ const c = connect({ port, host });
66
+ c.setTimeout(500, () => c.destroy() && ok(false));
67
+ c.once('connect', () => c.destroy() && ok(true));
68
+ c.once('error', () => ok(false));
69
+ });
70
+ const bindable = (port) =>
71
+ new Promise((ok) => {
72
+ const s = createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
73
+ s.listen(port, '127.0.0.1');
74
+ });
75
+ const free = async (port) => !(await answers(port, '127.0.0.1')) && !(await answers(port, '::1')) && (await bindable(port));
76
+ async function freePort(start) {
77
+ for (let port = start; port < start + 100; port++) if (await free(port)) return port;
78
+ return start;
79
+ }
80
+
81
+ const args = process.argv.slice(2);
82
+ if (!args.some((a) => a === '-p' || a === '--port' || a.startsWith('--port='))) {
83
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
84
+ const port = await freePort(Number(process.env.PORT) || Number(pkg.poad?.port) || 3300);
85
+ args.push('--port', String(port));
86
+ }
87
+
88
+ const next = spawn(nextBin, ['dev', ...args], { cwd: root, stdio: 'inherit', shell: windows, env: { ...process.env, ...added } });
89
+ const stop = () => next.kill();
90
+ process.on('SIGINT', stop);
91
+ process.on('SIGTERM', stop);
92
+ next.on('exit', (code) => process.exit(code ?? 0));
@@ -0,0 +1,160 @@
1
+ // Variables d'environnement du front, à la Next.js.
2
+ //
3
+ // Next.js lit lui-même, du moins au plus prioritaire, puis l'environnement du processus :
4
+ // .env .env.<mode> .env.local .env.<mode>.local (mode : development, production)
5
+ //
6
+ // Ce module ajoute le branchement automatique sur le projet poad local : sans
7
+ // POAD_URL ni POAD_ANON_KEY (ni dans les fichiers .env*, ni dans
8
+ // l'environnement), elles sont lues dans poad/config.toml et poad/secrets.toml
9
+ // (ce dossier ou un parent). scripts/dev.mjs les passe alors à next dev.
10
+ //
11
+ // Les valeurs ne sont JAMAIS compilées dans le code : le serveur Next.js les
12
+ // lit à chaque requête (src/core/env.server.ts) et n'envoie au navigateur que
13
+ // les variables PUBLIC_*, NEXT_PUBLIC_* et POAD_URL, POAD_ANON_KEY, POAD_MAIL_URL,
14
+ // POAD_APP ; il y ajoute les variables publiques du projet poad pour cette
15
+ // application (/env/v1?app=<POAD_APP>), que les valeurs locales remplacent.
16
+ //
17
+ // node scripts/env.mjs [mode] affiche les variables que verra le navigateur (noms seulement)
18
+ import { existsSync, readFileSync } from 'node:fs';
19
+ import { dirname, join, resolve } from 'node:path';
20
+ import { fileURLToPath, pathToFileURL } from 'node:url';
21
+
22
+ export const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
23
+
24
+ // POAD_APP : nom d'application du front (variables publiques par application,
25
+ // /env/v1?app=<nom>) ; un nom, rien de secret
26
+ const POAD_KEYS = ['POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL', 'POAD_APP'];
27
+ const APP_RE = /^[a-z][a-z0-9-]{0,62}$/;
28
+
29
+ /**
30
+ * Nom d'application du front : POAD_APP, sinon poad.app du package.json, sinon
31
+ * le nom du paquet (sans scope) ; '' si aucun n'est un nom valide (valeurs
32
+ * communes seulement). Même règle que l'engine : a-z, 0-9, « - ».
33
+ */
34
+ export function appName(dir = root, env = process.env) {
35
+ if (APP_RE.test(env.POAD_APP ?? '')) return env.POAD_APP;
36
+ let pkg = {};
37
+ try {
38
+ pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
39
+ } catch {
40
+ return '';
41
+ }
42
+ if (APP_RE.test(pkg.poad?.app ?? '')) return pkg.poad.app;
43
+ const name = String(pkg.name ?? '')
44
+ .replace(/^@[^/]+\//, '')
45
+ .toLowerCase()
46
+ .replace(/[^a-z0-9-]+/g, '-')
47
+ .replace(/^[^a-z]+|-+$/g, '')
48
+ .slice(0, 63);
49
+ return APP_RE.test(name) ? name : '';
50
+ }
51
+
52
+ /** Même règle que src/core/env.server.ts */
53
+ export const isPublic = (key) => key.startsWith('PUBLIC_') || key.startsWith('NEXT_PUBLIC_') || POAD_KEYS.includes(key);
54
+
55
+ /** Lecture d'un fichier .env : KEY=valeur, guillemets, commentaires, « export » */
56
+ export function parseDotenv(text) {
57
+ const out = {};
58
+ for (const raw of text.split(/\r?\n/)) {
59
+ const line = raw.trim();
60
+ if (!line || line.startsWith('#')) continue;
61
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
62
+ if (!m) continue;
63
+ let v = m[2];
64
+ const quoted = /^(['"])([\s\S]*)\1$/.exec(v);
65
+ if (quoted) v = quoted[1] === '"' ? quoted[2].replace(/\\n/g, '\n').replace(/\\"/g, '"') : quoted[2];
66
+ else v = v.replace(/\s+#.*$/, '').trim();
67
+ out[m[1]] = v;
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /** Sections et clés d'un fichier TOML simple (pas de tableaux ni de multilignes) */
73
+ export function parseToml(file, conf = {}) {
74
+ if (!existsSync(file)) return conf;
75
+ let section = '';
76
+ for (const raw of readFileSync(file, 'utf8').split(/\r?\n/)) {
77
+ const line = raw.replace(/#.*$/, '').trim();
78
+ const s = /^\[([^\]]+)\]$/.exec(line);
79
+ if (s) {
80
+ section = s[1].trim();
81
+ continue;
82
+ }
83
+ const kv = /^([A-Za-z0-9_.-]+)\s*=\s*"?([^"]*)"?$/.exec(line);
84
+ if (kv) (conf[section] ??= {})[kv[1]] = kv[2];
85
+ }
86
+ return conf;
87
+ }
88
+
89
+ /** Dossier du projet poad (poad/config.toml) : from ou un parent, sinon null */
90
+ export function findPoadProject(from = root) {
91
+ for (let dir = from; ; dir = dirname(dir)) {
92
+ if (existsSync(join(dir, 'poad', 'config.toml'))) return dir;
93
+ if (dirname(dir) === dir) return null;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * URL, clé anon et boîte e-mail du projet poad local : poad/config.toml, et
99
+ * poad/secrets.toml pour la clé (CLI 2.12 et plus ; avant, dans config.toml)
100
+ */
101
+ export function fromPoadProject(from = root) {
102
+ const dir = findPoadProject(from);
103
+ if (!dir) return {};
104
+ const conf = parseToml(join(dir, 'poad', 'config.toml'));
105
+ parseToml(join(dir, 'poad', 'secrets.toml'), conf);
106
+ const out = {};
107
+ if (conf.web?.port) out.POAD_URL = `http://localhost:${conf.web.port}`;
108
+ if (conf.auth?.anon) out.POAD_ANON_KEY = conf.auth.anon;
109
+ // [mail] depuis l'engine 0.7.0 (Mailpit), [inbucket] avant
110
+ const mail = conf.mail?.port ?? conf.inbucket?.port;
111
+ if (mail) out.POAD_MAIL_URL = `http://localhost:${mail}`;
112
+ return out;
113
+ }
114
+
115
+ /** Variables des fichiers .env*, dans l'ordre de Next.js */
116
+ export function fromDotenvFiles(mode = 'development', dir = root) {
117
+ let vars = {};
118
+ const files = ['.env', `.env.${mode}`, ...(mode === 'test' ? [] : ['.env.local']), `.env.${mode}.local`];
119
+ for (const name of files) {
120
+ const file = join(dir, name);
121
+ if (existsSync(file)) vars = { ...vars, ...parseDotenv(readFileSync(file, 'utf8')) };
122
+ }
123
+ return vars;
124
+ }
125
+
126
+ /**
127
+ * Variables du projet poad local à AJOUTER à l'environnement de next dev :
128
+ * seulement celles que ni les fichiers .env*, ni l'environnement ne donnent
129
+ * (Next.js ne remplace jamais une variable déjà présente dans le processus).
130
+ */
131
+ export function poadDefaults(mode = 'development', env = process.env, dir = root) {
132
+ const given = { ...fromDotenvFiles(mode, dir), ...env };
133
+ const out = {};
134
+ const app = appName(dir, {});
135
+ for (const [k, v] of Object.entries({ ...fromPoadProject(dir), ...(app ? { POAD_APP: app } : {}) })) {
136
+ if (given[k] === undefined || given[k] === '') out[k] = v;
137
+ }
138
+ return out;
139
+ }
140
+
141
+ /** Variables qu'aura le navigateur (même règle que le serveur) */
142
+ export function publicEnv(mode = 'development', env = process.env, dir = root) {
143
+ const app = appName(dir, {});
144
+ const vars = { ...fromPoadProject(dir), ...(app ? { POAD_APP: app } : {}), ...fromDotenvFiles(mode, dir), ...env };
145
+ return Object.fromEntries(
146
+ Object.entries(vars)
147
+ .filter(([k, v]) => isPublic(k) && v !== undefined && v !== '')
148
+ .sort(([a], [b]) => a.localeCompare(b)),
149
+ );
150
+ }
151
+
152
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
153
+ const mode = process.argv[2] || process.env.NODE_ENV || 'development';
154
+ const env = publicEnv(mode);
155
+ // Les noms seulement : la clé anon est publique, mais n'a rien à faire dans un journal
156
+ console.log(`[env] ${mode} : ${Object.keys(env).join(', ') || 'aucune variable'}`);
157
+ if (!env.POAD_URL || !env.POAD_ANON_KEY) {
158
+ console.warn('[env] POAD_URL ou POAD_ANON_KEY manquant : `poad init` ici, ou renseignez-les dans .env.local');
159
+ }
160
+ }
@@ -0,0 +1,93 @@
1
+ // node --test scripts/*.test.mjs : variables du front et contrat du modèle (poad create)
2
+ import { test } from 'node:test';
3
+ import assert from 'node:assert/strict';
4
+ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { appName, fromPoadProject, isPublic, parseDotenv, poadDefaults, publicEnv, root } from './env.mjs';
8
+
9
+ /** Projet poad factice : poad/config.toml, poad/secrets.toml (valeurs de test, pas de vrai secret) */
10
+ function fakeProject() {
11
+ const dir = mkdtempSync(join(tmpdir(), 'starter-next-'));
12
+ mkdirSync(join(dir, 'poad'));
13
+ writeFileSync(join(dir, 'poad', 'config.toml'), '[web]\nport = 41234 # gateway\n\n[mail]\nport = 41235\n');
14
+ writeFileSync(join(dir, 'poad', 'secrets.toml'), '[auth]\nanon = "test-anon"\n');
15
+ const app = join(dir, 'app');
16
+ mkdirSync(app);
17
+ return { dir, app };
18
+ }
19
+
20
+ test('parseDotenv : guillemets, commentaires, export', () => {
21
+ assert.deepEqual(parseDotenv('# c\nA=1\nexport B="x y"\nC=\'z\' \nD=v # fin\n'), { A: '1', B: 'x y', C: 'z', D: 'v' });
22
+ });
23
+
24
+ test('isPublic : PUBLIC_*, NEXT_PUBLIC_*, POAD_URL / ANON_KEY / MAIL_URL seulement', () => {
25
+ for (const k of ['PUBLIC_X', 'NEXT_PUBLIC_Y', 'POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL']) assert.ok(isPublic(k), k);
26
+ for (const k of ['POAD_SERVICE_KEY', 'DATABASE_URL', 'SECRET', 'PATH']) assert.ok(!isPublic(k), k);
27
+ });
28
+
29
+ test('fromPoadProject : lit le projet dans un dossier parent', () => {
30
+ const { dir, app } = fakeProject();
31
+ try {
32
+ assert.deepEqual(fromPoadProject(app), { POAD_URL: 'http://localhost:41234', POAD_ANON_KEY: 'test-anon', POAD_MAIL_URL: 'http://localhost:41235' });
33
+ } finally {
34
+ rmSync(dir, { recursive: true, force: true });
35
+ }
36
+ });
37
+
38
+ test('poadDefaults : .env* et l’environnement l’emportent sur le projet poad', () => {
39
+ const { dir, app } = fakeProject();
40
+ try {
41
+ assert.deepEqual(Object.keys(poadDefaults('development', {}, app)).sort(), ['POAD_ANON_KEY', 'POAD_MAIL_URL', 'POAD_URL']);
42
+ writeFileSync(join(app, '.env.local'), 'POAD_URL=https://example.test\n');
43
+ const d = poadDefaults('development', { POAD_ANON_KEY: 'from-env' }, app);
44
+ assert.deepEqual(Object.keys(d), ['POAD_MAIL_URL']);
45
+ const pub = publicEnv('development', { POAD_ANON_KEY: 'from-env', OTHER: 'no' }, app);
46
+ assert.equal(pub.POAD_URL, 'https://example.test');
47
+ assert.equal(pub.POAD_ANON_KEY, 'from-env');
48
+ assert.equal(pub.OTHER, undefined);
49
+ } finally {
50
+ rmSync(dir, { recursive: true, force: true });
51
+ }
52
+ });
53
+
54
+ test('appName : POAD_APP, sinon poad.app, sinon le nom du paquet ; passé à next dev', () => {
55
+ const { dir, app } = fakeProject();
56
+ try {
57
+ assert.equal(appName(app, {}), '');
58
+ writeFileSync(join(app, 'package.json'), JSON.stringify({ name: '@acme/Site_Web' }));
59
+ assert.equal(appName(app, {}), 'site-web');
60
+ writeFileSync(join(app, 'package.json'), JSON.stringify({ name: 'web', poad: { app: 'admin' } }));
61
+ assert.equal(appName(app, {}), 'admin');
62
+ assert.equal(appName(app, { POAD_APP: 'shop' }), 'shop');
63
+ assert.equal(appName(app, { POAD_APP: 'Not Valid' }), 'admin');
64
+ // Projet à plusieurs fronts : POAD_APP ajouté pour next dev, sauf s'il est donné
65
+ assert.equal(poadDefaults('development', {}, app).POAD_APP, 'admin');
66
+ assert.equal(poadDefaults('development', { POAD_APP: 'shop' }, app).POAD_APP, undefined);
67
+ assert.equal(publicEnv('development', {}, app).POAD_APP, 'admin');
68
+ assert.ok(isPublic('POAD_APP'));
69
+ } finally {
70
+ rmSync(dir, { recursive: true, force: true });
71
+ }
72
+ });
73
+
74
+ test('package.json : contrat du modèle attendu par poad create', () => {
75
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
76
+ assert.equal(pkg.name, '@poadio/starter-next');
77
+ assert.equal(pkg.publishConfig?.access, 'public');
78
+ assert.match(pkg.packageManager, /^bun@/);
79
+ const tpl = pkg.poad?.template;
80
+ assert.equal(tpl.framework, 'next');
81
+ // Lit les variables publiques de son application (/env/v1?app=) : poad create le sait
82
+ assert.equal(tpl.appEnv, true);
83
+ assert.ok(tpl.label && tpl.description && tpl.port);
84
+ assert.ok(Array.isArray(tpl.gitignore) && tpl.gitignore.includes('/.next/'));
85
+ // Port gardé après poad create (qui retire poad.template)
86
+ assert.equal(pkg.poad.port, tpl.port);
87
+ for (const f of ['src', 'public', '!public/env.json', 'scripts', 'gitignore', 'Dockerfile', 'Dockerfile.dockerignore']) assert.ok(pkg.files.includes(f), f);
88
+ for (const f of ['node_modules', '.next', '.env.local', 'poad']) assert.ok(!pkg.files.includes(f), f);
89
+ });
90
+
91
+ test('gitignore (publié) et .gitignore (dépôt) sont identiques', () => {
92
+ assert.equal(readFileSync(join(root, 'gitignore'), 'utf8'), readFileSync(join(root, '.gitignore'), 'utf8'));
93
+ });
@@ -0,0 +1,258 @@
1
+ 'use client';
2
+ import { useRef, useState, type FormEvent } from 'react';
3
+ import Link from 'next/link';
4
+ import { PoadButton, PoadCard, PoadDivider, PoadField, PoadIcon, PoadInput, PoadMessage, PoadPassword, PoadTab, PoadTabs } from '@poadio/ui-react';
5
+ import type { Result } from '@poadio/client-js';
6
+ import { Brand } from '@/components/brand';
7
+ import { Captcha, type CaptchaHandle } from '@/components/captcha';
8
+ import { Rich } from '@/components/rich';
9
+ import { useAuth } from '@/core/auth';
10
+ import { providerLabel, providerLogo } from '@/core/providers';
11
+ import { useT } from '@/i18n/client';
12
+ import type { MessageKey } from '@/i18n';
13
+
14
+ type Sent = { email: string; type: 'signup' | 'email' | 'recovery' };
15
+
16
+ /** Le formulaire ne recharge jamais la page */
17
+ const submit = (fn: () => unknown) => (e: FormEvent) => {
18
+ e.preventDefault();
19
+ void fn();
20
+ };
21
+
22
+ export function LoginForm() {
23
+ const auth = useAuth();
24
+ const t = useT();
25
+ const poad = auth.poad!;
26
+ const [tab, setTab] = useState('password');
27
+ const [busy, setBusy] = useState(false);
28
+ /** Fournisseur (ou « anonymous ») en cours, pour l'indicateur du bon bouton */
29
+ const [pending, setPending] = useState<string | null>(null);
30
+ const [email, setEmail] = useState('');
31
+ const [password, setPassword] = useState('');
32
+ const [name, setName] = useState('');
33
+ const [code, setCode] = useState('');
34
+ /** Adresse à laquelle un code vient d'être envoyé, et pour quoi */
35
+ const [sent, setSent] = useState<Sent | null>(null);
36
+
37
+ /** CAPTCHA exigé par le service (/settings) */
38
+ const c = auth.settings?.captcha;
39
+ const captcha = c && c.site_key ? { provider: c.provider, siteKey: c.site_key } : null;
40
+ const [captchaToken, setCaptchaToken] = useState<string | null>(null);
41
+ const widget = useRef<CaptchaHandle>(null);
42
+ /** Envoi impossible tant que le CAPTCHA exigé n'est pas résolu */
43
+ const blocked = Boolean(captcha) && !captchaToken;
44
+ const token = captchaToken ?? undefined;
45
+
46
+ async function call<T>(fn: () => Promise<Result<T>>, success?: string): Promise<T | null> {
47
+ setBusy(true);
48
+ try {
49
+ return await auth.run(fn, success);
50
+ } finally {
51
+ setBusy(false);
52
+ // Un jeton CAPTCHA ne sert qu'une fois
53
+ widget.current?.reset();
54
+ }
55
+ }
56
+
57
+ const signIn = () => call(() => poad.auth.signInWithPassword({ email, password, captchaToken: token }));
58
+
59
+ const signUp = async () => {
60
+ const data = await call(() =>
61
+ poad.auth.signUp({ email, password, data: name ? { name } : {}, redirectTo: auth.redirect('/app'), captchaToken: token }),
62
+ );
63
+ if (data && !data.session) setSent({ email, type: 'signup' });
64
+ };
65
+
66
+ const sendLink = async () => {
67
+ const data = await call(() => poad.auth.signInWithOtp({ email, redirectTo: auth.redirect('/app'), captchaToken: token }), t('login.emailSent'));
68
+ if (data) setSent({ email, type: 'email' });
69
+ };
70
+
71
+ const sendRecovery = async () => {
72
+ const data = await call(
73
+ () => poad.auth.resetPasswordForEmail(email, { redirectTo: auth.redirect('/reset'), captchaToken: token }),
74
+ t('login.recoverySent'),
75
+ );
76
+ if (data) setSent({ email, type: 'recovery' });
77
+ };
78
+
79
+ const verify = async () => {
80
+ if (!sent) return;
81
+ const ok = await call(() => poad.auth.verifyOtp({ email: sent.email, token: code, type: sent.type }));
82
+ if (ok) {
83
+ setSent(null);
84
+ setCode('');
85
+ }
86
+ };
87
+
88
+ const resend = async () => {
89
+ if (sent?.type !== 'signup') return;
90
+ await call(() => poad.auth.resend({ type: 'signup', email: sent.email, redirectTo: auth.redirect('/app'), captchaToken: token }), t('login.resent'));
91
+ };
92
+
93
+ const oauth = async (provider: string) => {
94
+ // La page part chez le fournisseur : l'indicateur reste jusqu'au départ
95
+ setPending(provider);
96
+ await call(() => poad.auth.signInWithOAuth({ provider, redirectTo: auth.redirect('/app') }));
97
+ };
98
+
99
+ const anonymous = async () => {
100
+ setPending('anonymous');
101
+ await call(() => poad.auth.signInAnonymously({ captchaToken: token }));
102
+ setPending(null);
103
+ };
104
+
105
+ const changeTab = (value: unknown) => {
106
+ setTab(String(value));
107
+ setSent(null);
108
+ setCode('');
109
+ };
110
+
111
+ const codeForm = (label: MessageKey, canResend = false) => (
112
+ <form className="form" onSubmit={submit(verify)}>
113
+ <PoadMessage severity="info" variant="soft" size="sm">
114
+ {t('login.sentTo', { email: sent?.email ?? '' })}{' '}
115
+ {auth.config?.mail && (
116
+ <a href={auth.config.mail} target="_blank" rel="noopener">
117
+ {t('login.openMailbox')}
118
+ </a>
119
+ )}
120
+ </PoadMessage>
121
+ <PoadField label={t(label)} required>
122
+ <PoadInput mono name="code" value={code} onChange={(e) => setCode(e.target.value)} inputMode="numeric" autoComplete="one-time-code" maxLength={6} required />
123
+ </PoadField>
124
+ <div className="row">
125
+ <PoadButton type="submit" loading={busy} disabled={code.length !== 6}>
126
+ {t('login.validate')}
127
+ </PoadButton>
128
+ {canResend && (
129
+ <PoadButton type="button" variant="text" onClick={() => void resend()}>
130
+ {t('login.resend')}
131
+ </PoadButton>
132
+ )}
133
+ <PoadButton type="button" variant="text" onClick={() => setSent(null)}>
134
+ {t('login.changeEmail')}
135
+ </PoadButton>
136
+ </div>
137
+ </form>
138
+ );
139
+
140
+ const emailField = (autoComplete: string) => (
141
+ <PoadField label={t('common.email')} required>
142
+ <PoadInput type="email" name="email" value={email} onChange={(e) => setEmail(e.target.value)} autoComplete={autoComplete} required />
143
+ </PoadField>
144
+ );
145
+
146
+ return (
147
+ <section className="auth">
148
+ <div className="auth-head">
149
+ <Link href="/">
150
+ <Brand size={32} />
151
+ </Link>
152
+ <h1>{t('login.title')}</h1>
153
+ </div>
154
+
155
+ <PoadCard>
156
+ <PoadTabs value={tab} onValueChange={changeTab} variant="line" stretch>
157
+ <PoadTab value="password" label={t('login.tabPassword')}>
158
+ <form className="form" onSubmit={submit(signIn)}>
159
+ {emailField('username')}
160
+ <PoadField plain label={t('common.password')} required>
161
+ <PoadPassword name="password" value={password} onValueChange={setPassword} toggleMask autoComplete="current-password" />
162
+ </PoadField>
163
+ <div className="row">
164
+ <PoadButton type="submit" loading={busy} disabled={!email || !password || blocked}>
165
+ <PoadIcon name="log-in" size={16} /> {t('common.signIn')}
166
+ </PoadButton>
167
+ <PoadButton type="button" variant="text" onClick={() => changeTab('recovery')}>
168
+ {t('login.forgot')}
169
+ </PoadButton>
170
+ </div>
171
+ </form>
172
+ </PoadTab>
173
+
174
+ <PoadTab value="signup" label={t('login.tabSignup')}>
175
+ {sent?.type === 'signup' ? (
176
+ codeForm('login.codeSignup', true)
177
+ ) : (
178
+ <form className="form" onSubmit={submit(signUp)}>
179
+ <PoadField label={t('common.name')} optional optionalText={t('common.optional')}>
180
+ <PoadInput name="name" value={name} onChange={(e) => setName(e.target.value)} autoComplete="name" />
181
+ </PoadField>
182
+ {emailField('email')}
183
+ <PoadField plain label={t('common.password')} required hint={t('login.minLength')}>
184
+ <PoadPassword name="password" value={password} onValueChange={setPassword} toggleMask feedback autoComplete="new-password" />
185
+ </PoadField>
186
+ <PoadButton type="submit" loading={busy} disabled={!email || !password || blocked}>
187
+ <PoadIcon name="user-plus" size={16} /> {t('login.create')}
188
+ </PoadButton>
189
+ </form>
190
+ )}
191
+ </PoadTab>
192
+
193
+ <PoadTab value="otp" label={t('login.tabOtp')}>
194
+ {sent?.type === 'email' ? (
195
+ codeForm('login.codeOtp')
196
+ ) : (
197
+ <form className="form" onSubmit={submit(sendLink)}>
198
+ <p className="muted" style={{ margin: 0 }}>
199
+ {t('login.otpHelp')}
200
+ </p>
201
+ {emailField('email')}
202
+ <PoadButton type="submit" loading={busy} disabled={!email || blocked}>
203
+ <PoadIcon name="mail" size={16} /> {t('login.send')}
204
+ </PoadButton>
205
+ </form>
206
+ )}
207
+ </PoadTab>
208
+
209
+ <PoadTab value="recovery" label={t('login.tabRecovery')}>
210
+ {sent?.type === 'recovery' ? (
211
+ codeForm('login.codeRecovery')
212
+ ) : (
213
+ <form className="form" onSubmit={submit(sendRecovery)}>
214
+ <p className="muted" style={{ margin: 0 }}>
215
+ {t('login.recoveryHelp')}
216
+ </p>
217
+ {emailField('email')}
218
+ <PoadButton type="submit" loading={busy} disabled={!email || blocked}>
219
+ <PoadIcon name="key-round" size={16} /> {t('login.sendLink')}
220
+ </PoadButton>
221
+ </form>
222
+ )}
223
+ </PoadTab>
224
+ </PoadTabs>
225
+ {captcha && <Captcha ref={widget} provider={captcha.provider} siteKey={captcha.siteKey} onToken={setCaptchaToken} />}
226
+ </PoadCard>
227
+
228
+ {auth.settings && (
229
+ <>
230
+ <PoadDivider />
231
+ <div className="providers">
232
+ <span className="muted">{t('login.or')}</span>
233
+ {auth.oauthProviders.map((p) => {
234
+ const logo = providerLogo(p);
235
+ return (
236
+ <PoadButton key={p} variant="outline" block loading={pending === p} onClick={() => void oauth(p)}>
237
+ {/* eslint-disable-next-line @next/next/no-img-element */}
238
+ {logo ? <img className="provider-logo" src={logo} alt="" /> : <PoadIcon name="log-in" size={16} />}
239
+ {t('login.continueWith', { provider: providerLabel(p) })}
240
+ </PoadButton>
241
+ );
242
+ })}
243
+ {!auth.oauthProviders.length && (
244
+ <span className="muted">
245
+ <Rich text={t('login.noProvider')} />
246
+ </span>
247
+ )}
248
+ {auth.settings.external?.['anonymous_users'] && (
249
+ <PoadButton variant="text" severity="secondary" block onClick={() => void anonymous()} loading={busy && pending === 'anonymous'} disabled={blocked}>
250
+ <PoadIcon name="user" size={16} /> {t('login.anonymous')}
251
+ </PoadButton>
252
+ )}
253
+ </div>
254
+ </>
255
+ )}
256
+ </section>
257
+ );
258
+ }
@@ -0,0 +1,16 @@
1
+ import { SignedOut } from '@/core/guards';
2
+ import { titled } from '@/i18n/server';
3
+ import { LoginForm } from './login-form';
4
+
5
+ export const generateMetadata = titled('title.login');
6
+
7
+ /** Connexion : mot de passe, inscription, lien magique, oubli, fournisseurs OAuth, sans compte */
8
+ export default function LoginPage() {
9
+ return (
10
+ <div className="screen">
11
+ <SignedOut>
12
+ <LoginForm />
13
+ </SignedOut>
14
+ </div>
15
+ );
16
+ }