|
1 | 1 | /* eslint-disable node/prefer-global/process */ |
2 | 2 | import type { LoaderFunction } from '@remix-run/node' |
3 | 3 | import { redirect } from '@remix-run/node' |
| 4 | +import { commitSession, getSession } from '../sessions' // Import session utilities |
4 | 5 |
|
5 | | -export const loader: LoaderFunction = async () => { |
6 | | - return redirect(`${process.env.NODE_ENV === 'development' ? process.env.CUHACKING_2025_AXIOM_LOCAL_URL : process.env.CUHACKING_2025_AXIOM_PUBLIC_URL}/api/users/oauth/linkedin`) |
7 | | - // HALP we need to log the user in and then set the session storage to save the userId |
8 | | - /* return redirect('/login') */ |
| 6 | +export const loader: LoaderFunction = async ({ request }) => { |
| 7 | + const baseUrl |
| 8 | + = process.env.NODE_ENV === 'development' |
| 9 | + ? 'http://localhost:8000' |
| 10 | + : 'https://axiom.cuhacking.ca' |
| 11 | + |
| 12 | + try { |
| 13 | + const authResponse = await fetch(`${baseUrl}/api/users/oauth/linkedin`, { |
| 14 | + method: 'POST', |
| 15 | + headers: { |
| 16 | + 'Content-Type': 'application/json', |
| 17 | + }, |
| 18 | + credentials: 'include', |
| 19 | + }) |
| 20 | + |
| 21 | + if (!authResponse.ok) { |
| 22 | + console.error('OAuth login failed:', authResponse.status, authResponse.statusText) |
| 23 | + return redirect('/login') |
| 24 | + } |
| 25 | + |
| 26 | + const userResponse = await fetch(`${baseUrl}/api/users/me`, { |
| 27 | + method: 'GET', |
| 28 | + headers: { |
| 29 | + 'Content-Type': 'application/json', |
| 30 | + }, |
| 31 | + credentials: 'include', |
| 32 | + }) |
| 33 | + |
| 34 | + if (!userResponse.ok) { |
| 35 | + console.error('Failed to fetch user data:', userResponse.status, userResponse.statusText) |
| 36 | + return redirect('/login') |
| 37 | + } |
| 38 | + |
| 39 | + const userData = await userResponse.json() |
| 40 | + const userId = userData?.id |
| 41 | + |
| 42 | + if (!userId) { |
| 43 | + console.error('No userId returned from API') |
| 44 | + return redirect('/login') |
| 45 | + } |
| 46 | + |
| 47 | + const session = await getSession(request.headers.get('Cookie')) |
| 48 | + session.set('userId', userId) |
| 49 | + |
| 50 | + return redirect('/dashboard', { |
| 51 | + headers: { |
| 52 | + 'Set-Cookie': await commitSession(session), |
| 53 | + }, |
| 54 | + }) |
| 55 | + } |
| 56 | + catch (error) { |
| 57 | + console.error('Error during OAuth login:', error) |
| 58 | + return redirect('/login') |
| 59 | + } |
9 | 60 | } |
10 | 61 |
|
11 | 62 | export default function AuthRedirect() { |
|
0 commit comments