-
-
Notifications
You must be signed in to change notification settings - Fork 677
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
efe5371
commit 37a2d10
Showing
27 changed files
with
2,751 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,165 @@ | ||
--- | ||
title: Authorization | ||
id: version-0.17.0-authorization | ||
original_id: authorization | ||
--- | ||
|
||
Authorization is a core feature used in almost all APIs. Sometimes we want to restrict access to some actions or reading some data only for specific group of users. | ||
|
||
In express.js (and other Node.js framework) we use middlewares for this, like `passport.js` or the custom ones. However in GraphQL's resolvers architecture we don't have middlewares so we have to imperatively call the auth checking function and manually passing context data in each resolver, which might be quite tedious work. | ||
|
||
And that's why authorization is a first-class feature in `TypeGraphQL`! | ||
|
||
## How to use? | ||
|
||
At first, you need to use `@Authorized` decorator as a guard on a field or a query/mutation. | ||
Example object type's fields 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; | ||
} | ||
``` | ||
|
||
You can leave the `@Authorized` decorator brackets empty or you can specify the roles that the user needs to have to get access to the field, query or mutation. | ||
By default the roles are `string` but you can change it easily as the decorator is generic - `@Authorized<number>(1, 7, 22)`. | ||
|
||
This way authed users (regardless of theirs roles) could read only `publicField` or `authorizedField` from `MyObject` object. They will receive `null` when accessing `hiddenField` field and will receive error (that will propagate through the whole query tree looking for nullable field) for `adminField` when they don't satisfy roles constraints. | ||
|
||
Sample query and mutations guards: | ||
|
||
```typescript | ||
@Resolver() | ||
class MyResolver { | ||
@Query() | ||
publicQuery(): MyObject { | ||
return { | ||
publicField: "Some public data", | ||
authorizedField: "Data only for logged users", | ||
adminField: "Top secret info for admin", | ||
}; | ||
} | ||
|
||
@Authorized() | ||
@Query() | ||
authedQuery(): string { | ||
return "Only for authed users!"; | ||
} | ||
|
||
@Authorized("ADMIN", "MODERATOR") | ||
@Mutation() | ||
adminMutation(): string { | ||
return "You are an admin/moderator, you can safely drop database ;)"; | ||
} | ||
} | ||
``` | ||
|
||
Authed users (regardless of theirs roles) will be able to read data from `publicQuery` and `authedQuery` but will receive error trying to perform `adminMutation` when their roles doesn't include `ADMIN` or `MODERATOR`. | ||
|
||
In next step, you need to create your auth checker function. Its implementation may depends on your business logic: | ||
|
||
```typescript | ||
export const customAuthChecker: AuthChecker<ContextType> = ( | ||
{ root, args, context, info }, | ||
roles, | ||
) => { | ||
// here you can read user from context | ||
// and check his permission in db against `roles` argument | ||
// that comes from `@Authorized`, eg. ["ADMIN", "MODERATOR"] | ||
|
||
return true; // or false if access denied | ||
}; | ||
``` | ||
|
||
The second argument of `AuthChecker` generic type is `RoleType` - use it together with `@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 you need silent auth guards and you don't want to return auth errors to users, you can set `authMode` property of `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 authorization error. | ||
|
||
## Recipes | ||
|
||
You can also use `TypeGraphQL` with JWT authentication. 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 you can use standard, token based authorization in HTTP header like in classic REST API and take advantages of `TypeGraphQL` authorization mechanism. | ||
|
||
## Example | ||
|
||
You can see how this works together 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.0-bootstrap | ||
original_id: bootstrap | ||
--- | ||
|
||
After creating our resolvers, types 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 by HTTP server, WebSockets or even MQTT. | ||
|
||
## Create Executable Schema | ||
|
||
To create an executable schema from type and resolver definitions, you 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 dozen of resolver classes, manual imports can be tedious. | ||
So you 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 HTTP GraphQL endpoint | ||
|
||
In most cases, the GraphQL app is served by a 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 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 `apollo-server` package from npm - it's not bundled with TypeGraphQL. | ||
|
||
Of course you can use `express-graphql` middleware, `graphql-yoga` or whatever you want 😉 | ||
|
||
## Create typeDefs and resolvers map | ||
|
||
TypeGraphQL also provides a second way to generate the GraphQL schema - the `buildTypeDefsAndResolvers` function. | ||
|
||
It accepts the same `BuildSchemaOptions` like 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 `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.0-browser-usage | ||
original_id: browser-usage | ||
--- | ||
|
||
## Using classes in client app | ||
|
||
Sometimes you might want to use the classes, that you've created and annotated with TypeGraphQL decorators, in your client app that works in browser. For example, you may want to reuse the args or input classes with `class-validator` decorators or the object type classes with some helpful custom methods. | ||
|
||
As TypeGraphQL is a Node.js framework, it doesn't work in browser environment, so you may quickly got an error, e.g. `ERROR in ./node_modules/fs.realpath/index.js`, while trying to build your app with Webpack. To fix that, you have to configure Webpack to use the decorators shim instead of normal module. All you need is to add this plugin code to your webpack config: | ||
|
||
```js | ||
plugins: [ | ||
// ...here are any other existing plugins that you already have | ||
new webpack.NormalModuleReplacementPlugin(/type-graphql$/, resource => { | ||
resource.request = resource.request.replace(/type-graphql/, "type-graphql/dist/browser-shim"); | ||
}), | ||
]; | ||
``` | ||
|
||
Also, thanks to this your bundle will be much lighter as you don't embedded the whole TypeGraphQL library code in your app. |
Oops, something went wrong.