diff --git a/src/Root.tsx b/src/Root.tsx index b2693d6..80b61ee 100644 --- a/src/Root.tsx +++ b/src/Root.tsx @@ -1,7 +1,7 @@ import { useEffect, useMemo, useState } from 'react' import App from './App' import AuthScreen, { NewPasswordScreen } from './components/AuthScreen' -import { consumeAuthRedirect, getSession, onSessionChange, type Session } from './lib/cloud/auth' +import { consumeAuthRedirect, getSession, hasOAuthRedirect, onSessionChange, type Session } from './lib/cloud/auth' import { cloudEnabled } from './lib/cloud/config' import { setScope } from './lib/scope' import { MediaProvider } from './store' @@ -14,7 +14,7 @@ export default function Root() { const [session, setSession] = useState(() => (cloudEnabled ? getSession() : null)) // Lien reçu par email en cours de traitement (#access_token=…) const [redirect, setRedirect] = useState<'checking' | 'recovery' | 'none'>(() => - cloudEnabled && /(^#|&)(access_token|error)=/.test(location.hash) ? 'checking' : 'none', + cloudEnabled && (/(^#|&)(access_token|error)=/.test(location.hash) || hasOAuthRedirect()) ? 'checking' : 'none', ) const [notice, setNotice] = useState() const userId = session?.user.id diff --git a/src/components/AuthScreen.tsx b/src/components/AuthScreen.tsx index 39a53b2..01ee626 100644 --- a/src/components/AuthScreen.tsx +++ b/src/components/AuthScreen.tsx @@ -2,7 +2,7 @@ import { t } from '../i18n' import { LanguageSelect } from '../i18n/react' import { Eye, EyeOff, Loader2 } from 'lucide-react' import { useState, type FormEvent, type ReactNode } from 'react' -import { PASSWORD_MIN, requestPasswordReset, signIn, signUp, updatePassword } from '../lib/cloud/auth' +import { PASSWORD_MIN, requestPasswordReset, signIn, signInWithGoogle, signUp, updatePassword } from '../lib/cloud/auth' import { cx } from '../lib/utils' type Mode = 'login' | 'signup' | 'forgot' @@ -62,6 +62,18 @@ export default function AuthScreen({ notice }: { notice?: string }) { setInfo(undefined) } + const google = async () => { + setError(undefined) + setInfo(undefined) + setBusy(true) + try { + await signInWithGoogle() + } catch (err) { + setError((err as Error).message) + setBusy(false) + } + } + const submit = async (e: FormEvent) => { e.preventDefault() setError(undefined) @@ -107,6 +119,19 @@ export default function AuthScreen({ notice }: { notice?: string }) { )} + {mode !== 'forgot' && ( + <> + +
+ + {t('auth.or')} + +
+ + )} +
{mode === 'forgot' &&

{t('auth.forgotTitle')}

} ([]) const [stack, setStack] = useState([]) const [peeked, setPeeked] = useState<{ item: MediaItem; owner?: PeekOwner }>() + // « Plus tard » sur le choix du pseudo : redemandé au prochain lancement + const [welcomeLater, setWelcomeLater] = useState(() => { + try { + return sessionStorage.getItem('azuucine:welcome-later') === '1' + } catch { + return false + } + }) + const later = useCallback(() => { + setWelcomeLater(true) + try { + sessionStorage.setItem('azuucine:welcome-later', '1') + } catch { + /* ignore */ + } + }, []) const refresh = useCallback(async () => { if (!enabled || !navigator.onLine) return @@ -127,6 +144,7 @@ export function SocialProvider({ children, onOpenOwnItem }: { children: ReactNod ), )} {children} + {enabled && me && RANDOM_USERNAME.test(me.username) && !welcomeLater && } {enabled && peeked && setPeeked(undefined)} />} ) diff --git a/src/components/social/WelcomeProfile.tsx b/src/components/social/WelcomeProfile.tsx new file mode 100644 index 0000000..2bcc144 --- /dev/null +++ b/src/components/social/WelcomeProfile.tsx @@ -0,0 +1,103 @@ +import { Loader2 } from 'lucide-react' +import { useState, type FormEvent } from 'react' +import { t } from '../../i18n' +import { updateProfile, USERNAME_RE, type ProfilePatch } from '../../lib/cloud/social' +import { cx } from '../../lib/utils' +import Avatar from './Avatar' +import { useSocial } from './SocialProvider' + +/** Pseudo attribué automatiquement à l'inscription (cinephile_xxxxxx) : pas encore choisi. */ +export const RANDOM_USERNAME = /^cinephile_[0-9a-f]{6}$/ + +/** « Zoé Ciné » → « zoe_cine » : accents retirés, espaces en _, le reste ignoré. */ +const toUsername = (v: string) => + v.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '').slice(0, 20) + +/** Premier lancement d'un compte : on choisit son pseudo (et son nom) avant tout. */ +export default function WelcomeProfile({ onLater }: { onLater: () => void }) { + const { me, refresh } = useSocial() + const suggested = me && !RANDOM_USERNAME.test(me.displayName) ? me.displayName : '' + const [displayName, setDisplayName] = useState(suggested) + const [username, setUsername] = useState('') + const [saving, setSaving] = useState(false) + const [error, setError] = useState() + + const clean = username.trim().toLowerCase().replace(/^@/, '') + const usernameOk = USERNAME_RE.test(clean) && !RANDOM_USERNAME.test(clean) + const name = displayName.trim() || clean + + const submit = async (e: FormEvent) => { + e.preventDefault() + if (!me || !usernameOk || name.length > 40) return + setSaving(true) + setError(undefined) + try { + const patch: ProfilePatch = { username: clean } + if (name !== me.displayName) patch.display_name = name + await updateProfile(patch) + await refresh() + } catch (err) { + setError((err as Error).message) + } finally { + setSaving(false) + } + } + + if (!me) return null + + return ( +
+
+
+ +
+

+ {t('welcome.titleA')} {t('welcome.titleB')} +

+

{t('welcome.text')}

+ + + + + + {error && ( +

+ {error} +

+ )} + + + + + +
+
+ ) +} diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index a2a2b83..e4bfdca 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -745,6 +745,19 @@ const dict: Translations = { 'feed.rewatched': 'sah erneut', 'feed.added': 'plant', 'feed.review': 'Meinung', + 'auth.google': "Mit Google fortfahren", + 'auth.or': "oder", + 'auth.err.google': "Anmeldung mit Google fehlgeschlagen. Bitte versuche es erneut.", + 'auth.err.storage': "Dein Browser blockiert den Speicher: Anmeldung nicht möglich.", + 'welcome.title': "Wähle deinen Benutzernamen", + 'welcome.titleA': "Willkommen bei", + 'welcome.titleB': "AzuuCine", + 'welcome.text': "Wähle einen Benutzernamen: So finden dich deine Freunde und können dir folgen.", + 'welcome.usernamePh': "dein_name", + 'welcome.namePh': "Dein Name", + 'welcome.nameHint': "Optional – wird auf deinem Profil angezeigt. Du kannst alles später ändern.", + 'welcome.go': "Los geht's", + 'welcome.later': "Später", } export default dict diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 429cf55..6cb6a24 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -745,6 +745,19 @@ const dict: Translations = { 'feed.rewatched': 'rewatched', 'feed.added': 'wants to watch', 'feed.review': 'review', + 'auth.google': "Continue with Google", + 'auth.or': "or", + 'auth.err.google': "Google sign-in failed. Please try again.", + 'auth.err.storage': "Your browser is blocking storage: unable to sign in.", + 'welcome.title': "Pick your username", + 'welcome.titleA': "Welcome to", + 'welcome.titleB': "AzuuCine", + 'welcome.text': "Pick a username: it's how your friends will find and follow you.", + 'welcome.usernamePh': "your_username", + 'welcome.namePh': "Your name", + 'welcome.nameHint': "Optional — shown on your profile. You can change everything later.", + 'welcome.go': "Let's go", + 'welcome.later': "Later", } export default dict diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 707b942..7bd8dd3 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -745,6 +745,19 @@ const dict: Translations = { 'feed.rewatched': 'volvió a ver', 'feed.added': 'quiere ver', 'feed.review': 'opinión', + 'auth.google': "Continuar con Google", + 'auth.or': "o", + 'auth.err.google': "No se pudo iniciar sesión con Google. Inténtalo de nuevo.", + 'auth.err.storage': "Tu navegador bloquea el almacenamiento: no se puede iniciar sesión.", + 'welcome.title': "Elige tu nombre de usuario", + 'welcome.titleA': "Bienvenido a", + 'welcome.titleB': "AzuuCine", + 'welcome.text': "Elige tu nombre de usuario: así te encontrarán y seguirán tus amigos.", + 'welcome.usernamePh': "tu_usuario", + 'welcome.namePh': "Tu nombre", + 'welcome.nameHint': "Opcional: se muestra en tu perfil. Podrás cambiarlo todo más tarde.", + 'welcome.go': "Vamos", + 'welcome.later': "Más tarde", } export default dict diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index c2e86d3..1ca0b61 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -747,6 +747,19 @@ const dict = { 'feed.rewatched': 'a revu', 'feed.added': 'veut voir', 'feed.review': 'avis', + 'auth.google': "Continuer avec Google", + 'auth.or': "ou", + 'auth.err.google': "La connexion avec Google a échoué. Réessaie.", + 'auth.err.storage': "Ton navigateur bloque le stockage : impossible de se connecter.", + 'welcome.title': "Choisis ton pseudo", + 'welcome.titleA': "Bienvenue sur", + 'welcome.titleB': "AzuuCine", + 'welcome.text': "Choisis ton pseudo : c'est grâce à lui que tes amis te trouveront et pourront te suivre.", + 'welcome.usernamePh': "ton_pseudo", + 'welcome.namePh': "Ton nom", + 'welcome.nameHint': "Facultatif — affiché sur ton profil. Tu pourras tout changer plus tard.", + 'welcome.go': "C'est parti", + 'welcome.later': "Plus tard", } export default dict diff --git a/src/i18n/locales/it.ts b/src/i18n/locales/it.ts index 2482ca0..8c91680 100644 --- a/src/i18n/locales/it.ts +++ b/src/i18n/locales/it.ts @@ -745,6 +745,19 @@ const dict: Translations = { 'feed.rewatched': 'ha rivisto', 'feed.added': 'vuole vedere', 'feed.review': 'opinione', + 'auth.google': "Continua con Google", + 'auth.or': "oppure", + 'auth.err.google': "Accesso con Google non riuscito. Riprova.", + 'auth.err.storage': "Il tuo browser blocca l'archiviazione: impossibile accedere.", + 'welcome.title': "Scegli il tuo username", + 'welcome.titleA': "Benvenuto su", + 'welcome.titleB': "AzuuCine", + 'welcome.text': "Scegli un username: è così che i tuoi amici ti troveranno e ti seguiranno.", + 'welcome.usernamePh': "il_tuo_username", + 'welcome.namePh': "Il tuo nome", + 'welcome.nameHint': "Facoltativo — mostrato sul tuo profilo. Potrai cambiare tutto più tardi.", + 'welcome.go': "Iniziamo", + 'welcome.later': "Più tardi", } export default dict diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts index c043473..8fd7339 100644 --- a/src/i18n/locales/ja.ts +++ b/src/i18n/locales/ja.ts @@ -745,6 +745,19 @@ const dict: Translations = { 'feed.rewatched': 'が再視聴:', 'feed.added': 'が見たい:', 'feed.review': 'レビュー', + 'auth.google': "Google で続行", + 'auth.or': "または", + 'auth.err.google': "Google でのログインに失敗しました。もう一度お試しください。", + 'auth.err.storage': "ブラウザがストレージをブロックしているため、ログインできません。", + 'welcome.title': "ユーザー名を選ぶ", + 'welcome.titleA': "ようこそ", + 'welcome.titleB': "AzuuCine へ", + 'welcome.text': "ユーザー名を選んでください。友だちはこの名前であなたを見つけてフォローできます。", + 'welcome.usernamePh': "your_name", + 'welcome.namePh': "表示名", + 'welcome.nameHint': "任意 — プロフィールに表示されます。あとからすべて変更できます。", + 'welcome.go': "はじめる", + 'welcome.later': "あとで", } export default dict diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts index 3e8e6bc..ec8e294 100644 --- a/src/i18n/locales/ko.ts +++ b/src/i18n/locales/ko.ts @@ -745,6 +745,19 @@ const dict: Translations = { 'feed.rewatched': '님이 다시 봤어요:', 'feed.added': '님이 보고 싶어 해요:', 'feed.review': '감상', + 'auth.google': "Google로 계속하기", + 'auth.or': "또는", + 'auth.err.google': "Google 로그인에 실패했어요. 다시 시도해 주세요.", + 'auth.err.storage': "브라우저가 저장소를 차단해 로그인할 수 없어요.", + 'welcome.title': "사용자 이름 선택", + 'welcome.titleA': "환영해요,", + 'welcome.titleB': "AzuuCine", + 'welcome.text': "사용자 이름을 정해 주세요. 친구들이 이 이름으로 나를 찾고 팔로우할 수 있어요.", + 'welcome.usernamePh': "your_name", + 'welcome.namePh': "내 이름", + 'welcome.nameHint': "선택 사항 — 프로필에 표시돼요. 나중에 모두 바꿀 수 있어요.", + 'welcome.go': "시작하기", + 'welcome.later': "나중에", } export default dict diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts index eca8af6..e200ab6 100644 --- a/src/i18n/locales/pt.ts +++ b/src/i18n/locales/pt.ts @@ -745,6 +745,19 @@ const dict: Translations = { 'feed.rewatched': 'reviu', 'feed.added': 'quer ver', 'feed.review': 'opinião', + 'auth.google': "Continuar com o Google", + 'auth.or': "ou", + 'auth.err.google': "Falha ao entrar com o Google. Tente novamente.", + 'auth.err.storage': "Seu navegador está bloqueando o armazenamento: não é possível entrar.", + 'welcome.title': "Escolha seu nome de usuário", + 'welcome.titleA': "Boas-vindas ao", + 'welcome.titleB': "AzuuCine", + 'welcome.text': "Escolha um nome de usuário: é assim que seus amigos vão te encontrar e seguir.", + 'welcome.usernamePh': "seu_usuario", + 'welcome.namePh': "Seu nome", + 'welcome.nameHint': "Opcional — aparece no seu perfil. Você pode mudar tudo depois.", + 'welcome.go': "Vamos lá", + 'welcome.later': "Depois", } export default dict diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index 066fe57..97ba370 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -745,6 +745,19 @@ const dict: Translations = { 'feed.rewatched': '重温了', 'feed.added': '想看', 'feed.review': '短评', + 'auth.google': "使用 Google 继续", + 'auth.or': "或", + 'auth.err.google': "Google 登录失败,请重试。", + 'auth.err.storage': "浏览器阻止了存储,无法登录。", + 'welcome.title': "选择你的用户名", + 'welcome.titleA': "欢迎来到", + 'welcome.titleB': "AzuuCine", + 'welcome.text': "选择一个用户名:朋友们会通过它找到并关注你。", + 'welcome.usernamePh': "your_name", + 'welcome.namePh': "你的名字", + 'welcome.nameHint': "可选——显示在你的主页上。之后都可以修改。", + 'welcome.go': "开始吧", + 'welcome.later': "稍后", } export default dict diff --git a/src/lib/cloud/auth.ts b/src/lib/cloud/auth.ts index c07add0..afbead6 100644 --- a/src/lib/cloud/auth.ts +++ b/src/lib/cloud/auth.ts @@ -195,6 +195,63 @@ export async function signOut(): Promise { } } +// ───────────────────────────── Connexion avec Google (OAuth + PKCE) ───────────────────────────── +// Google renvoie vers l'app avec un code à usage unique (?code=…) que seul cet appareil peut échanger, +// grâce au « vérificateur » gardé ici le temps de l'aller-retour. Aucun jeton ne passe dans l'adresse. + +const VERIFIER_KEY = 'azuucine:pkce' + +const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') + +export async function signInWithGoogle(): Promise { + const verifier = b64url(crypto.getRandomValues(new Uint8Array(48))) + const challenge = b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))) + try { + localStorage.setItem(VERIFIER_KEY, JSON.stringify({ verifier, at: Date.now() })) + } catch { + throw new AuthError(t('auth.err.storage')) + } + const params = new URLSearchParams({ + provider: 'google', + redirect_to: appUrl(), + code_challenge: challenge, + code_challenge_method: 's256', + }) + location.assign(`${SUPABASE_URL}/auth/v1/authorize?${params}`) +} + +/** Retour de Google : adresse avec ?code=… (ou ?error=…). */ +export const hasOAuthRedirect = () => /[?&](code|error)=/.test(location.search) + +async function consumeOAuthRedirect(): Promise<{ error?: string }> { + const params = new URLSearchParams(location.search) + const code = params.get('code') ?? '' + const oauthError = params.get('error_description') ?? params.get('error') + history.replaceState(null, '', `${location.pathname}#/`) + let saved: { verifier?: string; at?: number } = {} + try { + saved = JSON.parse(localStorage.getItem(VERIFIER_KEY) ?? '{}') + localStorage.removeItem(VERIFIER_KEY) + } catch { + /* ignore */ + } + if (oauthError) return { error: t('auth.err.google') } + // Vérificateur absent ou trop vieux (> 10 min) : on ne tente rien + if (!/^[A-Za-z0-9_-]{43,128}$/.test(saved.verifier ?? '') || !saved.at || Date.now() - saved.at > 600_000) { + return { error: t('auth.err.google') } + } + if (!/^[A-Za-z0-9_-]{8,256}$/.test(code)) return { error: t('auth.err.google') } + try { + const data = await gotrue('/token?grant_type=pkce', { body: { auth_code: code, code_verifier: saved.verifier } }) + const s = toSession(data) + if (!s) return { error: t('auth.err.response') } + setSession(s) + return {} + } catch (e) { + return { error: (e as Error).message } + } +} + let refreshing: Promise | null = null async function refresh(): Promise { @@ -232,6 +289,7 @@ export async function getAccessToken(force = false): Promise { * Supabase renvoie vers l'app avec les jetons après le « # ». On ouvre la session puis on nettoie l'adresse. */ export async function consumeAuthRedirect(): Promise<{ type?: string; error?: string }> { + if (hasOAuthRedirect()) return consumeOAuthRedirect() const hash = location.hash.startsWith('#') ? location.hash.slice(1) : '' if (!/(^|&)(access_token|error)=/.test(hash)) return {} const params = new URLSearchParams(hash) diff --git a/supabase/migrations/20261002120000_social.sql b/supabase/migrations/20261002120000_social.sql index f990ac2..e1e2015 100644 --- a/supabase/migrations/20261002120000_social.sql +++ b/supabase/migrations/20261002120000_social.sql @@ -53,8 +53,15 @@ set search_path = '' as $$ declare u text := public.azuu_random_username(); + -- Connexion Google : on reprend le nom du compte comme nom affiché (le pseudo reste à choisir) + n text := left(trim(regexp_replace(coalesce(new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'name', ''), '[[:cntrl:]]', '', 'g')), 40); begin - insert into public.profiles (id, username, display_name) values (new.id, u, u) on conflict (id) do nothing; + begin + insert into public.profiles (id, username, display_name) values (new.id, u, coalesce(nullif(n, ''), u)) on conflict (id) do nothing; + exception when others then + -- Nom refusé : on garde le pseudo (l'inscription ne doit jamais échouer pour ça) + insert into public.profiles (id, username, display_name) values (new.id, u, u) on conflict (id) do nothing; + end; return new; end; $$;