Sfoglia il codice sorgente

fix(dev-server): Update Keycloak test plugin

Michael Bromley 2 anni fa
parent
commit
4ac6f649bf

+ 14 - 0
packages/dev-server/docker-compose.yml

@@ -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
@@ -95,3 +107,5 @@ volumes:
     driver: local
   phpmyadmin_data:
     driver: local
+  keycloak_data:
+    driver: local

+ 2 - 1
packages/dev-server/test-plugins/keycloak-auth/keycloak-auth-plugin.ts

@@ -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';
@@ -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,

+ 11 - 9
packages/dev-server/test-plugins/keycloak-auth/keycloak-authentication-strategy.ts

@@ -5,7 +5,8 @@ import {
     Injector,
     Logger,
     RequestContext,
-    RoleService,
+    Role,
+    TransactionalConnection,
     User,
 } from '@vendure/core';
 import { DocumentNode } from 'graphql';
@@ -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 {
@@ -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;
@@ -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`);
@@ -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],
         });
     }

+ 20 - 20
packages/dev-server/test-plugins/keycloak-auth/public/index.html

@@ -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;
@@ -25,9 +25,7 @@
                 <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>
@@ -82,27 +80,29 @@
 
             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);
                     });
             }
@@ -115,7 +115,7 @@
                         Accept: 'application/json',
                     },
                     body: JSON.stringify({ query, variables }),
-                }).then((r) => {
+                }).then(r => {
                     return r.json();
                 });
             }