Skip to content

Modern Docker Management, Designed for Everyone

fix: auth session redirect

Kyle Mendell9da620a95340
diff --git a/backend/internal/api/auth_handler.go b/backend/internal/api/auth_handler.go
index d14492580..53a671b45 100644
--- a/backend/internal/api/auth_handler.go
+++ b/backend/internal/api/auth_handler.go
@@ -191,7 +191,7 @@ func (h *AuthHandler) Logout(c *gin.Context) {
}
func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
- user, exists := middleware.GetCurrentUser(c)
+ userID, exists := middleware.GetCurrentUserID(c)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
@@ -200,13 +200,22 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
return
}
+ user, err := h.userService.GetUser(c.Request.Context(), userID)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "error": "Failed to get user information",
+ })
+ return
+ }
+
c.JSON(http.StatusOK, dto.UserResponseDto{
ID: user.ID,
Username: user.Username,
DisplayName: user.DisplayName,
Email: user.Email,
Roles: user.Roles,
- OidcSubjectId: user.OidcSubjectId, // add
+ OidcSubjectId: user.OidcSubjectId,
})
}
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index d918f498b..36724fca0 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -40,13 +40,22 @@ func AuthMiddleware(authService *services.AuthService) gin.HandlerFunc {
return
}
- // Store in Gin context for handlers
- c.Set("currentUser", user)
+ // Store userID instead of full user object
+ c.Set("userID", user.ID)
c.Next()
}
}
+func GetCurrentUserID(c *gin.Context) (string, bool) {
+ userID, exists := c.Get("userID")
+ if !exists {
+ return "", false
+ }
+ userIDStr, ok := userID.(string)
+ return userIDStr, ok
+}
+
func GetCurrentUser(c *gin.Context) (*models.User, bool) {
user, exists := c.Get("currentUser")
if !exists {
diff --git a/backend/internal/services/user_service.go b/backend/internal/services/user_service.go
index b2b3d95f2..ef25af0ed 100644
--- a/backend/internal/services/user_service.go
+++ b/backend/internal/services/user_service.go
@@ -334,3 +334,18 @@ func matchesSearch(u dto.UserResponseDto, searchLower string) bool {
(u.Email != nil && strings.Contains(strings.ToLower(*u.Email), searchLower)) ||
(u.DisplayName != nil && strings.Contains(strings.ToLower(*u.DisplayName), searchLower))
}
+
+func (s *UserService) GetUser(ctx context.Context, userID string) (*models.User, error) {
+ fmt.Println(userID)
+ return s.getUserInternal(ctx, userID, s.db.DB)
+}
+
+func (s *UserService) getUserInternal(ctx context.Context, userID string, tx *gorm.DB) (*models.User, error) {
+ var user models.User
+ err := tx.
+ WithContext(ctx).
+ Where("id = ?", userID).
+ First(&user).
+ Error
+ return &user, err
+}
diff --git a/frontend/src/lib/services/api/api-service.ts b/frontend/src/lib/services/api/api-service.ts
index 180b77dad..57bc7ea9c 100644
--- a/frontend/src/lib/services/api/api-service.ts
+++ b/frontend/src/lib/services/api/api-service.ts
@@ -1,58 +1,54 @@
import axios, { type AxiosResponse } from 'axios';
-import { building, dev } from '$app/environment';
-import { browser } from '$app/environment';
abstract class BaseAPIService {
api = axios.create({
+ baseURL: '/api',
withCredentials: true
});
constructor() {
- if (!building) {
- if (browser) {
- this.api.defaults.baseURL = '/api';
- } else {
- const backendUrl = process.env.BACKEND_URL || 'http://localhost:3552';
- this.api.defaults.baseURL = `${backendUrl}/api`;
- }
+ if (typeof process !== 'undefined' && process?.env?.DEV_BACKEND_URL) {
+ this.api.defaults.baseURL = process.env.DEV_BACKEND_URL;
+ }
- this.api.interceptors.response.use(
- (response: AxiosResponse) => {
- return response;
- },
- (error) => {
- // Only log errors if not building
- if (!building) {
- console.error(
- `API Error [${error.config?.method?.toUpperCase()} ${error.config?.url}]:`,
- {
- status: error.response?.status,
- data: error.response?.data,
- message: error.message
- }
- );
+ this.api.interceptors.response.use(
+ (response) => response,
+ (error) => {
+ const status = error?.response?.status;
+ if (status === 401 && typeof window !== 'undefined') {
+ const reqUrl: string = error?.config?.url ?? '';
+ // Skip auth endpoints and public endpoints to avoid loops
+ const isAuthApi =
+ reqUrl.startsWith('/auth') ||
+ reqUrl.startsWith('/oidc') ||
+ reqUrl.startsWith('/settings/public');
+ const pathname = window.location.pathname || '/';
+ const isOnAuthPage = pathname.startsWith('/auth');
+
+ if (!isAuthApi && !isOnAuthPage) {
+ const redirectTo = encodeURIComponent(pathname);
+ // Hard replace to avoid history pollution
+ window.location.replace(`/auth/login?redirect=${redirectTo}`);
+ // Stop further promise chain
+ return new Promise(() => {});
}
- return Promise.reject(error);
}
- );
- }
+ return Promise.reject(error);
+ }
+ );
}
protected async handleResponse<T>(promise: Promise<AxiosResponse>): Promise<T> {
- if (building) {
- return {} as T;
- }
-
const response = await promise;
-
- // Prefer nested "data" payloads when present
const payload = response.data;
- const extractedData =
- payload && typeof payload === 'object' && 'data' in payload && payload.data !== undefined
- ? payload.data
+ const extracted =
+ payload &&
+ typeof payload === 'object' &&
+ 'data' in payload &&
+ (payload as any).data !== undefined
+ ? (payload as any).data
: payload;
-
- return extractedData;
+ return extracted as T;
}
}
diff --git a/frontend/src/lib/utils/redirect.util.ts b/frontend/src/lib/utils/redirect.util.ts
index bcd1cb225..915d94670 100644
--- a/frontend/src/lib/utils/redirect.util.ts
+++ b/frontend/src/lib/utils/redirect.util.ts
@@ -1,9 +1,34 @@
import type { User } from '$lib/types/user.type';
import type { Settings } from '$lib/types/settings.type';
+const PROTECTED_PREFIXES = [
+ 'dashboard',
+ 'compose',
+ 'containers',
+ 'customize',
+ 'events',
+ 'environments',
+ 'images',
+ 'volumes',
+ 'networks',
+ 'settings'
+];
+
+const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+const PROTECTED_RE = new RegExp(`^/(?:${PROTECTED_PREFIXES.map(escapeRe).join('|')})(?:/.*)?$`);
+
+const isProtectedPath = (path: string) => {
+ const result = PROTECTED_RE.test(path);
+ console.log(`Testing path: "${path}" against regex | Result: ${result}`);
+ console.log(`Regex pattern: ${PROTECTED_RE.source}`);
+ return result;
+};
+
export function getAuthRedirectPath(path: string, user: User | null, settings: Settings | null) {
const isSignedIn = !!user;
+ console.log(`Path: ${path}, isProtected: ${isProtectedPath(path)}, isSignedIn: ${isSignedIn}`);
+
const isUnauthenticatedOnlyPath =
path === '/auth/login' ||
path.startsWith('/auth/login/') ||
@@ -15,14 +40,9 @@ export function getAuthRedirectPath(path: string, user: User | null, settings: S
path.startsWith('/img') ||
path === '/favicon.ico';
- // Root should not render; redirect explicitly
- if (path === '/') {
- return isSignedIn ? '/dashboard' : '/auth/login';
- }
-
const isOnboardingPath = path === '/onboarding' || path.startsWith('/onboarding');
- if (!isSignedIn && !isUnauthenticatedOnlyPath) {
+ if (!isSignedIn && isProtectedPath(path)) {
return '/auth/login';
}
@@ -36,40 +56,9 @@ export function getAuthRedirectPath(path: string, user: User | null, settings: S
return '/dashboard';
}
- if (path === '/' && isSignedIn) {
- return '/dashboard';
+ if (path === '/') {
+ return isSignedIn ? '/dashboard' : '/auth/login';
}
return null;
}
-
-// Lightweight session validator
-async function validateSession(): Promise<boolean> {
- if (typeof window === 'undefined') return true; // SSR: skip
- try {
- const res = await fetch('/api/auth/validate', { credentials: 'include' });
- return res.ok;
- } catch {
- return false;
- }
-}
-
-// Session-aware redirect
-export async function getAuthRedirectPathWithSessionCheck(
- path: string,
- user: User | null,
- settings: Settings | null
-): Promise<string | null> {
- let effectiveUser = user;
-
- if (effectiveUser) {
- const valid = await validateSession();
- if (!valid) {
- effectiveUser = null;
- // Use normal logic for signed-out state; do not return '/'
- return getAuthRedirectPath(path, null, settings);
- }
- }
-
- return getAuthRedirectPath(path, effectiveUser, settings);
-}
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index 25810ec81..94048dcc0 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -7,56 +7,54 @@
import * as Sidebar from '$lib/components/ui/sidebar/index.js';
import AppSidebar from '$lib/components/sidebar/sidebar.svelte';
import { goto } from '$app/navigation';
- import userStore from '$lib/stores/user-store';
- import settingsStore from '$lib/stores/config-store';
- import { getAuthRedirectPathWithSessionCheck } from '$lib/utils/redirect.util';
+ import { getAuthRedirectPath } from '$lib/utils/redirect.util';
import LoadingIndicator from '$lib/components/loading-indicator.svelte';
+ import type { LayoutData } from './$types';
+ import type { Snippet } from 'svelte';
+ import Error from '$lib/components/error.svelte';
- let { children, data } = $props();
+ let {
+ data,
+ children
+ }: {
+ data: LayoutData;
+ children: Snippet;
+ } = $props();
- const { versionInformation, user, settings } = $state(data);
-
- $effect(() => {
- if (user) {
- userStore.setUser(user);
- }
-
- if (settings) {
- settingsStore.set(settings);
- }
- });
-
- $effect(() => {
- const currentUser = $userStore || user;
- const currentSettings = $settingsStore || settings;
-
- // Run session-aware redirect; avoid loops if already on the target path
- (async () => {
- const redirectPath = await getAuthRedirectPathWithSessionCheck(
- page.url.pathname,
- currentUser,
- currentSettings
- );
- if (redirectPath && redirectPath !== page.url.pathname) {
- await goto(redirectPath);
- }
- })();
- });
+ const { versionInformation, user, settings } = data;
const isNavigating = $derived(navigating.type !== null);
const isOnboardingPage = $derived(String(page.url.pathname).startsWith('/onboarding'));
- const isLoginPage = $derived(
- String(page.url.pathname) === '/login' ||
- String(page.url.pathname).startsWith('/auth/login') ||
- String(page.url.pathname) === '/auth' ||
- String(page.url.pathname).includes('/login') ||
- String(page.url.pathname).includes('/callback')
- );
- const currentUser = $derived($userStore || user);
+ const isLoginPage = $derived(page.url.pathname.startsWith('/auth/login'));
+
+ const redirectPath = getAuthRedirectPath(page.url.pathname, user, settings);
+ console.log(page.url.pathname);
+ if (redirectPath) {
+ goto(redirectPath);
+ }
</script>
<svelte:head><title>Arcane</title></svelte:head>
+<div class="bg-background min-h-screen">
+ {#if !settings}
+ <Error message="An Error Occured" showButton={true} />
+ {:else if !isOnboardingPage && !isLoginPage}
+ <Sidebar.Provider>
+ <AppSidebar {versionInformation} {user} />
+ <main class="flex-1">
+ <section class="p-10">
+ {@render children()}
+ </section>
+ </main>
+ </Sidebar.Provider>
+ {:else}
+ <main class="flex-1">
+ {@render children()}
+ </main>
+ {/if}
+</div>
+
<ModeWatcher />
<Toaster
toastOptions={{
@@ -72,20 +70,3 @@
/>
<ConfirmDialog />
<LoadingIndicator active={isNavigating} thickness="h-1.5" />
-
-<div class="bg-background min-h-screen">
- {#if currentUser && !isOnboardingPage && !isLoginPage}
- <Sidebar.Provider>
- <AppSidebar {versionInformation} user={currentUser} />
- <main class="flex-1">
- <section class="p-10">
- {@render children()}
- </section>
- </main>
- </Sidebar.Provider>
- {:else}
- <main class="flex-1">
- {@render children()}
- </main>
- {/if}
-</div>
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index 230e603e2..41afe2e45 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -1,41 +1,55 @@
import { env } from '$env/dynamic/public';
-import type { AppVersionInformation } from '$lib/types/application-configuration';
import { settingsAPI, userAPI, environmentManagementAPI } from '$lib/services/api';
import { environmentStore } from '$lib/stores/environment.store';
import { versionService } from '$lib/services/app-version-service';
import { tryCatch } from '$lib/utils/try-catch';
+import userStore from '$lib/stores/user-store';
+import settingsStore from '$lib/stores/config-store';
export const ssr = false;
export const load = async () => {
const updateCheckDisabled = env.PUBLIC_UPDATE_CHECK_DISABLED === 'true';
- let arcaneSettings = await tryCatch(settingsAPI.getSettings());
- if (arcaneSettings.error) {
- arcaneSettings = await tryCatch(settingsAPI.getPublicSettings());
- }
-
- const arcaneUser = await tryCatch(userAPI.getCurrentUser());
- const user = arcaneUser.error ? null : arcaneUser.data;
+ const userPromise = userAPI.getCurrentUser().catch(() => null);
+ const settingsPromise = settingsAPI.getSettings().catch((e) => {
+ console.error('Error fetching settings:', e);
+ return settingsAPI.getPublicSettings().catch(() => null);
+ });
- if (!environmentStore.isInitialized() && user) {
- const environments = await tryCatch(environmentManagementAPI.list());
- if (!environments.error) {
- await environmentStore.initialize(environments.data || [], true);
+ const environmentsPromise = userPromise.then(async (user) => {
+ if (!environmentStore.isInitialized() && user) {
+ const environments = await tryCatch(environmentManagementAPI.list());
+ if (!environments.error) {
+ await environmentStore.initialize(environments.data || [], true);
+ }
}
+ return null;
+ });
+
+ const versionPromise = updateCheckDisabled
+ ? Promise.resolve({ currentVersion: versionService.getCurrentVersion() })
+ : versionService.getVersionInformation();
+
+ const [user, settings, , versionInformation] = await Promise.all([
+ userPromise,
+ settingsPromise,
+ environmentsPromise,
+ versionPromise
+ ]);
+
+ if (user) {
+ await userStore.setUser(user);
}
- let versionInformation: AppVersionInformation;
- if (updateCheckDisabled) {
- versionInformation = { currentVersion: versionService.getCurrentVersion() };
- } else {
- versionInformation = await versionService.getVersionInformation();
+ if (settings) {
+ settingsStore.set(settings);
}
return {
user,
isAuthenticated: !!user,
- settings: arcaneSettings.data,
+ settings,
versionInformation,
updateCheckDisabled
};
diff --git a/frontend/src/routes/+page.ts b/frontend/src/routes/+page.ts
new file mode 100644
index 000000000..e3bf628c8
--- /dev/null
+++ b/frontend/src/routes/+page.ts
@@ -0,0 +1,6 @@
+import { redirect } from '@sveltejs/kit';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async () => {
+ return redirect(302, '/auth/login');
+};
diff --git a/frontend/src/routes/auth/login/+page.svelte b/frontend/src/routes/auth/login/+page.svelte
index cd5874798..943cdc8e0 100644
--- a/frontend/src/routes/auth/login/+page.svelte
+++ b/frontend/src/routes/auth/login/+page.svelte
@@ -40,7 +40,6 @@
try {
await authService.login({ username, password });
- await invalidateAll();
const redirectTo = data.redirectTo || '/dashboard';
goto(redirectTo);
} catch (err) {
diff --git a/frontend/src/routes/auth/oidc/callback/+page.svelte b/frontend/src/routes/auth/oidc/callback/+page.svelte
index b1dbf08ac..9fe0af072 100644
--- a/frontend/src/routes/auth/oidc/callback/+page.svelte
+++ b/frontend/src/routes/auth/oidc/callback/+page.svelte
@@ -74,8 +74,7 @@
};
userStore.setUser(user);
- await invalidateAll();
- toast.success('Successfully logged in!');
+ toast.success(`Welcome Back, ${user.displayName}`);
goto(redirectTo);
} else {
error = 'Authentication succeeded but user information is missing.';