-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathAuthContext.tsx
More file actions
208 lines (182 loc) · 6.3 KB
/
AuthContext.tsx
File metadata and controls
208 lines (182 loc) · 6.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
'use client';
import { createContext, useContext, useEffect, useState, useRef } from 'react';
import { getClient } from '@/lib/supabase/client';
import { useRouter } from 'next/navigation';
import { notifySuccess, notifyError } from '@/utils/notifications';
import type { User, Session } from '@supabase/supabase-js';
import type { TContextProviderProps } from '@/context/types';
import type { TNullable } from '@/lib/types';
type TAuthContext = {
user: TNullable<User>;
session: TNullable<Session>;
loading: boolean;
signInWithProvider: (provider: 'google' | 'github') => Promise<void>;
signInWithEmailOtp: (email: string) => Promise<boolean>;
logout: () => Promise<void>;
};
// Storage keys
const RETURN_TO_KEY = 'authReturnTo';
const WELCOME_SHOWN_KEY = 'authWelcomeShown';
// Helper to store return URL before auth
export const storeReturnUrl = () => {
if (typeof window !== 'undefined') {
const currentPath = window.location.pathname;
if (currentPath !== '/login' && currentPath !== '/') {
sessionStorage.setItem(RETURN_TO_KEY, currentPath);
}
}
};
// Helper to get and clear return URL
const getAndClearReturnUrl = (): string => {
if (typeof window !== 'undefined') {
const returnTo = sessionStorage.getItem(RETURN_TO_KEY);
sessionStorage.removeItem(RETURN_TO_KEY);
if (returnTo && returnTo.startsWith('/') && !returnTo.startsWith('//')) {
return returnTo;
}
}
return '/';
};
const AuthContext = createContext<TNullable<TAuthContext>>(null);
export const useAuth = () => useContext(AuthContext);
export const AuthProvider = ({ children }: TContextProviderProps) => {
const [user, setUser] = useState<TNullable<User>>(null);
const [session, setSession] = useState<TNullable<Session>>(null);
const [loading, setLoading] = useState<boolean>(true);
const router = useRouter();
// Use refs to track state for the subscription callback without causing re-subscriptions
const previousUserRef = useRef<TNullable<User>>(null);
const routerRef = useRef(router);
// Keep refs up to date
routerRef.current = router;
useEffect(() => {
const supabase = getClient();
// Get initial session. If local auth state is corrupt/stale, fail closed
// to anonymous and ask the server cleanup route to expire any leftover
// Supabase cookies rather than leaving the app permanently "loading".
supabase.auth
.getSession()
.then(({ data: { session }, error }) => {
if (error) {
void fetch('/auth/logout', { method: 'POST' }).catch(() => {});
}
const safeSession = error ? null : session;
setSession(safeSession);
setUser(safeSession?.user ?? null);
previousUserRef.current = safeSession?.user ?? null;
})
.catch(() => {
void fetch('/auth/logout', { method: 'POST' }).catch(() => {});
setSession(null);
setUser(null);
previousUserRef.current = null;
})
.finally(() => {
setLoading(false);
});
// Listen for auth changes - subscription should only be created once
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((event, session) => {
const newUser = session?.user ?? null;
// Update refs and state
previousUserRef.current = newUser;
setSession(session);
setUser(newUser);
setLoading(false);
// Show welcome message only on actual sign-in, not on page load/refresh
// SIGNED_IN fires when user actively signs in (OAuth, magic link, OTP)
// INITIAL_SESSION fires on page load with existing session - don't show notification
// Use sessionStorage to ensure notification only shows once per browser session
if (event === 'SIGNED_IN' && newUser) {
const welcomeShown = sessionStorage.getItem(WELCOME_SHOWN_KEY);
if (!welcomeShown) {
const displayName =
newUser.user_metadata?.full_name ||
newUser.email?.split('@')[0] ||
'there';
notifySuccess({
title: 'Welcome back!',
message: `Signed in as ${displayName}`,
});
sessionStorage.setItem(WELCOME_SHOWN_KEY, 'true');
}
// Smart redirect
const returnTo = getAndClearReturnUrl();
if (returnTo !== '/') {
routerRef.current.push(returnTo);
}
}
// Clear welcome flag on sign out so it shows again on next sign-in
if (event === 'SIGNED_OUT') {
sessionStorage.removeItem(WELCOME_SHOWN_KEY);
}
});
return () => subscription.unsubscribe();
}, []); // Empty dependency array - subscription should only be created once
const signInWithProvider = async (
provider: 'google' | 'github'
) => {
const supabase = getClient();
const { error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
});
if (error) {
notifyError({
title: 'Sign in failed',
message: error.message,
});
}
};
const signInWithEmailOtp = async (email: string): Promise<boolean> => {
const supabase = getClient();
const { error } = await supabase.auth.signInWithOtp({ email });
if (error) {
notifyError({
title: 'Failed to send code',
message: error.message,
});
return false;
}
const isGTEmail = email.endsWith('@gatech.edu');
const isOutlookEmail = email.endsWith('@outlook.com');
const additionalInstructions =
isGTEmail || isOutlookEmail
? ' NOTE: gatech.edu or outlook.com may require release from Quarantine. See https://security.microsoft.com/quarantine'
: '';
notifySuccess({
title: 'Code Sent!',
message: `Check your inbox at ${email}.${additionalInstructions}`,
autoClose: 8000,
});
return true;
};
const logout = async () => {
const supabase = getClient();
try {
await supabase.auth.signOut();
} finally {
await fetch('/auth/logout', { method: 'POST' }).catch(() => {});
}
setUser(null);
setSession(null);
router.push('/');
};
return (
<AuthContext.Provider
value={{
user,
session,
loading,
signInWithProvider,
signInWithEmailOtp,
logout,
}}
>
{children}
</AuthContext.Provider>
);
};