sso-auth-strategy.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { HttpService } from '@nestjs/axios';
  2. import {
  3. AuthenticationStrategy,
  4. ExternalAuthenticationService,
  5. Injector,
  6. Logger,
  7. RequestContext,
  8. RoleService,
  9. User,
  10. } from '@vendure/core';
  11. import { DocumentNode } from 'graphql';
  12. import gql from 'graphql-tag';
  13. export type SSOAuthData = {
  14. email: string;
  15. };
  16. export class SSOShopAuthenticationStrategy implements AuthenticationStrategy<SSOAuthData> {
  17. readonly name = 'ssoShop';
  18. private externalAuthenticationService: ExternalAuthenticationService;
  19. private httpService: HttpService;
  20. private roleService: RoleService;
  21. init(injector: Injector) {
  22. this.externalAuthenticationService = injector.get(ExternalAuthenticationService);
  23. this.httpService = injector.get(HttpService);
  24. this.roleService = injector.get(RoleService);
  25. }
  26. defineInputType(): DocumentNode {
  27. return gql`
  28. input SSOAuthInput {
  29. email: String!
  30. }
  31. `;
  32. }
  33. async authenticate(ctx: RequestContext, data: SSOAuthData): Promise<User | false> {
  34. if (data.email !== 'test@test.com') {
  35. return false;
  36. }
  37. const user = await this.externalAuthenticationService.findCustomerUser(ctx, this.name, data.email);
  38. if (user) {
  39. return user;
  40. }
  41. return this.externalAuthenticationService.createCustomerAndUser(ctx, {
  42. strategy: this.name,
  43. externalIdentifier: data.email,
  44. emailAddress: data.email,
  45. firstName: 'test',
  46. lastName: 'customer',
  47. verified: true,
  48. });
  49. }
  50. }