Skip to content

Commit

Permalink
Add authenticated user decorator, closes #43
Browse files Browse the repository at this point in the history
  • Loading branch information
ferrerojosh committed Apr 12, 2021
1 parent a61438f commit 0041a36
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
13 changes: 10 additions & 3 deletions example/src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { Controller, Get } from '@nestjs/common';
import { AuthenticatedUser } from 'nest-keycloak-connect';

@Controller()
export class AppController {

@Get()
getHello(): string {
return "Hello world!";
getHello(
@AuthenticatedUser()
user: any,
): string {
if (user) {
return `Hello ${user.preferred_username}`;
} else {
return 'Hello world!';
}
}
}
12 changes: 12 additions & 0 deletions src/decorators/authenticated-user.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

/**
* Retrieves the current Keycloak logged-in user.
* @since 1.5.0
*/
export const AuthenticatedUser = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const req = ctx.switchToHttp().getRequest();
return req.user;
},
);
1 change: 1 addition & 0 deletions src/keycloak-connect.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from './decorators/roles.decorator';
export * from './decorators/allow-any-role.decorator';
export * from './decorators/unprotected.decorator';
export * from './decorators/enforcer-options.decorator';
export * from './decorators/authenticated-user.decorator';
export * from './guards/auth.guard';
export * from './guards/resource.guard';
export * from './guards/role.guard';
Expand Down

0 comments on commit 0041a36

Please sign in to comment.