권한 부여
비공식 베타 번역
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
createContext 함수는 들어오는 각 요청에 대해 호출되므로, 여기에서 요청 객체를 통해 호출 사용자에 대한 컨텍스트 정보를 추가할 수 있습니다.
요청 헤더로부터 컨텍스트 생성
server/context.tstsimport type {CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';import {decodeAndVerifyJwtToken } from './utils';export async functioncreateContext ({req ,res }:CreateHTTPContextOptions ) {// Create your context based on the request object// Will be available as `ctx` in all your resolvers// This is just an example of something you might want to do in your ctx fnasync functiongetUserFromHeader () {if (req .headers .authorization ) {constuser = awaitdecodeAndVerifyJwtToken (req .headers .authorization .split (' ')[1],);returnuser ;}return null;}constuser = awaitgetUserFromHeader ();return {user ,};}export typeContext =Awaited <ReturnType <typeofcreateContext >>;
server/context.tstsimport type {CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';import {decodeAndVerifyJwtToken } from './utils';export async functioncreateContext ({req ,res }:CreateHTTPContextOptions ) {// Create your context based on the request object// Will be available as `ctx` in all your resolvers// This is just an example of something you might want to do in your ctx fnasync functiongetUserFromHeader () {if (req .headers .authorization ) {constuser = awaitdecodeAndVerifyJwtToken (req .headers .authorization .split (' ')[1],);returnuser ;}return null;}constuser = awaitgetUserFromHeader ();return {user ,};}export typeContext =Awaited <ReturnType <typeofcreateContext >>;
옵션 1: 리졸버를 사용한 권한 부여
server/routers/_app.tstsimport {initTRPC ,TRPCError } from '@trpc/server';import {z } from 'zod';typeContext = {user : {name : string } | null };export constt =initTRPC .context <Context >().create ();constappRouter =t .router ({// open for anyonehello :t .procedure .input (z .string ().nullish ()).query ((opts ) => `hello ${opts .input ??opts .ctx .user ?.name ?? 'world'}`),// checked in resolversecret :t .procedure .query ((opts ) => {if (!opts .ctx .user ) {throw newTRPCError ({code : 'UNAUTHORIZED' });}return {secret : 'sauce',};}),});
server/routers/_app.tstsimport {initTRPC ,TRPCError } from '@trpc/server';import {z } from 'zod';typeContext = {user : {name : string } | null };export constt =initTRPC .context <Context >().create ();constappRouter =t .router ({// open for anyonehello :t .procedure .input (z .string ().nullish ()).query ((opts ) => `hello ${opts .input ??opts .ctx .user ?.name ?? 'world'}`),// checked in resolversecret :t .procedure .query ((opts ) => {if (!opts .ctx .user ) {throw newTRPCError ({code : 'UNAUTHORIZED' });}return {secret : 'sauce',};}),});
옵션 2: 미들웨어를 사용한 권한 부여
server/routers/_app.tstsimport {initTRPC ,TRPCError } from '@trpc/server';import {z } from 'zod';typeContext = {user : {name : string } | null };export constt =initTRPC .context <Context >().create ();// you can reuse this for any procedureexport constprotectedProcedure =t .procedure .use (async functionisAuthed (opts ) {const {ctx } =opts ;// `ctx.user` is nullableif (!ctx .user ) {throw newTRPCError ({code : 'UNAUTHORIZED' });}returnopts .next ({ctx : {// ✅ user value is known to be non-null nowuser :ctx .user ,},});},);t .router ({// this is accessible for everyonehello :t .procedure .input (z .string ().nullish ()).query ((opts ) => `hello ${opts .input ??opts .ctx .user ?.name ?? 'world'}`),admin :t .router ({// this is accessible only to adminssecret :protectedProcedure .query ((opts ) => {return {secret : 'sauce',};}),}),});
server/routers/_app.tstsimport {initTRPC ,TRPCError } from '@trpc/server';import {z } from 'zod';typeContext = {user : {name : string } | null };export constt =initTRPC .context <Context >().create ();// you can reuse this for any procedureexport constprotectedProcedure =t .procedure .use (async functionisAuthed (opts ) {const {ctx } =opts ;// `ctx.user` is nullableif (!ctx .user ) {throw newTRPCError ({code : 'UNAUTHORIZED' });}returnopts .next ({ctx : {// ✅ user value is known to be non-null nowuser :ctx .user ,},});},);t .router ({// this is accessible for everyonehello :t .procedure .input (z .string ().nullish ()).query ((opts ) => `hello ${opts .input ??opts .ctx .user ?.name ?? 'world'}`),admin :t .router ({// this is accessible only to adminssecret :protectedProcedure .query ((opts ) => {return {secret : 'sauce',};}),}),});