-
-
Notifications
You must be signed in to change notification settings - Fork 133
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add authenticated user decorator, closes #43
- Loading branch information
1 parent
a61438f
commit 0041a36
Showing
3 changed files
with
23 additions
and
3 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,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!'; | ||
} | ||
} | ||
} |
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,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; | ||
}, | ||
); |
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