sivertschou / dundring

dundring.com is a free and open source in-browser training application created to control and track your training with a smart bike trainer⚡️
https://dundring.com
Apache License 2.0
57 stars 5 forks source link

Fix middleware types #198

Open sivertschou opened 1 year ago

sivertschou commented 1 year ago

As per now we have the type AuthenticatedRequest<T> being used for our endpoints requiring a user's token. I have not yet found a way to correctly use the types that model the scenarios that we actually want.

What we want: We'll use post("/me/workout") as our example endpoint. We only wish to accept requests with a token. If a token is provided, we will call the fictional function addWorkout, if not, we will send a response rejecting the request.

To ensure that the request contains a token, we use the middleware function authenticateToken, who's job is to validate the token and make the token's data easily available for the addWorkout function. In Express, we usually append the data we want in the authenticated function to the request parameter, but this leads to some issues with our types.

Intuitively, authenticateToken's request parameter should be Request<T>, and addWorkout's request parameter should be something like AuthenticatedRequest<T>, which should be an extension of Request<T>, where a username: string field is added. We want the

As per now out AuthenticatedRequest<T> has an optional field to make the types compile, username?: string. We obviously want it to be required, but i can't find a way to get the types and the Express middleware workflow to work 🥲

sivertschou commented 1 year ago

The best i've come up with is adding the middleware function as a type guard at the beginning of every function that should be authorized. I'm not too satisfied with it, but i think it is an improvement.

sivertschou commented 1 year ago

Being partly solved in #193