Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
1 task done
Sh4yy opened this issue Oct 20, 2023 · 2 comments
Open
1 task done
Labels
enhancement New feature or request

Comments

@Sh4yy
Copy link

Sh4yy commented Oct 20, 2023

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

  • Would you be willing to help implement this feature?
@harlan-zw
Copy link
Contributor

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
Copy link
Member

pi0 commented Oct 21, 2023

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 💯

@pi0 pi0 added the enhancement New feature or request label May 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants