-
-
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
8a31741
commit f8b85e3
Showing
26 changed files
with
2,723 additions
and
6 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
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,166 @@ | ||
--- | ||
title: Authorization | ||
id: version-0.17.1-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: | ||
|
||
```typescript | ||
@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: | ||
|
||
```typescript | ||
@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: | ||
|
||
```typescript | ||
export const customAuthChecker: AuthChecker<ContextType> = ( | ||
{ root, args, context, info }, | ||
roles, | ||
) => { | ||
// here we can read the user from context | ||
// and check his permission in the db 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. | ||
|
||
The last step is to register the function while building the schema: | ||
|
||
```typescript | ||
import { customAuthChecker } from "../auth/custom-auth-checker.ts"; | ||
|
||
const schema = await buildSchema({ | ||
resolvers: [MyResolver], | ||
// here we 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"`: | ||
|
||
```typescript | ||
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-express`: | ||
|
||
```typescript | ||
import express from "express"; | ||
import { ApolloServer, gql } from "apollo-server-express"; | ||
import * as jwt from "express-jwt"; | ||
|
||
import { schema } from "../example/above"; | ||
|
||
const app = express(); | ||
const path = "/graphql"; | ||
|
||
// Create a GraphQL server | ||
const server = new ApolloServer({ | ||
schema, | ||
context: ({ req }) => { | ||
const context = { | ||
req, | ||
user: req.user, // `req.user` comes from `express-jwt` | ||
}; | ||
return context; | ||
}, | ||
}); | ||
|
||
// Mount a jwt or other authentication middleware that is run before the GraphQL execution | ||
app.use( | ||
path, | ||
jwt({ | ||
secret: "TypeGraphQL", | ||
credentialsRequired: false, | ||
}), | ||
); | ||
|
||
// Apply the GraphQL server middleware | ||
server.applyMiddleware({ app, path }); | ||
|
||
// Launch the express server | ||
app.listen({ port: 4000 }, () => | ||
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`), | ||
); | ||
``` | ||
|
||
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/19majkel94/type-graphql/tree/master/examples/authorization). |
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,115 @@ | ||
--- | ||
title: Bootstrapping | ||
id: version-0.17.1-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 you must provide a `resolvers` property, which can be an array of resolver classes: | ||
|
||
```typescript | ||
import { FirstResolver, SecondResolver } from "../app/src/resolvers"; | ||
// ... | ||
const schema = await buildSchema({ | ||
resolvers: [FirstResolver, SampleResolver], | ||
}); | ||
``` | ||
|
||
However, when there are several resolver classes, manual imports can be cumbersome. | ||
So we can also provide an array of paths to resolver module files instead, which can include globs: | ||
|
||
```typescript | ||
const schema = await buildSchema({ | ||
resolvers: [__dirname + "/modules/**/*.resolver.ts", __dirname + "/resolvers/**/*.ts"], | ||
}); | ||
``` | ||
|
||
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: | ||
|
||
```typescript | ||
import { buildSchema } from "type-graphql"; | ||
|
||
async function bootstrap() { | ||
const schema = await buildSchema({ | ||
resolvers: [__dirname + "/**/*.resolver.ts"], | ||
}); | ||
|
||
// other initialization code, like creating http server | ||
} | ||
|
||
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/prisma/graphql-yoga) or [`apollo-server`](https://github.com/apollographql/apollo-server). Here is an example using [`apollo-server`](https://github.com/apollographql/apollo-server): | ||
|
||
```typescript | ||
import { ApolloServer } from "apollo-server"; | ||
|
||
const PORT = process.env.PORT || 4000; | ||
|
||
async function bootstrap() { | ||
// ... Building schema here | ||
|
||
// Create the GraphQL server | ||
const server = new ApolloServer({ | ||
schema, | ||
playground: true, | ||
}); | ||
|
||
// Start the server | ||
const { url } = await server.listen(PORT); | ||
console.log(`Server is running, GraphQL Playground available 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://github.com/apollographql/graphql-tools): | ||
|
||
```typescript | ||
import { makeExecutableSchema } from "graphql-tools"; | ||
|
||
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): | ||
|
||
```typescript | ||
import { withClientState } from "apollo-link-state"; | ||
|
||
const { typeDefs, resolvers } = await buildTypeDefsAndResolvers({ | ||
resolvers: [FirstResolver, SecondResolver], | ||
}); | ||
|
||
const stateLink = withClientState({ | ||
// ...other options like `cache` | ||
typeDefs, | ||
resolvers, | ||
}); | ||
|
||
// ...the rest of `ApolloClient` initialization code | ||
``` | ||
|
||
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. |
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,22 @@ | ||
--- | ||
title: Browser usage | ||
id: version-0.17.1-browser-usage | ||
original_id: browser-usage | ||
--- | ||
|
||
## Using classes in a client app | ||
|
||
Sometimes we might want to use the classes we've created and annotated with TypeGraphQL decorators, in our client app that works in the browser. For example, reusing the args or input classes with `class-validator` decorators or the object type classes with some helpful custom methods. | ||
|
||
Since TypeGraphQL is a Node.js framework, it doesn't work in a browser environment, so we may quickly get an error, e.g. `ERROR in ./node_modules/fs.realpath/index.js`, while trying to build our app with Webpack. To correct this, we have to configure Webpack to use the decorator shim instead of the normal module. We simply add this plugin code to our webpack config: | ||
|
||
```js | ||
plugins: [ | ||
// ...here are any other existing plugins that we already have | ||
new webpack.NormalModuleReplacementPlugin(/type-graphql$/, resource => { | ||
resource.request = resource.request.replace(/type-graphql/, "type-graphql/dist/browser-shim"); | ||
}), | ||
]; | ||
``` | ||
|
||
Thanks to this, our bundle will be much lighter as we don't need to embed the whole TypeGraphQL library code in our app. |
Oops, something went wrong.