webdevcody / wdc-saas-starter-kit

https://wdcstarterkit.com/
MIT License
867 stars 221 forks source link

Protect the routes!!! #12

Open Kiranism opened 1 month ago

Kiranism commented 1 month 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 1 month 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 1 month ago

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

evert-arias commented 1 month ago

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

Kiranism commented 1 month 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 1 month 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 1 month 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 1 month 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 1 month ago

I concur with that strategy.

Kiranism commented 1 month 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."