diff --git a/README.md b/README.md index 1d23cb0..c00662d 100644 --- a/README.md +++ b/README.md @@ -225,33 +225,15 @@ using the `@Context("req")` and `@Context("res")` decorators. ## Getting the tokens inside a controller or resolver -You can access the parsed access token and refresh token +You can access the access token and refresh token inside your controllers and resolvers using decorators. ```typescript -import { - Authenticated, - AccessToken, - HasPermission, -} from "@moveaxlab/nestjs-security"; - -interface User { - tokenType: "admin" | "user"; - uid: string; - permission: string[]; - // other information contained in the token -} +import { Authenticated, AccessToken } from "@moveaxlab/nestjs-security"; @Authenticated("admin") class MyController { - async myMethod(@AccessToken() token: User) { - // use the token here - } -} - -@HasPermission("myPermission") -class MySecondController { - async mySecondMethod(@AccessToken() token: User) { + async myMethod(@AccessToken() token: string) { // use the token here } } @@ -276,6 +258,33 @@ class MyController { } ``` +You can access the parsed access token using the `@User` decorator. + +```typescript +import { Authenticated, HasPermission, User } from "@moveaxlab/nestjs-security"; + +interface UserType { + tokenType: "admin" | "user"; + uid: string; + permission: string[]; + // other information contained in the token +} + +@Authenticated("admin") +class MyController { + async myMethod(@User() token: UserType) { + // use the token here + } +} + +@HasPermission("myPermission") +class MySecondController { + async mySecondMethod(@User() token: UserType) { + // use the token here + } +} +``` + ## Using different secrets based on the issuer The `jwtSecret` options can accept an object mapping the `iss` key diff --git a/src/decorators/index.ts b/src/decorators/index.ts index 786597c..dc9aa8c 100644 --- a/src/decorators/index.ts +++ b/src/decorators/index.ts @@ -3,3 +3,4 @@ export { Authenticated } from "./authenticated/authenticated.decorator"; export { HasPermission } from "./has-permission/has-permission.decorator"; export { RefreshCookieInterceptor } from "./refresh-cookie.interceptor"; export { RefreshToken } from "./refresh-token.decorator"; +export { User } from "./user.decorator"; diff --git a/src/decorators/user.decorator.ts b/src/decorators/user.decorator.ts new file mode 100644 index 0000000..85be3fe --- /dev/null +++ b/src/decorators/user.decorator.ts @@ -0,0 +1,9 @@ +import { createParamDecorator, ExecutionContext } from "@nestjs/common"; +import { getRequest } from "../utils"; + +/** + * Injects the parsed access token for the current request. + */ +export const User = createParamDecorator((_, context: ExecutionContext) => { + return getRequest(context).user; +});