google-auth-plugin.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { INestApplication } from '@nestjs/common';
  2. import { OnVendureBootstrap, OnVendureClose, PluginCommonModule, VendurePlugin } from '@vendure/core';
  3. import express from 'express';
  4. import { Server } from 'http';
  5. import path from 'path';
  6. import { GoogleAuthenticationStrategy } from './google-authentication-strategy';
  7. export type GoogleAuthPluginOptions = {
  8. clientId: string;
  9. };
  10. /**
  11. * An demo implementation of a Google login flow.
  12. *
  13. * To run this you'll need to install `google-auth-library` from npm.
  14. *
  15. * Then add this plugin to the dev config.
  16. *
  17. * The "storefront" is a simple html file which is served on http://localhost:80,
  18. * but to get it to work with the Google login button you'll need to resolve it to some
  19. * public-looking url such as `http://google-login-test.com` by modifying your OS
  20. * hosts file.
  21. */
  22. @VendurePlugin({
  23. imports: [PluginCommonModule],
  24. configuration: (config) => {
  25. config.authOptions.shopAuthenticationStrategy = [
  26. ...config.authOptions.shopAuthenticationStrategy,
  27. new GoogleAuthenticationStrategy(GoogleAuthPlugin.options.clientId),
  28. ];
  29. return config;
  30. },
  31. })
  32. export class GoogleAuthPlugin implements OnVendureBootstrap, OnVendureClose {
  33. static options: GoogleAuthPluginOptions;
  34. private staticServer: Server;
  35. static init(options: GoogleAuthPluginOptions) {
  36. this.options = options;
  37. return GoogleAuthPlugin;
  38. }
  39. onVendureBootstrap() {
  40. // Set up a static express server to serve the demo login page
  41. // from public/index.html.
  42. const app = express();
  43. app.use(express.static(path.join(__dirname, 'public')));
  44. this.staticServer = app.listen(80);
  45. }
  46. onVendureClose(): void | Promise<void> {
  47. return new Promise((resolve, reject) => {
  48. this.staticServer.close((err) => {
  49. if (err) {
  50. reject(err);
  51. } else {
  52. resolve();
  53. }
  54. });
  55. });
  56. }
  57. }