-
-
Notifications
You must be signed in to change notification settings - Fork 675
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c616efe
commit a190360
Showing
34 changed files
with
3,945 additions
and
4 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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
195 changes: 195 additions & 0 deletions
195
website/versioned_docs/version-2.0.0-beta.3/authorization.md
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,195 @@ | ||
--- | ||
title: Authorization | ||
id: version-2.0.0-beta.3-authorization | ||
original_id: authorization | ||
--- | ||
|
||
Authorization is a core feature used in almost all APIs. Sometimes we want to restrict data access or actions for a specific group of users. | ||
|
||
In express.js (and other Node.js frameworks) we use middleware for this, like `passport.js` or the custom ones. However, in GraphQL's resolver architecture we don't have middleware so we have to imperatively call the auth checking function and manually pass context data to each resolver, which might be a bit tedious. | ||
|
||
That's why authorization is a first-class feature in `TypeGraphQL`! | ||
|
||
## How to use | ||
|
||
First, we need to use the `@Authorized` decorator as a guard on a field, query or mutation. | ||
Example object type field guards: | ||
|
||
```ts | ||
@ObjectType() | ||
class MyObject { | ||
@Field() | ||
publicField: string; | ||
|
||
@Authorized() | ||
@Field() | ||
authorizedField: string; | ||
|
||
@Authorized("ADMIN") | ||
@Field() | ||
adminField: string; | ||
|
||
@Authorized(["ADMIN", "MODERATOR"]) | ||
@Field({ nullable: true }) | ||
hiddenField?: string; | ||
} | ||
``` | ||
|
||
We can leave the `@Authorized` decorator brackets empty or we can specify the role/roles that the user needs to possess in order to get access to the field, query or mutation. | ||
By default the roles are of type `string` but they can easily be changed as the decorator is generic - `@Authorized<number>(1, 7, 22)`. | ||
|
||
Thus, authorized users (regardless of their roles) can only read the `publicField` or the `authorizedField` from the `MyObject` object. They will receive `null` when accessing the `hiddenField` field and will receive an error (that will propagate through the whole query tree looking for a nullable field) for the `adminField` when they don't satisfy the role constraints. | ||
|
||
Sample query and mutation guards: | ||
|
||
```ts | ||
@Resolver() | ||
class MyResolver { | ||
@Query() | ||
publicQuery(): MyObject { | ||
return { | ||
publicField: "Some public data", | ||
authorizedField: "Data for logged users only", | ||
adminField: "Top secret info for admin", | ||
}; | ||
} | ||
|
||
@Authorized() | ||
@Query() | ||
authedQuery(): string { | ||
return "Authorized users only!"; | ||
} | ||
|
||
@Authorized("ADMIN", "MODERATOR") | ||
@Mutation() | ||
adminMutation(): string { | ||
return "You are an admin/moderator, you can safely drop the database ;)"; | ||
} | ||
} | ||
``` | ||
|
||
Authorized users (regardless of their roles) will be able to read data from the `publicQuery` and the `authedQuery` queries, but will receive an error when trying to perform the `adminMutation` when their roles don't include `ADMIN` or `MODERATOR`. | ||
|
||
Next, we need to create our auth checker function. Its implementation may depend on our business logic: | ||
|
||
```ts | ||
export const customAuthChecker: AuthChecker<ContextType> = ( | ||
{ root, args, context, info }, | ||
roles, | ||
) => { | ||
// Read user from context | ||
// and check the user's permission against the `roles` argument | ||
// that comes from the '@Authorized' decorator, eg. ["ADMIN", "MODERATOR"] | ||
|
||
return true; // or 'false' if access is denied | ||
}; | ||
``` | ||
|
||
The second argument of the `AuthChecker` generic type is `RoleType` - used together with the `@Authorized` decorator generic type. | ||
|
||
Auth checker can be also defined as a class - this way we can leverage the dependency injection mechanism: | ||
|
||
```ts | ||
export class CustomAuthChecker implements AuthCheckerInterface<ContextType> { | ||
constructor( | ||
// Dependency injection | ||
private readonly userRepository: Repository<User>, | ||
) {} | ||
|
||
check({ root, args, context, info }: ResolverData<ContextType>, roles: string[]) { | ||
const userId = getUserIdFromToken(context.token); | ||
// Use injected service | ||
const user = this.userRepository.getById(userId); | ||
|
||
// Custom logic, e.g.: | ||
return user % 2 === 0; | ||
} | ||
} | ||
``` | ||
|
||
The last step is to register the function or class while building the schema: | ||
|
||
```ts | ||
import { customAuthChecker } from "../auth/custom-auth-checker.ts"; | ||
|
||
const schema = await buildSchema({ | ||
resolvers: [MyResolver], | ||
// Register the auth checking function | ||
// or defining it inline | ||
authChecker: customAuthChecker, | ||
}); | ||
``` | ||
|
||
And it's done! 😉 | ||
|
||
If we need silent auth guards and don't want to return authorization errors to users, we can set the `authMode` property of the `buildSchema` config object to `"null"`: | ||
|
||
```ts | ||
const schema = await buildSchema({ | ||
resolvers: ["./**/*.resolver.ts"], | ||
authChecker: customAuthChecker, | ||
authMode: "null", | ||
}); | ||
``` | ||
|
||
It will then return `null` instead of throwing an authorization error. | ||
|
||
## Recipes | ||
|
||
We can also use `TypeGraphQL` with JWT authentication. | ||
Here's an example using `@apollo/server`: | ||
|
||
```ts | ||
import { ApolloServer } from "@apollo/server"; | ||
import { expressMiddleware } from "@apollo/server/express4"; | ||
import express from "express"; | ||
import jwt from "express-jwt"; | ||
import bodyParser from "body-parser"; | ||
import { schema } from "./graphql/schema"; | ||
import { User } from "./User.type"; | ||
|
||
// GraphQL path | ||
const GRAPHQL_PATH = "/graphql"; | ||
|
||
// GraphQL context | ||
type Context = { | ||
user?: User; | ||
}; | ||
|
||
// Express | ||
const app = express(); | ||
|
||
// Apollo server | ||
const server = new ApolloServer<Context>({ schema }); | ||
await server.start(); | ||
|
||
// Mount a JWT or other authentication middleware that is run before the GraphQL execution | ||
app.use( | ||
GRAPHQL_PATH, | ||
jwt({ | ||
secret: "TypeGraphQL", | ||
credentialsRequired: false, | ||
}), | ||
); | ||
|
||
// Apply GraphQL server middleware | ||
app.use( | ||
GRAPHQL_PATH, | ||
bodyParser.json(), | ||
expressMiddleware(server, { | ||
// Build context | ||
// 'req.user' comes from 'express-jwt' | ||
context: async ({ req }) => ({ user: req.user }), | ||
}), | ||
); | ||
|
||
// Start server | ||
await new Promise<void>(resolve => app.listen({ port: 4000 }, resolve)); | ||
console.log(`GraphQL server ready at http://localhost:4000/${GRAPHQL_PATH}`); | ||
``` | ||
|
||
Then we can use standard, token based authorization in the HTTP header like in classic REST APIs and take advantage of the `TypeGraphQL` authorization mechanism. | ||
|
||
## Example | ||
|
||
See how this works in the [simple real life example](https://github.com/MichalLytek/type-graphql/tree/v2.0.0-beta.3/examples/authorization). |
143 changes: 143 additions & 0 deletions
143
website/versioned_docs/version-2.0.0-beta.3/bootstrap.md
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,143 @@ | ||
--- | ||
title: Bootstrapping | ||
id: version-2.0.0-beta.3-bootstrap | ||
original_id: bootstrap | ||
--- | ||
|
||
After creating our resolvers, type classes, and other business-related code, we need to make our app run. First we have to build the schema, then we can expose it with an HTTP server, WebSockets or even MQTT. | ||
|
||
## Create Executable Schema | ||
|
||
To create an executable schema from type and resolver definitions, we need to use the `buildSchema` function. | ||
It takes a configuration object as a parameter and returns a promise of a `GraphQLSchema` object. | ||
|
||
In the configuration object we must provide a `resolvers` property, which is supposed to be an array of resolver classes: | ||
|
||
```ts | ||
import { FirstResolver, SecondResolver } from "./resolvers"; | ||
// ... | ||
const schema = await buildSchema({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
}); | ||
``` | ||
|
||
Be aware that only operations (queries, mutation, etc.) defined in the resolvers classes (and types directly connected to them) will be emitted in schema. | ||
|
||
So if we have defined some object types (that implements an interface type [with disabled auto registering](./interfaces.md#registering-in-schema)) but are not directly used in other types definition (like a part of an union, a type of a field or a return type of an operation), we need to provide them manually in `orphanedTypes` options of `buildSchema`: | ||
|
||
```ts | ||
import { FirstResolver, SecondResolver } from "../app/src/resolvers"; | ||
import { FirstObject } from "../app/src/types"; | ||
// ... | ||
const schema = await buildSchema({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
// Provide all the types that are missing in schema | ||
orphanedTypes: [FirstObject], | ||
}); | ||
``` | ||
|
||
In case of defining the resolvers array somewhere else (not inline in the `buildSchema`), we need to use the `as const` syntax to inform the TS compiler and satisfy the `NonEmptyArray<T>` constraints: | ||
|
||
```ts | ||
// resolvers.ts | ||
export const resolvers = [FirstResolver, SecondResolver] as const; | ||
|
||
// schema.ts | ||
import { resolvers } from "./resolvers"; | ||
|
||
const schema = await buildSchema({ resolvers }); | ||
``` | ||
|
||
There are also other options related to advanced features like [authorization](./authorization.md) or [validation](./validation.md) - you can read about them in docs. | ||
|
||
To make `await` work, we need to declare it as an async function. Example of `main.ts` file: | ||
|
||
```ts | ||
import { buildSchema } from "type-graphql"; | ||
|
||
async function bootstrap() { | ||
const schema = await buildSchema({ | ||
resolvers: [ | ||
// ... Resolvers classes | ||
], | ||
}); | ||
|
||
// ... | ||
} | ||
|
||
bootstrap(); // Actually run the async function | ||
``` | ||
|
||
## Create an HTTP GraphQL endpoint | ||
|
||
In most cases, the GraphQL app is served by an HTTP server. After building the schema we can create the GraphQL endpoint with a variety of tools such as [`graphql-yoga`](https://github.com/dotansimha/graphql-yoga) or [`@apollo/server`](https://github.com/apollographql/apollo-server). | ||
|
||
Below is an example using [`@apollo/server`](https://github.com/apollographql/apollo-server): | ||
|
||
```ts | ||
import { ApolloServer } from "@apollo/server"; | ||
import { startStandaloneServer } from "@apollo/server/standalone"; | ||
|
||
const PORT = process.env.PORT || 4000; | ||
|
||
async function bootstrap() { | ||
// ... Build GraphQL schema | ||
|
||
// Create GraphQL server | ||
const server = new ApolloServer({ schema }); | ||
|
||
// Start server | ||
const { url } = await startStandaloneServer(server, { listen: { port: 4000 } }); | ||
console.log(`GraphQL server ready at ${url}`); | ||
} | ||
|
||
bootstrap(); | ||
``` | ||
|
||
Remember to install the `@apollo/server` package from npm - it's not bundled with TypeGraphQL. | ||
|
||
Of course you can use the `express-graphql` middleware, `graphql-yoga` or whatever you want 😉 | ||
|
||
## Create typeDefs and resolvers map | ||
|
||
TypeGraphQL provides a second way to generate the GraphQL schema - the `buildTypeDefsAndResolvers` function. | ||
|
||
It accepts the same `BuildSchemaOptions` as the `buildSchema` function but instead of an executable `GraphQLSchema`, it creates a typeDefs and resolversMap pair that you can use e.g. with [@graphql-tools/\*`](https://the-guild.dev/graphql/tools): | ||
|
||
```ts | ||
import { makeExecutableSchema } from "@graphql-tools/schema"; | ||
|
||
const { typeDefs, resolvers } = await buildTypeDefsAndResolvers({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
}); | ||
|
||
const schema = makeExecutableSchema({ typeDefs, resolvers }); | ||
``` | ||
|
||
Or even with other libraries that expect the schema info in that shape, like [`apollo-link-state`](https://github.com/apollographql/apollo-link-state): | ||
|
||
```ts | ||
import { withClientState } from "apollo-link-state"; | ||
|
||
const { typeDefs, resolvers } = await buildTypeDefsAndResolvers({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
}); | ||
|
||
const stateLink = withClientState({ | ||
// ... Other options like `cache` | ||
typeDefs, | ||
resolvers, | ||
}); | ||
|
||
// ... Rest of `ApolloClient` initialization code | ||
``` | ||
|
||
There's also a `sync` version of it - `buildTypeDefsAndResolversSync`: | ||
|
||
```ts | ||
const { typeDefs, resolvers } = buildTypeDefsAndResolversSync({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
}); | ||
``` | ||
|
||
However, be aware that some of the TypeGraphQL features (i.a. [query complexity](./complexity.md)) might not work with the `buildTypeDefsAndResolvers` approach because they use some low-level `graphql-js` features. |
Oops, something went wrong.