Skip to content

Commit

Permalink
release: 2.0.0-rc.1
Browse files Browse the repository at this point in the history
  • Loading branch information
MichalLytek committed Apr 24, 2024
1 parent 5690981 commit 4a7aa2d
Show file tree
Hide file tree
Showing 20 changed files with 2,628 additions and 4 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# Changelog and release notes

## Unreleased
<!-- ## Unreleased -->

<!-- Here goes all the unreleased changes descriptions -->

## v2.0.0-rc.1

## Features

- support other `Reflect` polyfills than `reflect-metadata` by checking only used `Reflect` API (#1102)
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "type-graphql",
"version": "2.0.0-beta.6",
"version": "2.0.0-rc.1",
"private": false,
"description": "Create GraphQL schema and resolvers with TypeScript, using classes and decorators!",
"keywords": [
Expand Down
195 changes: 195 additions & 0 deletions website/versioned_docs/version-2.0.0-rc.1/authorization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
---
title: Authorization
id: version-2.0.0-rc.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:

```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-rc.1/examples/authorization).
103 changes: 103 additions & 0 deletions website/versioned_docs/version-2.0.0-rc.1/complexity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
---
title: Query complexity
id: version-2.0.0-rc.1-complexity
original_id: complexity
---

A single GraphQL query can potentially generate a huge workload for a server, like thousands of database operations which can be used to cause DDoS attacks. In order to limit and keep track of what each GraphQL operation can do, `TypeGraphQL` provides the option of integrating with Query Complexity tools like [graphql-query-complexity](https://github.com/ivome/graphql-query-complexity).

This cost analysis-based solution is very promising, since we can define a “cost” per field and then analyze the AST to estimate the total cost of the GraphQL query. Of course all the analysis is handled by `graphql-query-complexity`.

All we must do is define our complexity cost for the fields, mutations or subscriptions in `TypeGraphQL` and implement `graphql-query-complexity` in whatever GraphQL server that is being used.

## How to use

First, we need to pass `complexity` as an option to the decorator on a field, query or mutation.

Example of complexity

```ts
@ObjectType()
class MyObject {
@Field({ complexity: 2 })
publicField: string;

@Field({ complexity: ({ args, childComplexity }) => childComplexity + 1 })
complexField: string;
}
```

The `complexity` option may be omitted if the complexity value is 1.
Complexity can be passed as an option to any `@Field`, `@FieldResolver`, `@Mutation` or `@Subscription` decorator. If both `@FieldResolver` and `@Field` decorators of the same property have complexity defined, then the complexity passed to the field resolver decorator takes precedence.

In the next step, we will integrate `graphql-query-complexity` with the server that expose our GraphQL schema over HTTP.
You can use it with `express-graphql` like [in the lib examples](https://github.com/slicknode/graphql-query-complexity/blob/b6a000c0984f7391f3b4e886e3df6a7ed1093b07/README.md#usage-with-express-graphql), however we will use Apollo Server like in our other examples:

```ts
async function bootstrap() {
// ... Build GraphQL schema

// Create GraphQL server
const server = new ApolloServer({
schema,
// Create a plugin to allow query complexity calculation for every request
plugins: [
{
requestDidStart: async () => ({
async didResolveOperation({ request, document }) {
/**
* Provides GraphQL query analysis to be able to react on complex queries to the GraphQL server
* It can be used to protect the GraphQL server against resource exhaustion and DoS attacks
* More documentation can be found at https://github.com/ivome/graphql-query-complexity
*/
const complexity = getComplexity({
// GraphQL schema
schema,
// To calculate query complexity properly,
// check only the requested operation
// not the whole document that may contains multiple operations
operationName: request.operationName,
// GraphQL query document
query: document,
// GraphQL query variables
variables: request.variables,
// Add any number of estimators. The estimators are invoked in order, the first
// numeric value that is being returned by an estimator is used as the field complexity
// If no estimator returns a value, an exception is raised
estimators: [
// Using fieldExtensionsEstimator is mandatory to make it work with type-graphql
fieldExtensionsEstimator(),
// Add more estimators here...
// This will assign each field a complexity of 1
// if no other estimator returned a value
simpleEstimator({ defaultComplexity: 1 }),
],
});

// React to the calculated complexity,
// like compare it with max and throw error when the threshold is reached
if (complexity > MAX_COMPLEXITY) {
throw new Error(
`Sorry, too complicated query! ${complexity} exceeded the maximum allowed complexity of ${MAX_COMPLEXITY}`,
);
}
console.log("Used query complexity points:", complexity);
},
}),
},
],
});

// Start server
const { url } = await startStandaloneServer(server, { listen: { port: 4000 } });
console.log(`GraphQL server ready at ${url}`);
}
```

And it's done! 😉

For more info about how query complexity is computed, please visit [graphql-query-complexity](https://github.com/ivome/graphql-query-complexity).

## Example

See how this works in the [simple query complexity example](https://github.com/MichalLytek/type-graphql/tree/v2.0.0-rc.1/examples/query-complexity).
Loading

0 comments on commit 4a7aa2d

Please sign in to comment.