Skip to content

Commit

Permalink
release: 2.0.0-rc.2
Browse files Browse the repository at this point in the history
  • Loading branch information
MichalLytek committed Jun 7, 2024
1 parent 0ac4077 commit c4913f6
Show file tree
Hide file tree
Showing 22 changed files with 2,877 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.2

## Features

- support declaring middlewares on resolver class level (#620)
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-rc.1",
"version": "2.0.0-rc.2",
"private": false,
"description": "Create GraphQL schema and resolvers with TypeScript, using classes and decorators!",
"keywords": [
Expand Down
50 changes: 50 additions & 0 deletions website/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,56 @@
"version-2.0.0-rc.1/version-2.0.0-rc.1-validation": {
"title": "Argument and Input validation",
"sidebar_label": "Validation"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-authorization": {
"title": "Authorization"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-azure-functions": {
"title": "Azure Functions Integration"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-browser-usage": {
"title": "Browser usage"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-complexity": {
"title": "Query complexity"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-custom-decorators": {
"title": "Custom decorators"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-dependency-injection": {
"title": "Dependency injection"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-examples": {
"title": "Examples",
"sidebar_label": "List of examples"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-extensions": {
"title": "Extensions"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-generic-types": {
"title": "Generic Types"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-inheritance": {
"title": "Inheritance"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-interfaces": {
"title": "Interfaces"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-middlewares": {
"title": "Middleware and guards"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-resolvers": {
"title": "Resolvers"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-subscriptions": {
"title": "Subscriptions"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-unions": {
"title": "Unions"
},
"version-2.0.0-rc.2/version-2.0.0-rc.2-validation": {
"title": "Argument and Input validation",
"sidebar_label": "Validation"
}
},
"links": {
Expand Down
220 changes: 220 additions & 0 deletions website/versioned_docs/version-2.0.0-rc.2/authorization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
---
title: Authorization
id: version-2.0.0-rc.2-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`!

## Declaration

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`.

However, declaring `@Authorized()` on all the resolver's class methods would be not only a tedious task but also an error-prone one, as it's easy to forget to put it on some newly added method, etc.
Hence, TypeGraphQL support declaring `@Authorized()` or the resolver class level. This way you can declare it once per resolver's class but you can still overwrite the defaults and narrows the authorization rules:

```ts
@Authorized()
@Resolver()
class MyResolver {
// this will inherit the auth guard defined on the class level
@Query()
authedQuery(): string {
return "Authorized users only!";
}

// this one overwrites the resolver's one
// and registers roles required for this mutation
@Authorized("ADMIN", "MODERATOR")
@Mutation()
adminMutation(): string {
return "You are an admin/moderator, you can safely drop the database ;)";
}
}
```

## Runtime checks

Having all the metadata for authorization set, 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.2/examples/authorization).
Loading

0 comments on commit c4913f6

Please sign in to comment.