webdevcody / wdc-saas-starter-kit

https://wdcstarterkit.com/
MIT License
1.14k stars 268 forks source link

Protect the routes!!! #12

Open Kiranism opened 3 months ago

Kiranism commented 3 months ago

@webdevcody Hey, what can we do to protect the routes? Since we aren't using middleware, maybe we can do the checks directly in the pages?

something like export default async function Dashboard() { const user = await getUser(); if (!user) { return redirect('/admin/login'); } return (...)

image

evert-arias commented 3 months ago

@Kiranism You can protect routes by calling assertAuthenticated at the start of each protected page. This function returns the current user if logged in, or throws an error if not. Then error.tsx page catches these errors and shows a "not authenticated" message if it's an auth error.

Kiranism commented 3 months ago

Yeah, that will work. Maybe that can be added to the code.

evert-arias commented 3 months ago

It's already in the code. The dashboard page uses the assertAuthenticated function which is implemented in lib/session.ts.

Kiranism commented 3 months ago

It's already in the code. The dashboard page uses the assertAuthenticated function which is implemented in lib/session.ts.

It just throwing an error. Please check this picture https://github.com/webdevcody/wdc-saas-starter-kit/issues/12#issue-2432150213

evert-arias commented 3 months ago

@Kiranism I see. There were a few issues I had to solve to get this template work on production. I'll check that out.

evert-arias commented 3 months ago

So, when built for production, isAuthenticationError evaluates as false, but not when running locally in dev mode. As a result, it is showing the generic error message instead of the authentication error message.

image
webdevcody commented 3 months ago

I think having a method called assertAuthenticatedAndRedirect('/your/url') would be my recommendation. I personally don't like when a user is just randomly redirected to a new page; I'd rather show them an error so they know not to do it again. I can look into this error difference between prod and dev and try to update this.

evert-arias commented 3 months ago

I concur with that strategy.

Kiranism commented 3 months ago

I think having a method called assertAuthenticatedAndRedirect('/your/url') would be my recommendation. I personally don't like when a user is just randomly redirected to a new page; I'd rather show them an error so they know not to do it again. I can look into this error difference between prod and dev and try to update this.

Fair enough. I also noticed that you can still visit the login page (auth routes) after signing in, which can be avoided with a similar check."