S
SolidJSsh1man

what write so as not to constantly write a redirect in every function in case of unauthorize

I don’t have a database on the solidstart server, I only work with third-party APIs. Where to store user information. I want not to write in some functions constantly the same code for processing unauthorized. You need to write a wrapper function?
export const getUser = cache(async () => {
"use server";
try {
const session = await getSession();
const userId = session.data.userId;
if (userId === undefined) throw new Error("User not found");
const user = await db.user.findUnique({ where: { id: userId } });
if (!user) throw new Error("User not found");
return { id: user.id, username: user.username };
} catch {
await logoutSession();
throw redirect("/login");
}
}, "user");
export const getUser = cache(async () => {
"use server";
try {
const session = await getSession();
const userId = session.data.userId;
if (userId === undefined) throw new Error("User not found");
const user = await db.user.findUnique({ where: { id: userId } });
if (!user) throw new Error("User not found");
return { id: user.id, username: user.username };
} catch {
await logoutSession();
throw redirect("/login");
}
}, "user");
D
Dog26d ago
Are you using supabase and @solid-mediakit/auth?
S
sh1man26d ago
no i use lucia everything works fine for me
D
Dog26d ago
oh ok do you use supabase with lucia?
S
sh1man26d ago
no, i use prisma
D
Dog26d ago
because I'm trying to implement row level security with supabase and can't get it to work ok I think I have another project that used prisma let me check
S
sh1man26d ago
I did it like this
No description
No description
D
Dog26d ago
export const authOpts: SolidAuthConfig = {
adapter: PrismaAdapter(prisma),
providers: [
Google({
clientId: serverEnv.GOOGLE_CLIENT_ID,
clientSecret: serverEnv.GOOGLE_CLIENT_SECRET,
})
],
callbacks: {
async session({ session, user }) {
if (session.user) {
session.user.id = user.id;
}
const signingSecret = serverEnv.SUPABASE_JWT_SECRET
if (signingSecret) {
const payload = {
aud: "authenticated",
exp: Math.floor(new Date(session.expires).getTime() / 1000),
// sub: user.id,
email: user.email,
role: "authenticated",
}
session.supabaseAccessToken = jwt.sign(payload, signingSecret)
}
return session
},
},
debug: false,
};
export const authOpts: SolidAuthConfig = {
adapter: PrismaAdapter(prisma),
providers: [
Google({
clientId: serverEnv.GOOGLE_CLIENT_ID,
clientSecret: serverEnv.GOOGLE_CLIENT_SECRET,
})
],
callbacks: {
async session({ session, user }) {
if (session.user) {
session.user.id = user.id;
}
const signingSecret = serverEnv.SUPABASE_JWT_SECRET
if (signingSecret) {
const payload = {
aud: "authenticated",
exp: Math.floor(new Date(session.expires).getTime() / 1000),
// sub: user.id,
email: user.email,
role: "authenticated",
}
session.supabaseAccessToken = jwt.sign(payload, signingSecret)
}
return session
},
},
debug: false,
};
export const useSession = () => {
return createServerData$(
async (_, { request }) => {
return await getSession(request, authOpts)
},
{ key: () => ["auth_user"] }
)
}

const AuthShowcase: VoidComponent = () => {
const session = useSession();
return (
<div>
<Show
when={session()}
fallback={
<button
onClick={() => signIn("google", { redirect: false })}
>
Sign in
</button>
}
>
<span>Welcome {session()?.user?.name}</span>
<button
onClick={() => signOut({ redirect: true, redirectTo: "/" })}
>
Sign out
</button>
</Show>
</div>
);
};
export const useSession = () => {
return createServerData$(
async (_, { request }) => {
return await getSession(request, authOpts)
},
{ key: () => ["auth_user"] }
)
}

const AuthShowcase: VoidComponent = () => {
const session = useSession();
return (
<div>
<Show
when={session()}
fallback={
<button
onClick={() => signIn("google", { redirect: false })}
>
Sign in
</button>
}
>
<span>Welcome {session()?.user?.name}</span>
<button
onClick={() => signOut({ redirect: true, redirectTo: "/" })}
>
Sign out
</button>
</Show>
</div>
);
};
I was doing somethig like this to get the session user data but this was sing the old solid-start
S
sh1man26d ago
I didn't work with @solid-mediakit/auth and supabase. I can't help with this
D
Dog26d ago
no this is what you can do for your question, do the <Show when={session} or did you all ready solve this?
S
sh1man26d ago
yes
D
Dog26d ago
oh my bad I thought you hadn't
S
sh1man26d ago
Enough time has passed)
D
Dog26d ago
I normally get stuck on problems for weeks 😆
Want results from more Discord servers?
Add your server
More Posts
Solid doesn't re-render when update the same array in createSignalExpected behavior: Re-render inputs every time passwords array is updated even with the same value,For some reason <select> doesn't work correctlyhttps://playground.solidjs.com/anonymous/eedf65f3-e52b-49b0-a8b2-513465a75666 Here it is. When changCan someone tell me how to redirect the user on each API, if 401, that is, do not write the logic agCan someone tell me how to redirect the user on each API, if 401, that is, do not write the logic agHow to use web component in solidjsPlease ask solidjs how to solve the use of web component component editor ts reported error PropertyHow do I debug updatesI thought My app is working fine except I noticed a lag, which performance profile shows lots of unnHow to detect button holding in solid js?Does anyone know how to detect a button being holding for 2 seconds and are there any libraries or bVite internal server error expected "}" but found end of filesee screenshot, this is not the end of the file (not even close)How do I "curry" a function with props?I have a method "colorize" that receives two arguments: hue and shade. A component has a props.hue aMobX + SolidJS enableExternalSource untracked bug?I am evaluating using MobX with SolidJS and now that there is an `untrack` parameter to `enableExterhow to efficiently make nested data structures in solidHello, I am new to Solid atm, but am aware of some reactivity principles like singals, memos, effectSolidStart - Nitro Module missing `context` keys in `request`Hey guys, I understand what I am asking about is likely out of scope, as this is dealing with a 3rHandle user interactions to send backendI would like to know what are methods that can handle identification of user interaction points likeHow do I use solid for reactivity without a build step?I like solid as a frontend library, and I want to use it as a "vanilla" state management library foruse directive typescript errorWhen i try to use the use: directive i get the error ```Type '{ type: string; placeholder: string; vI have to fetch initial information in a component, how do I do it?const App: Component = () => { const resp = await fetch(...); // show Home component after fDynamically creating resources based on reactive state in Solid Store**What would be the right approach to solve this using solids reactivity? ** I want to achieve the Struggling to understand the correct way to use createResource with a storeI have a global store `export const [dataStore, setDataStore] = createStore({ some: "data"}) `, whicHow do I "protect" routes? I am using @solidjs/routerNow that Outlet is not supported anymore? How do I implement a route guard for nested routes?What are canonical patterns to separate UI from domain logic in SolidJS?I am developing an app that helps guitarists to learn notes. Users learn notes by exercising. The exsolidjs createResource doesn't show error when there was an error i.e 401 Invalid credentialscreateResource data.error always false