forked from nestjsx/nest-access-control
-
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.
feat(decorator): add support for graphql in user roles decorator
- Loading branch information
Showing
6 changed files
with
16,121 additions
and
6,422 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,36 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const common_1 = require("@nestjs/common"); | ||
const graphql_1 = require("@nestjs/graphql"); | ||
function userFactory(ctx) { | ||
const contextType = ctx.getType(); | ||
if (contextType === 'http') { | ||
// do something that is only important in the context of regular HTTP requests (REST) | ||
const { user } = ctx.switchToHttp().getRequest(); | ||
return user; | ||
} | ||
else if (contextType === 'rpc') { | ||
// do something that is only important in the context of Microservice requests | ||
throw new Error('Rpc context is not implemented yet'); | ||
} | ||
else if (contextType === 'ws') { | ||
// do something that is only important in the context of Websockets requests | ||
throw new Error('Websockets context is not implemented yet'); | ||
} | ||
else if (ctx.getType() === 'graphql') { | ||
// do something that is only important in the context of GraphQL requests | ||
const gqlExecutionContext = graphql_1.GqlExecutionContext.create(ctx); | ||
return gqlExecutionContext.getContext().req.user; | ||
} | ||
throw new Error('Invalid context'); | ||
} | ||
/** | ||
* Access the user roles from the request object i.e `req.user.roles`. | ||
* | ||
* You can pass an optional property key to the decorator to get it from the user object | ||
* e.g `@UserRoles('premissions')` will return the `req.user.premissions` instead. | ||
* e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead. | ||
*/ | ||
exports.UserRoles = common_1.createParamDecorator((data, ctx) => { | ||
const request = ctx.switchToHttp().getRequest(); | ||
return data ? request.user[data] : request.user.roles; | ||
const user = userFactory(ctx); | ||
return data ? user[data] : user.roles; | ||
}); |
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
Oops, something went wrong.