DINOD
tRPC2y ago
1 reply
DINO

How do I implement API key authorization along with JWT authorization in tRPC?

Hello,

I want to make some routes protected and to be accessed by either JWT auth or by API keys auth. So I check both auth methods in the same context.
To make things clear i will just share the code of my context:
export async function createContext({ req, res }: CreateFastifyContextOptions) {
  async function getUser() {
    try {
      const apiKey = req.headers['x-api-key']

      if (apiKey) {
        if (typeof apiKey !== 'string') {
          throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid API key' })
        }
        const isValid = await validateApiKey(apiKey)
        return {
          user: null,
          isAuthorized: isValid
        }
      } else {
        await req.jwtVerify()
        const em = orm.em.fork()
        const user = await em.findOne(User, { _id: new ObjectId(req.user.id) })

        if (!user) return null
        const u = wrap(user).toPOJO()
        return {
          user: u,
          isAuthorized: true
        }
      }
    } catch (err) {
      console.log('Error getting user from header or cookie', err)
      return null
    }
  }

  const user = await getUser()

  return {
    req,
    res,
    user
  }
}

I am using Fastify.js. What do you think of this approach?

Thanks.
Was this page helpful?