Browse Source

feat(core): Include auth strategy name in AttemptedLoginEvent

BREAKING CHANGE: The `AttemptedLoginEvent.identifier` property is now optional, since it will only be sent when using the "native" authentication strategy. Code that listens for this event should now check that the `identifier` property is defined before attempting to use it.
Michael Bromley 5 years ago
parent
commit
b83f1feff6

+ 3 - 1
packages/core/src/event-bus/events/attempted-login-event.ts

@@ -5,12 +5,14 @@ import { VendureEvent } from '../vendure-event';
 /**
  * @description
  * This event is fired when an attempt is made to log in via the shop or admin API `login` mutation.
+ * The `strategy` represents the name of the AuthenticationStrategy used in the login attempt.
+ * If the "native" strategy is used, the additional `identifier` property will be available.
  *
  * @docsCategory events
  * @docsPage Event Types
  */
 export class AttemptedLoginEvent extends VendureEvent {
-    constructor(public ctx: RequestContext, public identifier: string) {
+    constructor(public ctx: RequestContext, public strategy: string, public identifier?: string) {
         super();
     }
 }

+ 10 - 1
packages/core/src/service/services/auth.service.ts

@@ -9,6 +9,7 @@ import { InternalServerError, NotVerifiedError, UnauthorizedError } from '../../
 import { AuthenticationStrategy } from '../../config/auth/authentication-strategy';
 import {
     NATIVE_AUTH_STRATEGY_NAME,
+    NativeAuthenticationData,
     NativeAuthenticationStrategy,
 } from '../../config/auth/native-authentication-strategy';
 import { ConfigService } from '../../config/config.service';
@@ -42,7 +43,15 @@ export class AuthService {
         authenticationMethod: string,
         authenticationData: any,
     ): Promise<AuthenticatedSession> {
-        this.eventBus.publish(new AttemptedLoginEvent(ctx, authenticationMethod));
+        this.eventBus.publish(
+            new AttemptedLoginEvent(
+                ctx,
+                authenticationMethod,
+                authenticationMethod === NATIVE_AUTH_STRATEGY_NAME
+                    ? (authenticationData as NativeAuthenticationData).username
+                    : undefined,
+            ),
+        );
         const authenticationStrategy = this.getAuthenticationStrategy(apiType, authenticationMethod);
         const user = await authenticationStrategy.authenticate(ctx, authenticationData);
         if (!user) {