DEV Community

KenA
KenA

Posted on

HowTo: Gated Website

Hi. The idea is quite simple: when the user tries to access the website, the first presented page is a login page with just 1 password field. I don't need to actually Register a user with details like: name, username, email, address, etc.

I believe what I have to do is to have all routes of this website protected and just "free" them after successful login. Some kind of token should be saved so for each post login request I should verify the presence of this token.

The website is written using SvelteKit.

What would be the possible solutions to accomplish this task? Thanks in advance for sharing your ideas.

Top comments (3)

Collapse
 
kena profile image
KenA

Yeap, that's the idea ... I just don't know how to configure access control on the server side. or how a free hosting service provider would allow you to configure it.

Collapse
 
nikfp profile image
Nik F P

You could host this on Vercel, and use Vercel's encrypted environment variables to store a private key of some sort. I think Netlify would work also, and maybe Cloudflare as well.

From there, you are treating the user supplied password as a bearer token, validating it against the private key, and creating a signed bearer token for the session (different from the token the user gave you to start with), passed around using using something like HTTP only cookies.

The pattern I might use would be to parse cookies and check for the session token in the Handle hook, and pass something through locals to identify which client it is and if they are allowed to access anything. If the cookie isn't present, the hook still runs and forwards the request to the endpoint that was targeted.

Then in the endpoints, every route except for the login route would check for auth status and redirect to login if the user is not authenticated.

Then the login endpoint would parse out the token you supplied to the user through the form submit, validate it, set the cookie with the session bearer token, and send a response. This then gets you back to checking the cookie in the handle hook on future requests, but since the cookie is now present and valid, the other endpoints will pick it up and do the work instead of redirecting.

The downside to this is that your server side execution is stateless, which is normally good, however the only way to revoke access to the site is to redeploy with a different private key. Vercel and Netlify should both work for this pattern though. Just keep in mind that ANYONE that has one of the sign in tokens will be able to sign in as that user, from anywhere. The same user will also be able to sign in multiple times at once.

If you wanted to tie this in to a durable session store of some sort, you might look at cloudflare's KV or durable objects offerings.

Collapse
 
barathrum54 profile image
Taha

provide a unique key to them, make them access your page using the key you gave them after transaction