oidc #11
@@ -92,5 +92,8 @@
|
|||||||
"Update": "Aktualisieren",
|
"Update": "Aktualisieren",
|
||||||
"Welcome back": "Willkommen zurück",
|
"Welcome back": "Willkommen zurück",
|
||||||
"work, todo, ideas": "Arbeit, Aufgaben, Ideen",
|
"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..."
|
||||||
}
|
}
|
||||||
@@ -92,5 +92,8 @@
|
|||||||
"Update": "Update",
|
"Update": "Update",
|
||||||
"Welcome back": "Welcome back",
|
"Welcome back": "Welcome back",
|
||||||
"work, todo, ideas": "work, todo, ideas",
|
"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..."
|
||||||
}
|
}
|
||||||
@@ -96,5 +96,8 @@
|
|||||||
"Update": "Actualizar",
|
"Update": "Actualizar",
|
||||||
"Welcome back": "Bienvenido de nuevo",
|
"Welcome back": "Bienvenido de nuevo",
|
||||||
"work, todo, ideas": "trabajo, tareas, ideas",
|
"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..."
|
||||||
}
|
}
|
||||||
@@ -96,5 +96,8 @@
|
|||||||
"Update": "Mettre à jour",
|
"Update": "Mettre à jour",
|
||||||
"Welcome back": "Bon retour",
|
"Welcome back": "Bon retour",
|
||||||
"work, todo, ideas": "travail, tâches, idées",
|
"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..."
|
||||||
}
|
}
|
||||||
@@ -100,5 +100,8 @@
|
|||||||
"Update": "Aktualizuj",
|
"Update": "Aktualizuj",
|
||||||
"Welcome back": "Witaj ponownie",
|
"Welcome back": "Witaj ponownie",
|
||||||
"work, todo, ideas": "praca, zadania, pomysły",
|
"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..."
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ import LoginPage from "@/pages/login";
|
|||||||
import RegisterPage from "@/pages/register";
|
import RegisterPage from "@/pages/register";
|
||||||
import DashboardPage from "@/pages/dashboard";
|
import DashboardPage from "@/pages/dashboard";
|
||||||
import PrivacyPolicyPage from "@/pages/privacy-policy";
|
import PrivacyPolicyPage from "@/pages/privacy-policy";
|
||||||
|
import OidcCallbackPage from "@/pages/oidc-callback";
|
||||||
import Layout from "@/components/layout";
|
import Layout from "@/components/layout";
|
||||||
import { useSync } from "@/lib/sync";
|
import { useSync } from "@/lib/sync";
|
||||||
import { useMobileStatusBar } from "@/hooks/use-mobile-status-bar";
|
import { useMobileStatusBar } from "@/hooks/use-mobile-status-bar";
|
||||||
@@ -17,6 +18,7 @@ function App() {
|
|||||||
<Routes>
|
<Routes>
|
||||||
{/* Public Routes (accessible to everyone) */}
|
{/* Public Routes (accessible to everyone) */}
|
||||||
<Route path="/privacy-policy" element={<PrivacyPolicyPage />} />
|
<Route path="/privacy-policy" element={<PrivacyPolicyPage />} />
|
||||||
|
<Route path="/auth/callback" element={<OidcCallbackPage />} />
|
||||||
|
|
||||||
{/* Public Routes (only accessible if NOT logged in) */}
|
{/* Public Routes (only accessible if NOT logged in) */}
|
||||||
<Route element={<PublicRoute />}>
|
<Route element={<PublicRoute />}>
|
||||||
@@ -40,3 +42,4 @@ function App() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default App;
|
export default App;
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
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";
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
export interface User {
|
export interface User {
|
||||||
@@ -8,6 +8,20 @@ export interface User {
|
|||||||
created_at: string;
|
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
|
// Fetch current user
|
||||||
async function fetchUser(): Promise<User | null> {
|
async function fetchUser(): Promise<User | null> {
|
||||||
try {
|
try {
|
||||||
@@ -35,8 +49,13 @@ export function useLogin() {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (credentials: any) => api.post("/auth/login", credentials),
|
mutationFn: (credentials: { email: string; password: string }): Promise<LoginResult> =>
|
||||||
onSuccess: () => {
|
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"] });
|
queryClient.invalidateQueries({ queryKey: ["user"] });
|
||||||
navigate("/");
|
navigate("/");
|
||||||
},
|
},
|
||||||
@@ -48,8 +67,13 @@ export function useRegister() {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (credentials: any) => api.post("/auth/register", credentials),
|
mutationFn: (credentials: { email: string; password: string }): Promise<LoginResult> =>
|
||||||
onSuccess: () => {
|
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"] });
|
queryClient.invalidateQueries({ queryKey: ["user"] });
|
||||||
navigate("/");
|
navigate("/");
|
||||||
},
|
},
|
||||||
@@ -63,8 +87,25 @@ export function useLogout() {
|
|||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: () => api.post("/auth/logout", {}),
|
mutationFn: () => api.post("/auth/logout", {}),
|
||||||
onSuccess: () => {
|
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);
|
queryClient.setQueryData(["user"], null);
|
||||||
navigate("/login");
|
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`;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,13 @@
|
|||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { api } from "@/lib/api";
|
import { api } from "@/lib/api";
|
||||||
|
|
||||||
|
export type AuthMode = 'session' | 'jwt' | 'both';
|
||||||
|
|
||||||
export interface ConfigResponse {
|
export interface ConfigResponse {
|
||||||
allow_registration: boolean;
|
allow_registration: boolean;
|
||||||
|
auth_mode: AuthMode;
|
||||||
|
oidc_enabled: boolean;
|
||||||
|
password_login_enabled: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useConfig() {
|
export function useConfig() {
|
||||||
@@ -13,3 +18,4 @@ export function useConfig() {
|
|||||||
staleTime: Infinity, // Config rarely changes
|
staleTime: Infinity, // Config rarely changes
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 = () => {
|
const getApiUrl = () => {
|
||||||
// 1. Runtime config (Docker)
|
// 1. Runtime config (Docker)
|
||||||
if (window.env?.API_URL) {
|
if (window.env?.API_URL) {
|
||||||
@@ -40,17 +55,22 @@ export class ApiError extends Error {
|
|||||||
|
|
||||||
async function fetchWithAuth(endpoint: string, options: RequestInit = {}) {
|
async function fetchWithAuth(endpoint: string, options: RequestInit = {}) {
|
||||||
const url = `${getApiUrl()}${endpoint}`;
|
const url = `${getApiUrl()}${endpoint}`;
|
||||||
|
const token = getAuthToken();
|
||||||
|
|
||||||
const headers = {
|
const headers: Record<string, string> = {
|
||||||
"Content-Type": "application/json",
|
"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 = {
|
const config: RequestInit = {
|
||||||
...options,
|
...options,
|
||||||
headers,
|
headers,
|
||||||
credentials: "include", // Important for cookies!
|
credentials: "include", // Still include for session-based auth
|
||||||
// signal: controller.signal, // Removing signal, using race instead
|
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -60,8 +80,6 @@ async function fetchWithAuth(endpoint: string, options: RequestInit = {}) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const response = (await Promise.race([fetchPromise, timeoutPromise])) as Response;
|
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) {
|
if (!response.ok) {
|
||||||
// Try to parse error message
|
// Try to parse error message
|
||||||
@@ -109,11 +127,18 @@ export const api = {
|
|||||||
}),
|
}),
|
||||||
delete: (endpoint: string) => fetchWithAuth(endpoint, { method: "DELETE" }),
|
delete: (endpoint: string) => fetchWithAuth(endpoint, { method: "DELETE" }),
|
||||||
exportData: async () => {
|
exportData: async () => {
|
||||||
|
const token = getAuthToken();
|
||||||
|
const headers: Record<string, string> = {};
|
||||||
|
if (token) {
|
||||||
|
headers["Authorization"] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
const response = await fetch(`${getApiUrl()}/export`, {
|
const response = await fetch(`${getApiUrl()}/export`, {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
|
headers,
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new ApiError(response.status, "Failed to export data");
|
if (!response.ok) throw new ApiError(response.status, "Failed to export data");
|
||||||
return response.blob();
|
return response.blob();
|
||||||
},
|
},
|
||||||
importData: (data: any) => api.post("/import", data),
|
importData: (data: any) => api.post("/import", data),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { Settings } from "lucide-react";
|
import { Settings, ExternalLink } from "lucide-react";
|
||||||
import { SettingsDialog } from "@/components/settings-dialog";
|
import { SettingsDialog } from "@/components/settings-dialog";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { Link } from "react-router-dom";
|
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 { useConfig } from "@/hooks/useConfig";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -26,6 +26,7 @@ export default function LoginPage() {
|
|||||||
const { mutate: login, isPending } = useLogin();
|
const { mutate: login, isPending } = useLogin();
|
||||||
const { data: config } = useConfig();
|
const { data: config } = useConfig();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const startOidcLogin = useOidcLogin();
|
||||||
|
|
||||||
const form = useForm<LoginFormValues>({
|
const form = useForm<LoginFormValues>({
|
||||||
resolver: zodResolver(loginSchema),
|
resolver: zodResolver(loginSchema),
|
||||||
@@ -63,40 +64,71 @@ export default function LoginPage() {
|
|||||||
{t("Enter your email to sign in to your account")}
|
{t("Enter your email to sign in to your account")}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent className="space-y-4">
|
||||||
<Form {...form}>
|
{/* OIDC/SSO Login Button */}
|
||||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
{config?.oidc_enabled && (
|
||||||
<FormField
|
<>
|
||||||
control={form.control}
|
<Button
|
||||||
name="email"
|
type="button"
|
||||||
render={({ field }) => (
|
variant="outline"
|
||||||
<FormItem>
|
className="w-full"
|
||||||
<FormLabel>{t("Email")}</FormLabel>
|
onClick={startOidcLogin}
|
||||||
<FormControl>
|
>
|
||||||
<Input placeholder="name@example.com" {...field} />
|
<ExternalLink className="mr-2 h-4 w-4" />
|
||||||
</FormControl>
|
{t("Sign in with SSO")}
|
||||||
<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>
|
</Button>
|
||||||
</form>
|
{/* Divider only if both OIDC and password login are enabled */}
|
||||||
</Form>
|
{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>
|
</CardContent>
|
||||||
<CardFooter className="flex justify-center">
|
<CardFooter className="flex justify-center">
|
||||||
{config?.allow_registration !== false && (
|
{config?.allow_registration !== false && (
|
||||||
@@ -113,3 +145,4 @@ export default function LoginPage() {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
52
k-notes-frontend/src/pages/oidc-callback.tsx
Normal file
52
k-notes-frontend/src/pages/oidc-callback.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -36,10 +36,14 @@ export default function RegisterPage() {
|
|||||||
if (!isConfigLoading && config?.allow_registration === false) {
|
if (!isConfigLoading && config?.allow_registration === false) {
|
||||||
toast.error(t("Registration is currently disabled"));
|
toast.error(t("Registration is currently disabled"));
|
||||||
navigate("/login");
|
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]);
|
}, [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
|
return null; // Or a loading spinner
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ edition = "2024"
|
|||||||
default-run = "notes-api"
|
default-run = "notes-api"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["sqlite", "smart-features", "auth-oidc", "auth-jwt"]
|
default = ["sqlite", "smart-features"]
|
||||||
sqlite = ["notes-infra/sqlite"]
|
sqlite = ["notes-infra/sqlite"]
|
||||||
postgres = ["notes-infra/postgres"]
|
postgres = ["notes-infra/postgres"]
|
||||||
smart-features = ["notes-infra/smart-features", "notes-infra/broker-nats"]
|
smart-features = ["notes-infra/smart-features", "notes-infra/broker-nats"]
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
#[cfg(feature = "smart-features")]
|
#[cfg(feature = "smart-features")]
|
||||||
use notes_infra::factory::{EmbeddingProvider, VectorProvider};
|
use notes_infra::factory::{EmbeddingProvider, VectorProvider};
|
||||||
use serde::Deserialize;
|
use serde::{Deserialize, Serialize};
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
/// Authentication mode - determines how the API authenticates requests
|
/// Authentication mode - determines how the API authenticates requests
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
pub enum AuthMode {
|
pub enum AuthMode {
|
||||||
/// Session-based authentication using cookies (default for backward compatibility)
|
/// Session-based authentication using cookies (default for backward compatibility)
|
||||||
@@ -66,6 +66,9 @@ pub struct Config {
|
|||||||
|
|
||||||
/// Whether the application is running in production mode
|
/// Whether the application is running in production mode
|
||||||
pub is_production: bool,
|
pub is_production: bool,
|
||||||
|
|
||||||
|
/// Frontend URL for OIDC redirect (defaults to first CORS origin)
|
||||||
|
pub frontend_url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Config {
|
impl Default for Config {
|
||||||
@@ -100,6 +103,7 @@ impl Default for Config {
|
|||||||
jwt_audience: None,
|
jwt_audience: None,
|
||||||
jwt_expiry_hours: 24,
|
jwt_expiry_hours: 24,
|
||||||
is_production: false,
|
is_production: false,
|
||||||
|
frontend_url: "http://localhost:5173".to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -219,6 +223,8 @@ impl Config {
|
|||||||
jwt_audience,
|
jwt_audience,
|
||||||
jwt_expiry_hours,
|
jwt_expiry_hours,
|
||||||
is_production,
|
is_production,
|
||||||
|
frontend_url: env::var("FRONTEND_URL")
|
||||||
|
.unwrap_or_else(|_| "http://localhost:5173".to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ use validator::Validate;
|
|||||||
|
|
||||||
use notes_domain::{Email, Note, Password, Tag};
|
use notes_domain::{Email, Note, Password, Tag};
|
||||||
|
|
||||||
|
use crate::config::AuthMode;
|
||||||
|
|
||||||
/// Request to create a new note
|
/// Request to create a new note
|
||||||
#[derive(Debug, Deserialize, Validate)]
|
#[derive(Debug, Deserialize, Validate)]
|
||||||
pub struct CreateNoteRequest {
|
pub struct CreateNoteRequest {
|
||||||
@@ -165,6 +167,9 @@ impl From<notes_domain::NoteVersion> for NoteVersionResponse {
|
|||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
pub struct ConfigResponse {
|
pub struct ConfigResponse {
|
||||||
pub allow_registration: bool,
|
pub allow_registration: bool,
|
||||||
|
pub auth_mode: AuthMode,
|
||||||
|
pub oidc_enabled: bool,
|
||||||
|
pub password_login_enabled: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Note Link response DTO
|
/// Note Link response DTO
|
||||||
|
|||||||
@@ -387,25 +387,19 @@ async fn oidc_callback(
|
|||||||
.await
|
.await
|
||||||
.map_err(|_| ApiError::Internal("Session error".into()))?;
|
.map_err(|_| ApiError::Internal("Session error".into()))?;
|
||||||
|
|
||||||
// In JWT mode, return token as JSON
|
// In JWT mode, redirect to frontend with token in URL fragment
|
||||||
#[cfg(feature = "auth-jwt")]
|
#[cfg(feature = "auth-jwt")]
|
||||||
if matches!(auth_mode, AuthMode::Jwt | AuthMode::Both) {
|
if matches!(auth_mode, AuthMode::Jwt | AuthMode::Both) {
|
||||||
let token = create_jwt_for_user(&user, &state)?;
|
let token = create_jwt_for_user(&user, &state)?;
|
||||||
return Ok(Json(TokenResponse {
|
let redirect_url = format!(
|
||||||
access_token: token,
|
"{}/auth/callback#access_token={}",
|
||||||
token_type: "Bearer".to_string(),
|
state.config.frontend_url, token
|
||||||
expires_in: state.config.jwt_expiry_hours * 3600,
|
);
|
||||||
})
|
return Ok(axum::response::Redirect::to(&redirect_url).into_response());
|
||||||
.into_response());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Session mode: return user info
|
// Session mode: redirect to frontend (session cookie already set)
|
||||||
Ok(Json(UserResponse {
|
Ok(axum::response::Redirect::to(&state.config.frontend_url).into_response())
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
created_at: user.created_at,
|
|
||||||
})
|
|
||||||
.into_response())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fallback OIDC callback when auth-axum-login is not enabled
|
/// Fallback OIDC callback when auth-axum-login is not enabled
|
||||||
@@ -470,15 +464,15 @@ async fn oidc_callback(
|
|||||||
.await
|
.await
|
||||||
.map_err(|_| ApiError::Internal("Session error".into()))?;
|
.map_err(|_| ApiError::Internal("Session error".into()))?;
|
||||||
|
|
||||||
// Return token as JSON
|
// Redirect to frontend with token in URL fragment
|
||||||
#[cfg(feature = "auth-jwt")]
|
#[cfg(feature = "auth-jwt")]
|
||||||
{
|
{
|
||||||
let token = create_jwt_for_user(&user, &state)?;
|
let token = create_jwt_for_user(&user, &state)?;
|
||||||
return Ok(Json(TokenResponse {
|
let redirect_url = format!(
|
||||||
access_token: token,
|
"{}/auth/callback#access_token={}",
|
||||||
token_type: "Bearer".to_string(),
|
state.config.frontend_url, token
|
||||||
expires_in: state.config.jwt_expiry_hours * 3600,
|
);
|
||||||
}));
|
return Ok(axum::response::Redirect::to(&redirect_url));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "auth-jwt"))]
|
#[cfg(not(feature = "auth-jwt"))]
|
||||||
|
|||||||
@@ -10,5 +10,11 @@ use crate::state::AppState;
|
|||||||
pub async fn get_config(State(state): State<AppState>) -> ApiResult<Json<ConfigResponse>> {
|
pub async fn get_config(State(state): State<AppState>) -> ApiResult<Json<ConfigResponse>> {
|
||||||
Ok(Json(ConfigResponse {
|
Ok(Json(ConfigResponse {
|
||||||
allow_registration: state.config.allow_registration,
|
allow_registration: state.config.allow_registration,
|
||||||
|
auth_mode: state.config.auth_mode,
|
||||||
|
#[cfg(feature = "auth-oidc")]
|
||||||
|
oidc_enabled: state.oidc_service.is_some(),
|
||||||
|
#[cfg(not(feature = "auth-oidc"))]
|
||||||
|
oidc_enabled: false,
|
||||||
|
password_login_enabled: cfg!(feature = "auth-axum-login"),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user