Skip to content

Commit 52a7c9a

Browse files
fix(shared): resolve session persistence issue on browser refresh
- Initialize session state on SupabaseService startup - Add async getCurrentSession() method for reliable session retrieval - Make authAdminGuard async to properly await session initialization - Add auth state change listener to maintain session updates 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 1cc41d0 commit 52a7c9a

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

projects/admin/src/app/core/guards/authAdminGuard.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ import { CanMatchFn, Router } from '@angular/router';
33
import { Roles } from 'shared';
44
import { SupabaseService } from 'shared';
55

6-
export const authAdminGuard: CanMatchFn = (): boolean => {
6+
export const authAdminGuard: CanMatchFn = async (): Promise<boolean> => {
77
const supabaseService = inject(SupabaseService);
88
const router = inject(Router);
9-
const session = supabaseService.getSession();
9+
10+
const session = await supabaseService.getCurrentSession();
1011
if (session?.user?.app_metadata?.['role'] === Roles.ADMIN) {
1112
return true;
1213
} else {

projects/shared/src/services/supabase.service.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,34 @@ export class SupabaseService {
2121
this.supabase = this.ngZone.runOutsideAngular(() =>
2222
createClient(environment.supabaseUrl, environment.supabaseKey)
2323
);
24+
this.initializeSession();
25+
}
26+
27+
private async initializeSession(): Promise<void> {
28+
const { data: { session } } = await this.supabase.auth.getSession();
29+
this.session = session;
30+
31+
this.supabase.auth.onAuthStateChange((event, session) => {
32+
this.ngZone.run(() => {
33+
this.session = session;
34+
});
35+
});
2436
}
2537

2638
getSession(): AuthSession | null {
2739
return this.session;
2840
}
2941

42+
async getCurrentSession(): Promise<AuthSession | null> {
43+
if (this.session) {
44+
return this.session;
45+
}
46+
47+
const { data: { session } } = await this.supabase.auth.getSession();
48+
this.session = session;
49+
return session;
50+
}
51+
3052
authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) {
3153
return this.supabase.auth.onAuthStateChange(callback);
3254
}

0 commit comments

Comments
 (0)