Compare commits
2
Commits
90a0412066
...
157be0c049
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
157be0c049 | ||
|
|
4dc3f27ac4 |
@@ -1,48 +1,74 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { signInWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from "firebase/auth";
|
import { signInWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from "firebase/auth";
|
||||||
import { auth } from "@/lib/firebase";
|
import { auth } from "@/lib/firebase";
|
||||||
import { c2api } from "@/lib/c2api";
|
import { c2api } from "@/lib/c2api";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useAuth } from "@/components/AuthProvider";
|
||||||
|
import { describeAuthError } from "@/lib/authErrors";
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(false);
|
const [misconfigured, setMisconfigured] = useState(false);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { user, loading: authLoading, orgId } = useAuth();
|
||||||
|
|
||||||
|
// Do NOT navigate straight from the sign-in handlers below: signInWith*
|
||||||
|
// resolves before AuthProvider's onAuthStateChanged listener has fetched
|
||||||
|
// claims and set/cleared the drb_session cookie. Pushing to /dashboard
|
||||||
|
// immediately races that — for a no-org account the cookie never gets
|
||||||
|
// set, so middleware.ts bounces the very next request straight back to
|
||||||
|
// /login, which is the ping-pong this screen used to cause. Instead,
|
||||||
|
// react to AuthProvider's own settled state: this also covers a user who
|
||||||
|
// arrives here already signed in (e.g. redirected from a protected route
|
||||||
|
// by middleware while their Firebase session was still valid) — same
|
||||||
|
// destination logic, no separate code path, no bounce.
|
||||||
|
useEffect(() => {
|
||||||
|
if (authLoading) return;
|
||||||
|
if (!user) return;
|
||||||
|
router.replace(orgId ? "/dashboard" : "/onboarding");
|
||||||
|
}, [authLoading, user, orgId, router]);
|
||||||
|
|
||||||
async function handleSubmit(e: React.FormEvent) {
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setLoading(true);
|
setSubmitting(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
setMisconfigured(false);
|
||||||
try {
|
try {
|
||||||
await signInWithEmailAndPassword(auth, email, password);
|
await signInWithEmailAndPassword(auth, email, password);
|
||||||
c2api.recordSession().catch(() => {});
|
c2api.recordSession().catch(() => {});
|
||||||
router.push("/dashboard");
|
// Redirect happens via the effect above once claims are settled.
|
||||||
} catch {
|
} catch (err) {
|
||||||
setError("Invalid email or password.");
|
const info = describeAuthError(err, "Invalid email or password.");
|
||||||
} finally {
|
setError(info.message);
|
||||||
setLoading(false);
|
setMisconfigured(info.misconfiguration);
|
||||||
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleGoogle() {
|
async function handleGoogle() {
|
||||||
setLoading(true);
|
setSubmitting(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
setMisconfigured(false);
|
||||||
try {
|
try {
|
||||||
await signInWithPopup(auth, new GoogleAuthProvider());
|
await signInWithPopup(auth, new GoogleAuthProvider());
|
||||||
c2api.recordSession().catch(() => {});
|
c2api.recordSession().catch(() => {});
|
||||||
router.push("/dashboard");
|
// Redirect happens via the effect above once claims are settled.
|
||||||
} catch {
|
} catch (err) {
|
||||||
setError("Google sign-in failed. Try again.");
|
const info = describeAuthError(err, "Google sign-in failed. Try again.");
|
||||||
} finally {
|
setError(info.message);
|
||||||
setLoading(false);
|
setMisconfigured(info.misconfiguration);
|
||||||
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const loading = submitting || !!user;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-sm mx-auto pt-16">
|
<div className="max-w-sm mx-auto pt-16">
|
||||||
<Link href="/" className="flex items-center justify-center gap-2 mb-6 font-mono font-bold text-white">
|
<Link href="/" className="flex items-center justify-center gap-2 mb-6 font-mono font-bold text-white">
|
||||||
@@ -75,7 +101,9 @@ export default function LoginPage() {
|
|||||||
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{error && <p className="text-red-400 text-xs">{error}</p>}
|
{error && (
|
||||||
|
<p className={`text-xs ${misconfigured ? "text-amber-400" : "text-red-400"}`}>{error}</p>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import Link from "next/link";
|
|||||||
import { createUserWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from "firebase/auth";
|
import { createUserWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from "firebase/auth";
|
||||||
import { auth } from "@/lib/firebase";
|
import { auth } from "@/lib/firebase";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
import { describeAuthError } from "@/lib/authErrors";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Self-serve account creation (SAAS_PLAN.md B4). Only creates the Firebase
|
* Self-serve account creation (SAAS_PLAN.md B4). Only creates the Firebase
|
||||||
@@ -17,6 +18,7 @@ export default function SignupPage() {
|
|||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [misconfigured, setMisconfigured] = useState(false);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
@@ -24,18 +26,14 @@ export default function SignupPage() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
setMisconfigured(false);
|
||||||
try {
|
try {
|
||||||
await createUserWithEmailAndPassword(auth, email, password);
|
await createUserWithEmailAndPassword(auth, email, password);
|
||||||
router.push("/onboarding");
|
router.push("/onboarding");
|
||||||
} catch (err: unknown) {
|
} catch (err) {
|
||||||
const code = (err as { code?: string })?.code;
|
const info = describeAuthError(err, "Could not create your account. Check your details and try again.");
|
||||||
if (code === "auth/email-already-in-use") {
|
setError(info.message);
|
||||||
setError("An account with this email already exists. Try signing in instead.");
|
setMisconfigured(info.misconfiguration);
|
||||||
} else if (code === "auth/weak-password") {
|
|
||||||
setError("Password is too weak — use at least 6 characters.");
|
|
||||||
} else {
|
|
||||||
setError("Could not create your account. Check your details and try again.");
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -44,11 +42,14 @@ export default function SignupPage() {
|
|||||||
async function handleGoogle() {
|
async function handleGoogle() {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
setMisconfigured(false);
|
||||||
try {
|
try {
|
||||||
await signInWithPopup(auth, new GoogleAuthProvider());
|
await signInWithPopup(auth, new GoogleAuthProvider());
|
||||||
router.push("/onboarding");
|
router.push("/onboarding");
|
||||||
} catch {
|
} catch (err) {
|
||||||
setError("Google sign-up failed. Try again.");
|
const info = describeAuthError(err, "Google sign-up failed. Try again.");
|
||||||
|
setError(info.message);
|
||||||
|
setMisconfigured(info.misconfiguration);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -87,7 +88,9 @@ export default function SignupPage() {
|
|||||||
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{error && <p className="text-red-400 text-xs">{error}</p>}
|
{error && (
|
||||||
|
<p className={`text-xs ${misconfigured ? "text-amber-400" : "text-red-400"}`}>{error}</p>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
|
|||||||
@@ -61,16 +61,37 @@ function MoonIcon() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function Nav() {
|
export function Nav() {
|
||||||
const { user, isAdmin, isOperator, isOrgOwner, orgId } = useAuth();
|
const { user, isAdmin, isOperator, isOrgOwner, orgId, signOut, refreshClaims } = useAuth();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { nodes: pending } = useUnconfiguredNodes();
|
const { nodes: pending } = useUnconfiguredNodes();
|
||||||
const unackedAlerts = useUnacknowledgedAlerts();
|
const unackedAlerts = useUnacknowledgedAlerts();
|
||||||
const { theme, toggle } = useTheme();
|
const { theme, toggle } = useTheme();
|
||||||
const [mobileOpen, setMobileOpen] = useState(false);
|
const [mobileOpen, setMobileOpen] = useState(false);
|
||||||
|
const [profileMenuOpen, setProfileMenuOpen] = useState(false);
|
||||||
|
const [refreshing, setRefreshing] = useState(false);
|
||||||
|
|
||||||
if (!user) return null;
|
if (!user) return null;
|
||||||
|
|
||||||
|
async function handleSignOut() {
|
||||||
|
setProfileMenuOpen(false);
|
||||||
|
await signOut();
|
||||||
|
router.push("/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-fetches the ID token so a claims change made server-side (e.g. an
|
||||||
|
// admin granting a role, or org_id being provisioned) takes effect without
|
||||||
|
// a full sign-out/sign-in. See AuthProvider.refreshClaims.
|
||||||
|
async function handleRefreshClaims() {
|
||||||
|
setRefreshing(true);
|
||||||
|
try {
|
||||||
|
await refreshClaims();
|
||||||
|
} finally {
|
||||||
|
setRefreshing(false);
|
||||||
|
setProfileMenuOpen(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const allLinks = [
|
const allLinks = [
|
||||||
...viewerLinks,
|
...viewerLinks,
|
||||||
...(orgId === FOUNDING_ORG_ID || isAdmin ? [tripsLink] : []),
|
...(orgId === FOUNDING_ORG_ID || isAdmin ? [tripsLink] : []),
|
||||||
@@ -120,18 +141,51 @@ export function Nav() {
|
|||||||
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
|
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Profile avatar (desktop) */}
|
{/* Profile avatar + dropdown (desktop) */}
|
||||||
<button
|
<div className="hidden md:block relative">
|
||||||
onClick={() => router.push("/profile")}
|
<button
|
||||||
className={`hidden md:flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold transition-colors ${
|
onClick={() => setProfileMenuOpen((v) => !v)}
|
||||||
pathname.startsWith("/profile")
|
className={`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold transition-colors ${
|
||||||
? "bg-indigo-600 text-white"
|
pathname.startsWith("/profile") || profileMenuOpen
|
||||||
: "bg-gray-800 text-gray-300 hover:bg-gray-700"
|
? "bg-indigo-600 text-white"
|
||||||
}`}
|
: "bg-gray-800 text-gray-300 hover:bg-gray-700"
|
||||||
title="Profile"
|
}`}
|
||||||
>
|
title="Account"
|
||||||
{(user?.displayName || user?.email || "?")[0].toUpperCase()}
|
>
|
||||||
</button>
|
{(user?.displayName || user?.email || "?")[0].toUpperCase()}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{profileMenuOpen && (
|
||||||
|
<>
|
||||||
|
{/* Click-away backdrop */}
|
||||||
|
<div className="fixed inset-0 z-40" onClick={() => setProfileMenuOpen(false)} />
|
||||||
|
<div className="absolute right-0 mt-2 w-48 bg-gray-900 border border-gray-800 rounded-lg shadow-lg z-50 py-1 font-mono text-sm">
|
||||||
|
<Link
|
||||||
|
href="/profile"
|
||||||
|
onClick={() => setProfileMenuOpen(false)}
|
||||||
|
className="block px-3 py-2 text-gray-300 hover:bg-gray-800 hover:text-white transition-colors"
|
||||||
|
>
|
||||||
|
Profile
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
onClick={handleRefreshClaims}
|
||||||
|
disabled={refreshing}
|
||||||
|
className="w-full text-left px-3 py-2 text-gray-300 hover:bg-gray-800 hover:text-white transition-colors disabled:opacity-50"
|
||||||
|
title="Pick up a role or org change made server-side, without signing out"
|
||||||
|
>
|
||||||
|
{refreshing ? "Refreshing…" : "Refresh access"}
|
||||||
|
</button>
|
||||||
|
<div className="border-t border-gray-800 my-1" />
|
||||||
|
<button
|
||||||
|
onClick={handleSignOut}
|
||||||
|
className="w-full text-left px-3 py-2 text-red-500 hover:bg-gray-800 hover:text-red-400 transition-colors"
|
||||||
|
>
|
||||||
|
Sign out
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Hamburger (mobile) */}
|
{/* Hamburger (mobile) */}
|
||||||
<button
|
<button
|
||||||
@@ -177,7 +231,7 @@ export function Nav() {
|
|||||||
)}
|
)}
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
<div className="border-t border-gray-800 pt-3 mt-1">
|
<div className="border-t border-gray-800 pt-3 mt-1 flex flex-col gap-1">
|
||||||
<Link
|
<Link
|
||||||
href="/profile"
|
href="/profile"
|
||||||
onClick={() => setMobileOpen(false)}
|
onClick={() => setMobileOpen(false)}
|
||||||
@@ -187,6 +241,19 @@ export function Nav() {
|
|||||||
>
|
>
|
||||||
Profile
|
Profile
|
||||||
</Link>
|
</Link>
|
||||||
|
<button
|
||||||
|
onClick={() => { setMobileOpen(false); handleRefreshClaims(); }}
|
||||||
|
disabled={refreshing}
|
||||||
|
className="py-2 text-sm font-mono text-gray-500 text-left disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{refreshing ? "Refreshing…" : "Refresh access"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => { setMobileOpen(false); handleSignOut(); }}
|
||||||
|
className="py-2 text-sm font-mono text-red-500 text-left"
|
||||||
|
>
|
||||||
|
Sign out
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* Maps Firebase Auth error codes to user-facing messages instead of
|
||||||
|
* discarding them. Two categories:
|
||||||
|
*
|
||||||
|
* - misconfiguration: something is wrong with *our* deployment (a domain
|
||||||
|
* not on the authorized list, a sign-in provider not enabled in the
|
||||||
|
* Firebase console). Retrying can never fix these — the message says so
|
||||||
|
* instead of "try again", which would send a user into a retry loop
|
||||||
|
* against a config problem only we can fix.
|
||||||
|
* - everything else: the user's own situation (blocked/closed popup, bad
|
||||||
|
* password, a network blip) — retrying might well work.
|
||||||
|
*
|
||||||
|
* Always logs the raw error so it isn't silently discarded — the point of
|
||||||
|
* this file is to stop swallowing that information, not just relabel it.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface AuthErrorInfo {
|
||||||
|
message: string;
|
||||||
|
misconfiguration: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MISCONFIGURATION_MESSAGES: Record<string, string> = {
|
||||||
|
"auth/unauthorized-domain":
|
||||||
|
"This domain isn't authorized for sign-in yet. That's a configuration issue on our end (Firebase Console → Authentication → Settings → Authorized domains) — retrying won't fix it. Please report this.",
|
||||||
|
"auth/operation-not-allowed":
|
||||||
|
"This sign-in method isn't enabled for this app yet. That's a configuration issue on our end (Firebase Console → Authentication → Sign-in method) — retrying won't fix it. Please report this.",
|
||||||
|
};
|
||||||
|
|
||||||
|
const USER_MESSAGES: Record<string, string> = {
|
||||||
|
"auth/popup-blocked": "Your browser blocked the sign-in popup. Allow popups for this site and try again.",
|
||||||
|
"auth/popup-closed-by-user": "Sign-in window was closed before finishing. Try again.",
|
||||||
|
"auth/cancelled-popup-request": "Sign-in was interrupted by another sign-in attempt. Try again.",
|
||||||
|
"auth/network-request-failed": "Network error — check your connection and try again.",
|
||||||
|
"auth/invalid-credential": "Invalid email or password.",
|
||||||
|
"auth/wrong-password": "Invalid email or password.",
|
||||||
|
"auth/user-not-found": "Invalid email or password.",
|
||||||
|
"auth/too-many-requests": "Too many attempts. Wait a few minutes and try again.",
|
||||||
|
"auth/email-already-in-use": "An account with this email already exists. Try signing in instead.",
|
||||||
|
"auth/weak-password": "Password is too weak — use at least 6 characters.",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function describeAuthError(err: unknown, fallback: string): AuthErrorInfo {
|
||||||
|
const code = (err as { code?: string } | null | undefined)?.code;
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error("[auth]", code ?? "(no error code)", err);
|
||||||
|
|
||||||
|
if (code && MISCONFIGURATION_MESSAGES[code]) {
|
||||||
|
return { message: MISCONFIGURATION_MESSAGES[code], misconfiguration: true };
|
||||||
|
}
|
||||||
|
if (code && USER_MESSAGES[code]) {
|
||||||
|
return { message: USER_MESSAGES[code], misconfiguration: false };
|
||||||
|
}
|
||||||
|
return { message: fallback, misconfiguration: false };
|
||||||
|
}
|
||||||
@@ -35,7 +35,31 @@ mqtt.{{ domain }} {
|
|||||||
# To move it to app.{{ domain }}, create the A record first, then change this
|
# To move it to app.{{ domain }}, create the A record first, then change this
|
||||||
# line — the reverse_proxy target stays the same either way.
|
# line — the reverse_proxy target stays the same either way.
|
||||||
{{ domain }} {
|
{{ domain }} {
|
||||||
reverse_proxy localhost:3000 {
|
route {
|
||||||
header_up X-Forwarded-For {remote_host}
|
# Firebase Auth's sign-in handler, served from our own origin.
|
||||||
|
#
|
||||||
|
# signInWithPopup opens {{ firebase_auth_handler_host | default('discord-radio-bot-461301.firebaseapp.com') }}/__/auth/handler and
|
||||||
|
# then reads back state the opener wrote. Chrome now partitions third-party
|
||||||
|
# storage, so when that handler is on a different site from the app the
|
||||||
|
# popup cannot see that state: it opens, fails, and closes instantly with no
|
||||||
|
# console or network trace. The handler page says so itself if you visit it
|
||||||
|
# directly ("storage-partitioned browser environment").
|
||||||
|
#
|
||||||
|
# Proxying the handler through this domain makes it same-site, which is
|
||||||
|
# Google's documented fix. Host must be rewritten upstream or Firebase
|
||||||
|
# Hosting will not recognise the request.
|
||||||
|
#
|
||||||
|
# NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN must be set to {{ domain }} in the CI
|
||||||
|
# build secrets to match, and {{ domain }} must be listed in the Firebase
|
||||||
|
# console's authorised domains. Changing only one of the three does nothing.
|
||||||
|
handle /__/auth/* {
|
||||||
|
reverse_proxy https://{{ firebase_auth_handler_host | default('discord-radio-bot-461301.firebaseapp.com') }} {
|
||||||
|
header_up Host {{ firebase_auth_handler_host | default('discord-radio-bot-461301.firebaseapp.com') }}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reverse_proxy localhost:3000 {
|
||||||
|
header_up X-Forwarded-For {remote_host}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user