unjs / unstorage

💾 Unstorage provides an async Key-Value storage API with conventional features like multi driver mounting, watching and working with metadata, dozens of built-in drivers and a tiny core.
https://unstorage.unjs.io
MIT License
1.71k stars 128 forks source link

Rewriting the Key from the Authorize method when using the createStorageServer #324

Open Sh4yy opened 10 months ago

Sh4yy commented 10 months ago

Describe the feature

I am building a tiny sync layer between my client and server using the createStorageServer which is working great! However, I would like to be able to rewrite the request key from the authorize method. This would allow me to namespace the data for each user.

I noticed that there is also the resolvePath method, but this is called before the authorize method, and is synchronous, so I can't use it to rewrite the key.

I ended up using a middleware to authorize and rewrite the key, but I think it would be nice to have this functionality built-in to the createStorageServer.

Example

import { createStorageServer } from "unstorage/server";

const storageServer = createStorageServer(storage, {
  authorize: async (req) => {
   const auth = req.event.headers.get('authorization')
    if (!auth) { throw new Error('Unauthorized') }

    const [type, token] = auth.split(' ')
    if (type !== 'Bearer') { throw new Error('Unauthorized') }

    // now we can verify the token
    const user = await verifyToken(token)
    if (!user) { throw new Error('Unauthorized') }
    const userId = normalizeKey(user.id)

    // rewrite the key
    req.key = joinKeys('user', userId, req.key)

    // or maybe return the new key
    return joinKeys('user', userId, req.key)

  },
});

I would be happy to submit a PR for this if you think it's a good idea.

Additional information

harlan-zw commented 10 months ago

Looking at the code, the key modification should be respected given that we are creating a custom context just for the authorize function.

IMO a PR for this would be good

pi0 commented 10 months ago

Thanks for making this issue suggestion. I think it would be nice idea to allow transforming context (key rewrite) but probably we can introduce a new hook that gets called after authorize to allow this conditionally based on auth context.

Feel feee to open a draft PR for this 💯