oidc integration

Reviewed-on: #11
This commit was merged in pull request #11.
This commit is contained in:
2026-01-06 20:11:22 +00:00
parent ede9567e09
commit bf9c688e6b
39 changed files with 2853 additions and 516 deletions

View File

@@ -92,5 +92,8 @@
"Update": "Aktualisieren",
"Welcome back": "Willkommen zurück",
"work, todo, ideas": "Arbeit, Aufgaben, Ideen",
"Your notes will appear here. Click + to create one.": "Deine Notizen werden hier erscheinen. Klicke +, um eine zu erstellen."
"Your notes will appear here. Click + to create one.": "Deine Notizen werden hier erscheinen. Klicke +, um eine zu erstellen.",
"Sign in with SSO": "Mit SSO anmelden",
"Or continue with": "Oder fortfahren mit",
"Completing sign in...": "Anmeldung wird abgeschlossen..."
}

View File

@@ -92,5 +92,8 @@
"Update": "Update",
"Welcome back": "Welcome back",
"work, todo, ideas": "work, todo, ideas",
"Your notes will appear here. Click + to create one.": "Your notes will appear here. Click + to create one."
"Your notes will appear here. Click + to create one.": "Your notes will appear here. Click + to create one.",
"Sign in with SSO": "Sign in with SSO",
"Or continue with": "Or continue with",
"Completing sign in...": "Completing sign in..."
}

View File

@@ -96,5 +96,8 @@
"Update": "Actualizar",
"Welcome back": "Bienvenido de nuevo",
"work, todo, ideas": "trabajo, tareas, ideas",
"Your notes will appear here. Click + to create one.": "Tus notas aparecerán aquí. Haz clic en + para crear una."
"Your notes will appear here. Click + to create one.": "Tus notas aparecerán aquí. Haz clic en + para crear una.",
"Sign in with SSO": "Iniciar sesión con SSO",
"Or continue with": "O continuar con",
"Completing sign in...": "Completando inicio de sesión..."
}

View File

@@ -96,5 +96,8 @@
"Update": "Mettre à jour",
"Welcome back": "Bon retour",
"work, todo, ideas": "travail, tâches, idées",
"Your notes will appear here. Click + to create one.": "Tes notes apparaîtront ici. Clique sur + pour en créer une."
"Your notes will appear here. Click + to create one.": "Tes notes apparaîtront ici. Clique sur + pour en créer une.",
"Sign in with SSO": "Se connecter avec SSO",
"Or continue with": "Ou continuer avec",
"Completing sign in...": "Connexion en cours..."
}

View File

@@ -100,5 +100,8 @@
"Update": "Aktualizuj",
"Welcome back": "Witaj ponownie",
"work, todo, ideas": "praca, zadania, pomysły",
"Your notes will appear here. Click + to create one.": "Twoje notatki pojawią się tutaj. Kliknij +, aby utworzyć notatkę."
"Your notes will appear here. Click + to create one.": "Twoje notatki pojawią się tutaj. Kliknij +, aby utworzyć notatkę.",
"Sign in with SSO": "Zaloguj się przez SSO",
"Or continue with": "Lub kontynuuj przez",
"Completing sign in...": "Kończenie logowania..."
}

View File

@@ -5,6 +5,7 @@ import LoginPage from "@/pages/login";
import RegisterPage from "@/pages/register";
import DashboardPage from "@/pages/dashboard";
import PrivacyPolicyPage from "@/pages/privacy-policy";
import OidcCallbackPage from "@/pages/oidc-callback";
import Layout from "@/components/layout";
import { useSync } from "@/lib/sync";
import { useMobileStatusBar } from "@/hooks/use-mobile-status-bar";
@@ -17,6 +18,7 @@ function App() {
<Routes>
{/* Public Routes (accessible to everyone) */}
<Route path="/privacy-policy" element={<PrivacyPolicyPage />} />
<Route path="/auth/callback" element={<OidcCallbackPage />} />
{/* Public Routes (only accessible if NOT logged in) */}
<Route element={<PublicRoute />}>
@@ -40,3 +42,4 @@ function App() {
}
export default App;

View File

@@ -1,5 +1,5 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { api, setAuthToken, clearAuthToken, getBaseUrl } from "@/lib/api";
import { useNavigate } from "react-router-dom";
export interface User {
@@ -8,6 +8,20 @@ export interface User {
created_at: string;
}
// Token response from JWT/OIDC login
export interface TokenResponse {
access_token: string;
token_type: string;
expires_in: number;
}
// Login can return either User (session mode) or Token (JWT mode)
export type LoginResult = User | TokenResponse;
function isTokenResponse(result: LoginResult): result is TokenResponse {
return 'access_token' in result;
}
// Fetch current user
async function fetchUser(): Promise<User | null> {
try {
@@ -35,8 +49,13 @@ export function useLogin() {
const navigate = useNavigate();
return useMutation({
mutationFn: (credentials: any) => api.post("/auth/login", credentials),
onSuccess: () => {
mutationFn: (credentials: { email: string; password: string }): Promise<LoginResult> =>
api.post("/auth/login", credentials),
onSuccess: (result: LoginResult) => {
// If we got a token response, store the token
if (isTokenResponse(result)) {
setAuthToken(result.access_token);
}
queryClient.invalidateQueries({ queryKey: ["user"] });
navigate("/");
},
@@ -48,8 +67,13 @@ export function useRegister() {
const navigate = useNavigate();
return useMutation({
mutationFn: (credentials: any) => api.post("/auth/register", credentials),
onSuccess: () => {
mutationFn: (credentials: { email: string; password: string }): Promise<LoginResult> =>
api.post("/auth/register", credentials),
onSuccess: (result: LoginResult) => {
// If we got a token response, store the token
if (isTokenResponse(result)) {
setAuthToken(result.access_token);
}
queryClient.invalidateQueries({ queryKey: ["user"] });
navigate("/");
},
@@ -63,8 +87,25 @@ export function useLogout() {
return useMutation({
mutationFn: () => api.post("/auth/logout", {}),
onSuccess: () => {
// Clear both session data and JWT token
clearAuthToken();
queryClient.setQueryData(["user"], null);
navigate("/login");
},
onError: () => {
// Even on error, clear local state
clearAuthToken();
queryClient.setQueryData(["user"], null);
navigate("/login");
},
});
}
// Hook to initiate OIDC login flow
export function useOidcLogin() {
return () => {
// Redirect to OIDC login endpoint
window.location.href = `${getBaseUrl()}/api/v1/auth/login/oidc`;
};
}

View File

@@ -2,8 +2,13 @@
import { useQuery } from "@tanstack/react-query";
import { api } from "@/lib/api";
export type AuthMode = 'session' | 'jwt' | 'both';
export interface ConfigResponse {
allow_registration: boolean;
auth_mode: AuthMode;
oidc_enabled: boolean;
password_login_enabled: boolean;
}
export function useConfig() {
@@ -13,3 +18,4 @@ export function useConfig() {
staleTime: Infinity, // Config rarely changes
});
}

View File

@@ -6,6 +6,21 @@ declare global {
}
}
const TOKEN_STORAGE_KEY = 'k_notes_auth_token';
// JWT Token management
export function setAuthToken(token: string): void {
localStorage.setItem(TOKEN_STORAGE_KEY, token);
}
export function getAuthToken(): string | null {
return localStorage.getItem(TOKEN_STORAGE_KEY);
}
export function clearAuthToken(): void {
localStorage.removeItem(TOKEN_STORAGE_KEY);
}
const getApiUrl = () => {
// 1. Runtime config (Docker)
if (window.env?.API_URL) {
@@ -40,17 +55,22 @@ export class ApiError extends Error {
async function fetchWithAuth(endpoint: string, options: RequestInit = {}) {
const url = `${getApiUrl()}${endpoint}`;
const token = getAuthToken();
const headers = {
const headers: Record<string, string> = {
"Content-Type": "application/json",
...options.headers,
...(options.headers as Record<string, string> || {}),
};
// Add Authorization header if we have a JWT token
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
const config: RequestInit = {
...options,
headers,
credentials: "include", // Important for cookies!
// signal: controller.signal, // Removing signal, using race instead
credentials: "include", // Still include for session-based auth
};
try {
@@ -60,8 +80,6 @@ async function fetchWithAuth(endpoint: string, options: RequestInit = {}) {
);
const response = (await Promise.race([fetchPromise, timeoutPromise])) as Response;
// clearTimeout(timeoutId); // Not needed with race logic here (though leaking timer? No, race settles.)
if (!response.ok) {
// Try to parse error message
@@ -109,11 +127,18 @@ export const api = {
}),
delete: (endpoint: string) => fetchWithAuth(endpoint, { method: "DELETE" }),
exportData: async () => {
const token = getAuthToken();
const headers: Record<string, string> = {};
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
const response = await fetch(`${getApiUrl()}/export`, {
credentials: "include",
headers,
});
if (!response.ok) throw new ApiError(response.status, "Failed to export data");
return response.blob();
},
importData: (data: any) => api.post("/import", data),
};

View File

@@ -1,11 +1,11 @@
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Settings } from "lucide-react";
import { Settings, ExternalLink } from "lucide-react";
import { SettingsDialog } from "@/components/settings-dialog";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Link } from "react-router-dom";
import { useLogin } from "@/hooks/use-auth";
import { useLogin, useOidcLogin } from "@/hooks/use-auth";
import { useConfig } from "@/hooks/useConfig";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -26,6 +26,7 @@ export default function LoginPage() {
const { mutate: login, isPending } = useLogin();
const { data: config } = useConfig();
const { t } = useTranslation();
const startOidcLogin = useOidcLogin();
const form = useForm<LoginFormValues>({
resolver: zodResolver(loginSchema),
@@ -63,40 +64,71 @@ export default function LoginPage() {
{t("Enter your email to sign in to your account")}
</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>{t("Email")}</FormLabel>
<FormControl>
<Input placeholder="name@example.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>{t("Password")}</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={isPending}>
{isPending ? t("Signing in...") : t("Sign in")}
<CardContent className="space-y-4">
{/* OIDC/SSO Login Button */}
{config?.oidc_enabled && (
<>
<Button
type="button"
variant="outline"
className="w-full"
onClick={startOidcLogin}
>
<ExternalLink className="mr-2 h-4 w-4" />
{t("Sign in with SSO")}
</Button>
</form>
</Form>
{/* Divider only if both OIDC and password login are enabled */}
{config?.password_login_enabled && (
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">
{t("Or continue with")}
</span>
</div>
</div>
)}
</>
)}
{/* Email/Password Form - only show if password login is enabled */}
{config?.password_login_enabled !== false && (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>{t("Email")}</FormLabel>
<FormControl>
<Input placeholder="name@example.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>{t("Password")}</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={isPending}>
{isPending ? t("Signing in...") : t("Sign in")}
</Button>
</form>
</Form>
)}
</CardContent>
<CardFooter className="flex justify-center">
{config?.allow_registration !== false && (
@@ -113,3 +145,4 @@ export default function LoginPage() {
</div>
);
}

View File

@@ -0,0 +1,52 @@
import { useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { setAuthToken } from "@/lib/api";
import { useTranslation } from "react-i18next";
/**
* OIDC Callback Handler
*
* This page handles redirects from the OIDC provider after authentication.
*
* In Session mode: The backend sets a session cookie during the callback,
* so we just need to redirect to the dashboard.
*
* In JWT mode: The backend redirects here with a token in the URL fragment
* or query params, which we need to extract and store.
*/
export default function OidcCallbackPage() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const queryClient = useQueryClient();
const { t } = useTranslation();
useEffect(() => {
// Check for token in URL hash (implicit flow) or query params
const hashParams = new URLSearchParams(window.location.hash.slice(1));
const accessToken =
hashParams.get("access_token") || searchParams.get("access_token");
if (accessToken) {
// JWT mode: store the token
setAuthToken(accessToken);
}
// Invalidate user query to refetch with new auth state
queryClient.invalidateQueries({ queryKey: ["user"] });
// Redirect to dashboard
navigate("/", { replace: true });
}, [navigate, searchParams, queryClient]);
return (
<div className="flex min-h-screen items-center justify-center bg-gray-50 dark:bg-gray-950">
<div className="text-center">
<div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto mb-4" />
<p className="text-gray-500 dark:text-gray-400">
{t("Completing sign in...")}
</p>
</div>
</div>
);
}

View File

@@ -36,10 +36,14 @@ export default function RegisterPage() {
if (!isConfigLoading && config?.allow_registration === false) {
toast.error(t("Registration is currently disabled"));
navigate("/login");
} else if (!isConfigLoading && config?.password_login_enabled === false) {
// Registration requires password login to be enabled
toast.error(t("Registration is not available"));
navigate("/login");
}
}, [config, isConfigLoading, navigate, t]);
if (isConfigLoading || config?.allow_registration === false) {
if (isConfigLoading || config?.allow_registration === false || config?.password_login_enabled === false) {
return null; // Or a loading spinner
}