-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: 🚧 add verifyied as custom directive to api
Signed-off-by: Manuel Ruck <[email protected]>
- Loading branch information
Manuel Ruck
committed
Jul 15, 2024
1 parent
9048e2a
commit 2f1d2ce
Showing
3 changed files
with
77 additions
and
4 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
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,50 @@ | ||
import { defaultFieldResolver, GraphQLSchema } from 'graphql'; | ||
import { getDirective, MapperKind, mapSchema } from '@graphql-tools/utils'; | ||
|
||
export const authDirective = ( | ||
directiveName: string, | ||
getUserFn: (token: string) => { hasRole: (role: string) => boolean }, | ||
) => { | ||
const typeDirectiveArgumentMaps: Record<string, any> = {}; | ||
return { | ||
authDirectiveTypeDefs: `directive @${directiveName}( | ||
requires: Role = ADMIN, | ||
) on OBJECT | FIELD_DEFINITION | ||
enum Role { | ||
ADMIN | ||
REVIEWER | ||
USER | ||
UNKNOWN | ||
}`, | ||
authDirectiveTransformer: (schema: GraphQLSchema) => | ||
mapSchema(schema, { | ||
[MapperKind.TYPE]: (type) => { | ||
const authDirective = getDirective(schema, type, directiveName)?.[0]; | ||
if (authDirective) { | ||
typeDirectiveArgumentMaps[type.name] = authDirective; | ||
} | ||
return undefined; | ||
}, | ||
[MapperKind.OBJECT_FIELD]: (fieldConfig, _fieldName, typeName) => { | ||
const authDirective = | ||
getDirective(schema, fieldConfig, directiveName)?.[0] ?? | ||
typeDirectiveArgumentMaps[typeName]; | ||
if (authDirective) { | ||
const { requires } = authDirective; | ||
if (requires) { | ||
const { resolve = defaultFieldResolver } = fieldConfig; | ||
fieldConfig.resolve = function (source, args, context, info) { | ||
const user = getUserFn(context.headers.authToken); | ||
if (!user.hasRole(requires)) { | ||
throw new Error('not authorized'); | ||
} | ||
return resolve(source, args, context, info); | ||
}; | ||
return fieldConfig; | ||
} | ||
} | ||
}, | ||
}), | ||
}; | ||
}; |
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