mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-02-06 07:03:47 +01:00
update auth recipe
This commit is contained in:
@@ -6,7 +6,7 @@ The `createContext`-function is called for each incoming request so here you can
|
|||||||
|
|
||||||
```ts
|
```ts
|
||||||
// ~/server/trpc/index.ts
|
// ~/server/trpc/index.ts
|
||||||
import type * as trpc from '@trpc/server'
|
import type { inferAsyncReturnType } from '@trpc/server'
|
||||||
import type { CompatibilityEvent } from 'h3'
|
import type { CompatibilityEvent } from 'h3'
|
||||||
import { decodeAndVerifyJwtToken } from '~/somewhere/in/your/app/utils'
|
import { decodeAndVerifyJwtToken } from '~/somewhere/in/your/app/utils'
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ export async function createContext({ req }: CompatibilityEvent) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type Context = trpc.inferAsyncReturnType<typeof createContext>
|
type Context = inferAsyncReturnType<typeof createContext>
|
||||||
|
|
||||||
// [..] Define API handler and app router
|
// [..] Define API handler and app router
|
||||||
```
|
```
|
||||||
@@ -38,6 +38,8 @@ type Context = trpc.inferAsyncReturnType<typeof createContext>
|
|||||||
### Option 1: Authorize using resolver
|
### Option 1: Authorize using resolver
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
|
import { TRPCError } from '@trpc/server'
|
||||||
|
|
||||||
export const router = trpc
|
export const router = trpc
|
||||||
.router<Context>()
|
.router<Context>()
|
||||||
// open for anyone
|
// open for anyone
|
||||||
@@ -51,7 +53,7 @@ export const router = trpc
|
|||||||
.query('secret', {
|
.query('secret', {
|
||||||
resolve: ({ ctx }) => {
|
resolve: ({ ctx }) => {
|
||||||
if (!ctx.user)
|
if (!ctx.user)
|
||||||
throw new trpc.TRPCError({ code: 'UNAUTHORIZED' })
|
throw new TRPCError({ code: 'UNAUTHORIZED' })
|
||||||
|
|
||||||
return {
|
return {
|
||||||
secret: 'sauce',
|
secret: 'sauce',
|
||||||
@@ -65,7 +67,6 @@ export const router = trpc
|
|||||||
```ts
|
```ts
|
||||||
import * as trpc from '@trpc/server'
|
import * as trpc from '@trpc/server'
|
||||||
import { TRPCError } from '@trpc/server'
|
import { TRPCError } from '@trpc/server'
|
||||||
import { createRouter } from '../createRouter'
|
|
||||||
|
|
||||||
export const router = trpc
|
export const router = trpc
|
||||||
.router<Context>()
|
.router<Context>()
|
||||||
|
|||||||
Reference in New Issue
Block a user