#How to retrieve the id from the logged in user
1 messages · Page 1 of 1 (latest)
Based on the provided knowledge sources, there isn't a direct example of retrieving a dynamic user ID from a logged-in user. However, there are examples of how to handle authentication and redirection based on user status.
In Astro, you can use the Astro.redirect method to redirect to another page dynamically, which might be useful after checking if the user is logged in by getting their session from a cookie. Here's an example:
---import { isLoggedIn } from '../utils';
const cookie = Astro.request.headers.get('cookie');
// If the user is not logged in, redirect them to the login page
if (!isLoggedIn(cookie)) {
return Astro.redirect('/login');
}---
<html>
<!-- Page here... -->
</html>
(Source: Astro Docs - Dynamic Redirects (https://docs.astro.build/en/guides/routing/#dynamic-redirects))
For handling authentication with Supabase, you can use the supabase.auth.setSession method to set the session using the access and refresh tokens. If the session setting fails, you can redirect the user to the sign-in page. Here's an example:
const accessToken = cookies.get("sb-access-token");
const refreshToken = cookies.get("sb-refresh-token");
if (!accessToken || !refreshToken) {
return redirect("/signin");
}
const { data, error } = await supabase.auth.setSession({
refresh_token: refreshToken.value,
access_token: accessToken.value,
});
if (error) {
cookies.delete("sb-access-token", {
path: "/",
});
cookies.delete("sb-refresh-token", {
path: "/",
});
return redirect("/signin");
}
const email = data.user?.email;
(Source: Astro Docs - Creating Auth Pages (https://docs.astro.build/en/guides/backend/supabase/#creating-auth-pages))