Skip to content

Commit

Permalink
fix(dev-server): Update Keycloak test plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbromley committed Jan 23, 2024
1 parent c2a4685 commit 4ac6f64
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 30 deletions.
14 changes: 14 additions & 0 deletions packages/dev-server/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,18 @@ services:
- pgadmin_data:/var/lib/pgadmin
links:
- "postgres:pgsql-server"
keycloak:
image: quay.io/keycloak/keycloak
ports:
- "9000:8080"
environment:
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: admin
command:
- start-dev
- --import-realm
volumes:
- keycloak_data:/opt/keycloak/data
volumes:
postgres_data:
driver: local
Expand All @@ -95,3 +107,5 @@ volumes:
driver: local
phpmyadmin_data:
driver: local
keycloak_data:
driver: local
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { HttpModule } from '@nestjs/axios';
import { MiddlewareConsumer, NestModule } from '@nestjs/common';
import { PluginCommonModule, VendurePlugin } from '@vendure/core';
import express from 'express';
Expand All @@ -17,7 +18,7 @@ import { KeycloakAuthenticationStrategy } from './keycloak-authentication-strate
* Video demo of this: https://youtu.be/Tj4kwjNd2nM
*/
@VendurePlugin({
imports: [PluginCommonModule],
imports: [PluginCommonModule, HttpModule],
configuration: config => {
config.authOptions.adminAuthenticationStrategy = [
...config.authOptions.adminAuthenticationStrategy,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import {
Injector,
Logger,
RequestContext,
RoleService,
Role,
TransactionalConnection,
User,
} from '@vendure/core';
import { DocumentNode } from 'graphql';
Expand All @@ -29,13 +30,13 @@ export class KeycloakAuthenticationStrategy implements AuthenticationStrategy<Ke
readonly name = 'keycloak';
private externalAuthenticationService: ExternalAuthenticationService;
private httpService: HttpService;
private roleService: RoleService;
private connection: TransactionalConnection;
private bearerToken: string;

init(injector: Injector) {
this.externalAuthenticationService = injector.get(ExternalAuthenticationService);
this.httpService = injector.get(HttpService);
this.roleService = injector.get(RoleService);
this.connection = injector.get(TransactionalConnection);
}

defineInputType(): DocumentNode {
Expand All @@ -51,13 +52,13 @@ export class KeycloakAuthenticationStrategy implements AuthenticationStrategy<Ke
this.bearerToken = data.token;
try {
const response = await this.httpService
.get('http://localhost:9000/auth/realms/myrealm/protocol/openid-connect/userinfo', {
.get('http://localhost:9000/realms/myrealm/protocol/openid-connect/userinfo', {
headers: {
Authorization: `Bearer ${this.bearerToken}`,
},
})
.toPromise();
userInfo = response.data;
userInfo = response?.data;
} catch (e: any) {
Logger.error(e);
return false;
Expand All @@ -75,8 +76,9 @@ export class KeycloakAuthenticationStrategy implements AuthenticationStrategy<Ke
return user;
}

const roles = await this.roleService.findAll(ctx);
const merchantRole = roles.items.find(r => r.code === 'merchant');
const merchantRole = await this.connection.getRepository(ctx, Role).findOne({
where: { code: 'merchant' },
});

if (!merchantRole) {
Logger.error(`Could not find "merchant" role`);
Expand All @@ -88,8 +90,8 @@ export class KeycloakAuthenticationStrategy implements AuthenticationStrategy<Ke
externalIdentifier: userInfo.sub,
identifier: userInfo.preferred_username,
emailAddress: userInfo.email,
firstName: userInfo.given_name,
lastName: userInfo.family_name,
firstName: userInfo.given_name ?? userInfo.preferred_username,
lastName: userInfo.family_name ?? userInfo.preferred_username,
roles: [merchantRole],
});
}
Expand Down
40 changes: 20 additions & 20 deletions packages/dev-server/test-plugins/keycloak-auth/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
crossorigin="anonymous"
/>
<script src="http://localhost:9000/auth/js/keycloak.js"></script>
<script src="http://localhost:9000/js/keycloak.js"></script>
<style>
#logout.hidden {
display: none;
Expand All @@ -25,9 +25,7 @@ <h2 class="mt-4">Welcome to << corporate intranet >></h2>
<button class="btn btn-sm btn-secondary hidden" id="logout">Log out of intranet</button>
</p>
<div class="text-center mt-4">
<button id="login" class="btn btn-primary">
Log In To Vendure
</button>
<button id="login" class="btn btn-primary">Log In To Vendure</button>
</div>
</div>
<script>
Expand Down Expand Up @@ -82,27 +80,29 @@ <h2 class="mt-4">Welcome to << corporate intranet >></h2>

function loginToAdminUi() {
return graphQlQuery(
`
mutation Authenticate($token: String!) {
authenticate(input: {
keycloak: {
token: $token
}
}) {
user { id }
}
}
`,
/* GraphQL */ `
mutation Authenticate($token: String!) {
authenticate(input: { keycloak: { token: $token } }) {
... on CurrentUser {
id
}
... on ErrorResult {
errorCode
message
}
}
}
`,
{ token: keycloak.token },
)
.then((result) => {
.then(result => {
console.log(result);
if (result.data?.authenticate.user) {
if (result.data?.authenticate.id) {
// successfully authenticated
window.location.replace('http://localhost:3000/admin');
window.location.replace('http://localhost:4200/admin');
}
})
.catch((err) => {
.catch(err => {
console.log('error', err);
});
}
Expand All @@ -115,7 +115,7 @@ <h2 class="mt-4">Welcome to << corporate intranet >></h2>
Accept: 'application/json',
},
body: JSON.stringify({ query, variables }),
}).then((r) => {
}).then(r => {
return r.json();
});
}
Expand Down

0 comments on commit 4ac6f64

Please sign in to comment.