Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authorization #23

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions examples/ghost/src/data-sources/AuthSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Context } from "./Context";

export class AuthSource {
constructor(protected ctx: Context) {}

async canViewPost(id: string): Promise<boolean> {
const post = await this.ctx.post.byId(id);
if (post.status === "published") {
return true;
}
return false;
}

async canViewUser(id: string): Promise<boolean> {
return true;
}
}
2 changes: 2 additions & 0 deletions examples/ghost/src/data-sources/Context.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { PostSource } from "./PostSource";
import { UserSource } from "./UserSource";
import { AuthSource } from "./AuthSource";
import { knex } from "../utils/knexInstance";

export class Context {
auth = new AuthSource(this);
post = new PostSource(this);
user = new UserSource(this);

Expand Down
16 changes: 15 additions & 1 deletion examples/ghost/src/data-sources/PostSource.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
import DataLoader from "dataloader";
import { Context } from "./Context";
import { dbt } from "../generated";
import { byColumnLoader } from "../utils/loaderUtils";
import { byColumnLoader, manyByColumnLoader } from "../utils/loaderUtils";

export class PostSource {
constructor(protected ctx: Context) {}

authorIdsLoader = new DataLoader<string, dbt.PostsAuthors[]>((ids) => {
return manyByColumnLoader(this.ctx, "postsAuthors", "postId", ids);
});

byIdLoader = new DataLoader<string, dbt.Posts>((ids) => {
return byColumnLoader(this.ctx, "posts", "id", ids);
});

byId(id: string) {
return this.byIdLoader.load(id);
}

async authorIds(postId: string) {
const result = await this.authorIdsLoader.load(postId);
return result.map(({ authorId }) => authorId);
}

async authors(postId: string) {
const authorIds = await this.authorIds(postId);
return this.ctx.user.byIdLoader.loadMany(authorIds);
}
}
2 changes: 2 additions & 0 deletions examples/ghost/src/schema/Query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ export const Query = queryType({
t.field("postById", {
type: Post,
args: { id: idArg() },
authorize: (root, args, ctx) => ctx.auth.canViewPost(args.id),
resolve(root, args, ctx) {
return ctx.post.byId(args.id);
},
});
t.field("userById", {
type: User,
args: { id: idArg() },
authorize: (root, args, ctx) => ctx.auth.canViewUser(args.id),
resolve(root, args, ctx) {
return ctx.user.byId(args.id);
},
Expand Down
30 changes: 30 additions & 0 deletions examples/ghost/src/utils/loaderUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import _ from "lodash";
import { DBTables } from "../generated/ghost-db-tables";
import { Context } from "../data-sources/Context";
import { QueryBuilder } from "knex";

export function byColumnLoader<
Tbl extends keyof DBTables,
Expand All @@ -23,3 +24,32 @@ export function byColumnLoader<
});
});
}

/**
* A type-safe loader for loading many of a particular item,
* grouped by an individual key.
* @param ctx
* @param table
* @param key
* @param keys
*/
export function manyByColumnLoader<
Tbl extends keyof DBTables,
Key extends Extract<keyof DBTables[Tbl], string>,
KeyType extends Extract<DBTables[Tbl][Key], string | number>
>(
ctx: Context,
tableName: Tbl,
key: Key,
keys: KeyType[],
scope: (qb: QueryBuilder) => QueryBuilder = (qb) => qb
) {
const builder = ctx
.knex(tableName)
.select(`${tableName}.*`)
.whereIn(`${tableName}.${key}`, _.uniq(keys));
return scope(builder).then((rows: DBTables[Tbl][]) => {
const grouped = _.groupBy(rows, key);
return keys.map((id) => grouped[id] || []);
});
}
47 changes: 43 additions & 4 deletions src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
isOutputType,
isUnionType,
isScalarType,
defaultFieldResolver,
} from "graphql";
import { NexusArgConfig, NexusArgDef } from "./definitions/args";
import {
Expand Down Expand Up @@ -81,11 +82,16 @@ import {
GraphQLPossibleInputs,
GraphQLPossibleOutputs,
NonNullConfig,
WrappedResolver,
} from "./definitions/_types";
import { TypegenAutoConfigOptions } from "./typegenAutoConfig";
import { TypegenFormatFn } from "./typegenFormatPrettier";
import { TypegenMetadata } from "./typegenMetadata";
import { AbstractTypeResolver, GetGen } from "./typegenTypeHelpers";
import {
AbstractTypeResolver,
GetGen,
AuthorizeResolver,
} from "./typegenTypeHelpers";
import { firstDefined, objValues, suggestionList, isObject } from "./utils";

export type Maybe<T> = T | null;
Expand Down Expand Up @@ -506,9 +512,9 @@ export class SchemaBuilder {
return type;
}

protected withScalarMethods<T extends NexusGenCustomDefinitionMethods<string>>(
definitionBlock: T
): T {
protected withScalarMethods<
T extends NexusGenCustomDefinitionMethods<string>
>(definitionBlock: T): T {
this.customScalarMethods.forEach(([methodName, typeName]) => {
// @ts-ignore - Yeah, yeah... we know
definitionBlock[methodName] = function(fieldName, ...opts) {
Expand Down Expand Up @@ -888,6 +894,12 @@ export class SchemaBuilder {
if (!resolver && !forInterface) {
resolver = (typeConfig as NexusObjectTypeConfig<any>).defaultResolver;
}
if (fieldOptions.authorize) {
resolver = wrapAuthorize(
resolver || defaultFieldResolver,
fieldOptions.authorize
);
}
return resolver;
}

Expand All @@ -909,6 +921,33 @@ function extendError(name: string) {
);
}

export function wrapAuthorize(
resolver: GraphQLFieldResolver<any, any>,
authorize: AuthorizeResolver<string, any>
): GraphQLFieldResolver<any, any> {
const nexusAuthWrapped: WrappedResolver = async (root, args, ctx, info) => {
const authResult = await authorize(root, args, ctx, info);
if (authResult === true) {
return resolver(root, args, ctx, info);
}
if (authResult === false) {
throw new Error("Not authorized");
}
if (authResult instanceof Error) {
throw authResult;
}
const {
fieldName,
parentType: { name: parentTypeName },
} = info;
throw new Error(
`Nexus authorize for ${parentTypeName}.${fieldName} Expected a boolean or Error, saw ${authResult}`
);
};
nexusAuthWrapped.nexusWrappedResolver = resolver;
return nexusAuthWrapped;
}

export interface BuildTypes<
TypeMapDefs extends Record<string, GraphQLNamedType>
> {
Expand Down
5 changes: 5 additions & 0 deletions src/definitions/_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@ import {
GraphQLLeafType,
GraphQLCompositeType,
GraphQLInputObjectType,
GraphQLFieldResolver,
} from "graphql";

export type WrappedResolver = GraphQLFieldResolver<any, any> & {
nexusWrappedResolver?: GraphQLFieldResolver<any, any>;
};

export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

export type BaseScalars = "String" | "Int" | "Float" | "ID" | "Boolean";
Expand Down
10 changes: 10 additions & 0 deletions src/definitions/definitionBlocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
GetGen,
HasGen3,
NeedsResolver,
AuthorizeResolver,
} from "../typegenTypeHelpers";
import { NexusArgDef } from "./args";
import {
Expand Down Expand Up @@ -52,6 +53,15 @@ export interface OutputScalarConfig<
* Resolve method for the field
*/
resolve?: FieldResolver<TypeName, FieldName>;
/**
* Authorization for an individual field. Returning "true"
* or "Promise<true>" means the field can be accessed.
* Returning "false" or "Promise<false>" will respond
* with a "Not Authorized" error for the field. Returning
* or throwing an error will also prevent the resolver from
* executing.
*/
authorize?: AuthorizeResolver<TypeName, FieldName>;
}

export interface NexusOutputFieldConfig<
Expand Down
1 change: 0 additions & 1 deletion src/definitions/objectType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ export interface NexusObjectTypeConfig<TypeName extends string> {
description?: string | null;
/**
* Specifies a default field resolver for all members of this type.
* Warning: this may break type-safety.
*/
defaultResolver?: FieldResolver<TypeName, any>;
}
Expand Down
11 changes: 9 additions & 2 deletions src/typegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ import {
isUnionType,
GraphQLInputObjectType,
GraphQLEnumType,
defaultFieldResolver,
} from "graphql";
import { TypegenInfo } from "./builder";
import { eachObj, GroupedTypes, groupTypes, mapObj } from "./utils";
import { WrappedResolver } from "./definitions/_types";

const SpecifiedScalars = {
ID: "string",
Expand Down Expand Up @@ -344,10 +346,15 @@ export class Typegen {
}

hasResolver(
field: GraphQLField<any, any>,
field: GraphQLField<any, any> & { resolve?: WrappedResolver },
_type: GraphQLObjectType | GraphQLInterfaceType // Used in tests
) {
return Boolean(field.resolve);
if (field.resolve) {
if (field.resolve.nexusWrappedResolver !== defaultFieldResolver) {
return true;
}
}
return false;
}

printRootTypeMap() {
Expand Down
10 changes: 10 additions & 0 deletions src/typegenTypeHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@ export type FieldResolver<TypeName extends string, FieldName extends string> = (
info: GraphQLResolveInfo
) => MaybePromiseDeep<ResultValue<TypeName, FieldName>>;

export type AuthorizeResolver<
TypeName extends string,
FieldName extends string
> = (
root: RootValue<TypeName>,
args: ArgsValue<TypeName, FieldName>,
context: GetGen<"context">,
info: GraphQLResolveInfo
) => MaybePromise<boolean | Error>;

export type AbstractResolveReturn<
TypeName extends string
> = NexusGen extends infer GenTypes
Expand Down