-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add protected trpc router example (#194)
- Loading branch information
1 parent
126aaae
commit 4ad5c93
Showing
5 changed files
with
57 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { createProtectedRouter } from "./protected-router"; | ||
|
||
// Example router with queries that can only be hit if the user requesting is signed in | ||
export const protectedExampleRouter = createProtectedRouter() | ||
.query("getSession", { | ||
resolve({ ctx }) { | ||
return ctx.session; | ||
}, | ||
}) | ||
.query("getSecretMessage", { | ||
resolve({ ctx }) { | ||
return "He who asks a question is a fool for five minutes; he who does not ask a question remains a fool forever."; | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import * as trpc from "@trpc/server"; | ||
import { createRouter } from "./context"; | ||
|
||
/** | ||
* Creates a tRPC router that asserts all queries and mutations are from an authorized user. Will throw an unauthorized error if a user is not signed in. | ||
*/ | ||
export function createProtectedRouter() { | ||
return createRouter().middleware(({ ctx, next }) => { | ||
if (!ctx.session || !ctx.session.user) { | ||
throw new trpc.TRPCError({ code: "UNAUTHORIZED" }); | ||
} | ||
return next({ | ||
ctx: { | ||
...ctx, | ||
// infers that `session` is non-nullable to downstream resolvers | ||
session: { ...ctx.session, user: ctx.session.user }, | ||
}, | ||
}); | ||
}); | ||
} |