@commercetools-frontend/mc-dev-authentication 21.0.0 → 21.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export * from "./declarations/src/index";
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
6
+ var _startsWithInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/starts-with');
7
+ var _concatInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/concat');
8
+ var fs = require('fs');
9
+ var path = require('path');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
12
+
13
+ var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
14
+ var _startsWithInstanceProperty__default = /*#__PURE__*/_interopDefault(_startsWithInstanceProperty);
15
+ var _concatInstanceProperty__default = /*#__PURE__*/_interopDefault(_concatInstanceProperty);
16
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
17
+ var path__default = /*#__PURE__*/_interopDefault(path);
18
+
19
+ function logoutRoute(response) {
20
+ var _context;
21
+
22
+ var additionalCookieParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
23
+ // NOTE: removing the cookie only works if your are running the MC API
24
+ // locally, otherwise the cookie won't get removed as it's set to a
25
+ // proper domain (e.g. commercetools.com), which we can't unset from localhost.
26
+ response.setHeader('Set-Cookie', _concatInstanceProperty__default["default"](_context = ["mcAccessToken=''", // <-- unset the value
27
+ 'Path=/', "Expires=".concat(new Date(0).toUTCString()), // <-- put a date in the past
28
+ 'HttpOnly']).call(_context, additionalCookieParameters).join('; '));
29
+ }
30
+
31
+ var pages$1 = {
32
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n <div class=\"info\">\n <small>\n Note that Single Sign On is not supported at the moment for the\n development login page. If you are interested in this functionality,\n let us know and open a\n <a\n href=\"https://github.com/commercetools/merchant-center-application-kit/issues/new/choose\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >support issue</a\n >.\n </small>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
33
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
34
+ };
35
+
36
+ var trimTrailingSlash$1 = function trimTrailingSlash(value) {
37
+ return value.replace(/\/$/, '');
38
+ };
39
+
40
+ function createMcDevAuthenticationMiddleware(applicationConfig) {
41
+ var htmlLogin = pages$1.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash$1(applicationConfig.env.mcApiUrl));
42
+ var htmlLogout = pages$1.logoutPage;
43
+ var isDevAuthenticationMiddlewareDisabled = String(applicationConfig.env.disableAuthRoutesOfDevServer) === 'true' || applicationConfig.env.servedByProxy;
44
+ return function (request, response, next) {
45
+ var _applicationConfig$en, _applicationConfig$en2;
46
+
47
+ if (request.originalUrl === '/api/graphql') {
48
+ response.statusCode = 404;
49
+ response.setHeader('Content-Type', 'application/json');
50
+ response.end(_JSON$stringify__default["default"]({
51
+ message: "This GraphQL endpoint is only available in production in the [Merchant Center Proxy Router](https://docs.commercetools.com/custom-applications/concepts/merchant-center-proxy-router). Please check that you are not calling this endpoint in development mode."
52
+ }));
53
+ return;
54
+ }
55
+
56
+ if ((_applicationConfig$en = applicationConfig.env.__DEVELOPMENT__) !== null && _applicationConfig$en !== void 0 && (_applicationConfig$en2 = _applicationConfig$en.oidc) !== null && _applicationConfig$en2 !== void 0 && _applicationConfig$en2.authorizeUrl) {
57
+ var _applicationConfig$en3, _applicationConfig$en4, _context;
58
+
59
+ // Handle login page for OIDC workflow when developing against a local MC API.
60
+ if ((_applicationConfig$en3 = applicationConfig.env.__DEVELOPMENT__) !== null && _applicationConfig$en3 !== void 0 && (_applicationConfig$en4 = _applicationConfig$en3.oidc) !== null && _applicationConfig$en4 !== void 0 && _startsWithInstanceProperty__default["default"](_context = _applicationConfig$en4.authorizeUrl).call(_context, 'http://localhost')) {
61
+ var _context2;
62
+
63
+ if (_startsWithInstanceProperty__default["default"](_context2 = request.originalUrl).call(_context2, '/login/authorize')) {
64
+ if (isDevAuthenticationMiddlewareDisabled) {
65
+ next();
66
+ } else {
67
+ response.end(htmlLogin);
68
+ }
69
+
70
+ return;
71
+ }
72
+ }
73
+ } else {
74
+ if (request.originalUrl === '/login') {
75
+ if (isDevAuthenticationMiddlewareDisabled) {
76
+ next();
77
+ } else {
78
+ response.end(htmlLogin);
79
+ }
80
+
81
+ return;
82
+ }
83
+
84
+ if (request.originalUrl === '/logout') {
85
+ logoutRoute(response);
86
+
87
+ if (isDevAuthenticationMiddlewareDisabled) {
88
+ next();
89
+ } else {
90
+ response.end(htmlLogout);
91
+ }
92
+
93
+ return;
94
+ }
95
+ }
96
+
97
+ next();
98
+ };
99
+ }
100
+
101
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
102
+ var pages = {
103
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n <div class=\"info\">\n <small>\n Note that Single Sign On is not supported at the moment for the\n development login page. If you are interested in this functionality,\n let us know and open a\n <a\n href=\"https://github.com/commercetools/merchant-center-application-kit/issues/new/choose\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >support issue</a\n >.\n </small>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
104
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
105
+ };
106
+
107
+ var trimTrailingSlash = function trimTrailingSlash(value) {
108
+ return value.replace(/\/$/, '');
109
+ }; // Make sure any symlinks in the project folder are resolved:
110
+ // https://github.com/facebook/create-react-app/issues/637
111
+
112
+
113
+ var appDirectory = fs__default["default"].realpathSync(process.cwd());
114
+
115
+ var resolveApp = function resolveApp(relativePath) {
116
+ return path__default["default"].resolve(appDirectory, relativePath);
117
+ };
118
+
119
+ var paths = {
120
+ appBuild: resolveApp('public')
121
+ }; // This transformer will generate a development `login` and `logout` HTML files
122
+ // and copy them to the application public folder.
123
+ // This is necessary to run the application locally in production mode.
124
+
125
+ var transformerLocal = function transformerLocal(compiledHtml) {
126
+ var htmlLogin = pages.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash(compiledHtml.env.mcApiUrl));
127
+ var htmlLogout = pages.logoutPage;
128
+ fs__default["default"].writeFileSync(path__default["default"].join(paths.appBuild, 'login.html'), htmlLogin, 'utf8');
129
+ fs__default["default"].writeFileSync(path__default["default"].join(paths.appBuild, 'logout.html'), htmlLogout, 'utf8');
130
+ };
131
+
132
+ exports.createMcDevAuthenticationMiddleware = createMcDevAuthenticationMiddleware;
133
+ exports.transformerLocal = transformerLocal;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === "production") {
4
+ module.exports = require("./commercetools-frontend-mc-dev-authentication.cjs.prod.js");
5
+ } else {
6
+ module.exports = require("./commercetools-frontend-mc-dev-authentication.cjs.dev.js");
7
+ }
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
6
+ var _startsWithInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/starts-with');
7
+ var _concatInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/concat');
8
+ var fs = require('fs');
9
+ var path = require('path');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
12
+
13
+ var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
14
+ var _startsWithInstanceProperty__default = /*#__PURE__*/_interopDefault(_startsWithInstanceProperty);
15
+ var _concatInstanceProperty__default = /*#__PURE__*/_interopDefault(_concatInstanceProperty);
16
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
17
+ var path__default = /*#__PURE__*/_interopDefault(path);
18
+
19
+ function logoutRoute(response) {
20
+ var _context;
21
+
22
+ var additionalCookieParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
23
+ // NOTE: removing the cookie only works if your are running the MC API
24
+ // locally, otherwise the cookie won't get removed as it's set to a
25
+ // proper domain (e.g. commercetools.com), which we can't unset from localhost.
26
+ response.setHeader('Set-Cookie', _concatInstanceProperty__default["default"](_context = ["mcAccessToken=''", // <-- unset the value
27
+ 'Path=/', "Expires=".concat(new Date(0).toUTCString()), // <-- put a date in the past
28
+ 'HttpOnly']).call(_context, additionalCookieParameters).join('; '));
29
+ }
30
+
31
+ var pages$1 = {
32
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n <div class=\"info\">\n <small>\n Note that Single Sign On is not supported at the moment for the\n development login page. If you are interested in this functionality,\n let us know and open a\n <a\n href=\"https://github.com/commercetools/merchant-center-application-kit/issues/new/choose\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >support issue</a\n >.\n </small>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
33
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
34
+ };
35
+
36
+ var trimTrailingSlash$1 = function trimTrailingSlash(value) {
37
+ return value.replace(/\/$/, '');
38
+ };
39
+
40
+ function createMcDevAuthenticationMiddleware(applicationConfig) {
41
+ var htmlLogin = pages$1.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash$1(applicationConfig.env.mcApiUrl));
42
+ var htmlLogout = pages$1.logoutPage;
43
+ var isDevAuthenticationMiddlewareDisabled = String(applicationConfig.env.disableAuthRoutesOfDevServer) === 'true' || applicationConfig.env.servedByProxy;
44
+ return function (request, response, next) {
45
+ var _applicationConfig$en, _applicationConfig$en2;
46
+
47
+ if (request.originalUrl === '/api/graphql') {
48
+ response.statusCode = 404;
49
+ response.setHeader('Content-Type', 'application/json');
50
+ response.end(_JSON$stringify__default["default"]({
51
+ message: "This GraphQL endpoint is only available in production in the [Merchant Center Proxy Router](https://docs.commercetools.com/custom-applications/concepts/merchant-center-proxy-router). Please check that you are not calling this endpoint in development mode."
52
+ }));
53
+ return;
54
+ }
55
+
56
+ if ((_applicationConfig$en = applicationConfig.env.__DEVELOPMENT__) !== null && _applicationConfig$en !== void 0 && (_applicationConfig$en2 = _applicationConfig$en.oidc) !== null && _applicationConfig$en2 !== void 0 && _applicationConfig$en2.authorizeUrl) {
57
+ var _applicationConfig$en3, _applicationConfig$en4, _context;
58
+
59
+ // Handle login page for OIDC workflow when developing against a local MC API.
60
+ if ((_applicationConfig$en3 = applicationConfig.env.__DEVELOPMENT__) !== null && _applicationConfig$en3 !== void 0 && (_applicationConfig$en4 = _applicationConfig$en3.oidc) !== null && _applicationConfig$en4 !== void 0 && _startsWithInstanceProperty__default["default"](_context = _applicationConfig$en4.authorizeUrl).call(_context, 'http://localhost')) {
61
+ var _context2;
62
+
63
+ if (_startsWithInstanceProperty__default["default"](_context2 = request.originalUrl).call(_context2, '/login/authorize')) {
64
+ if (isDevAuthenticationMiddlewareDisabled) {
65
+ next();
66
+ } else {
67
+ response.end(htmlLogin);
68
+ }
69
+
70
+ return;
71
+ }
72
+ }
73
+ } else {
74
+ if (request.originalUrl === '/login') {
75
+ if (isDevAuthenticationMiddlewareDisabled) {
76
+ next();
77
+ } else {
78
+ response.end(htmlLogin);
79
+ }
80
+
81
+ return;
82
+ }
83
+
84
+ if (request.originalUrl === '/logout') {
85
+ logoutRoute(response);
86
+
87
+ if (isDevAuthenticationMiddlewareDisabled) {
88
+ next();
89
+ } else {
90
+ response.end(htmlLogout);
91
+ }
92
+
93
+ return;
94
+ }
95
+ }
96
+
97
+ next();
98
+ };
99
+ }
100
+
101
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
102
+ var pages = {
103
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n <div class=\"info\">\n <small>\n Note that Single Sign On is not supported at the moment for the\n development login page. If you are interested in this functionality,\n let us know and open a\n <a\n href=\"https://github.com/commercetools/merchant-center-application-kit/issues/new/choose\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >support issue</a\n >.\n </small>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
104
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
105
+ };
106
+
107
+ var trimTrailingSlash = function trimTrailingSlash(value) {
108
+ return value.replace(/\/$/, '');
109
+ }; // Make sure any symlinks in the project folder are resolved:
110
+ // https://github.com/facebook/create-react-app/issues/637
111
+
112
+
113
+ var appDirectory = fs__default["default"].realpathSync(process.cwd());
114
+
115
+ var resolveApp = function resolveApp(relativePath) {
116
+ return path__default["default"].resolve(appDirectory, relativePath);
117
+ };
118
+
119
+ var paths = {
120
+ appBuild: resolveApp('public')
121
+ }; // This transformer will generate a development `login` and `logout` HTML files
122
+ // and copy them to the application public folder.
123
+ // This is necessary to run the application locally in production mode.
124
+
125
+ var transformerLocal = function transformerLocal(compiledHtml) {
126
+ var htmlLogin = pages.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash(compiledHtml.env.mcApiUrl));
127
+ var htmlLogout = pages.logoutPage;
128
+ fs__default["default"].writeFileSync(path__default["default"].join(paths.appBuild, 'login.html'), htmlLogin, 'utf8');
129
+ fs__default["default"].writeFileSync(path__default["default"].join(paths.appBuild, 'logout.html'), htmlLogout, 'utf8');
130
+ };
131
+
132
+ exports.createMcDevAuthenticationMiddleware = createMcDevAuthenticationMiddleware;
133
+ exports.transformerLocal = transformerLocal;
@@ -0,0 +1,120 @@
1
+ import _JSON$stringify from '@babel/runtime-corejs3/core-js-stable/json/stringify';
2
+ import _startsWithInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/starts-with';
3
+ import _concatInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/concat';
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+
7
+ function logoutRoute(response) {
8
+ var _context;
9
+
10
+ var additionalCookieParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
11
+ // NOTE: removing the cookie only works if your are running the MC API
12
+ // locally, otherwise the cookie won't get removed as it's set to a
13
+ // proper domain (e.g. commercetools.com), which we can't unset from localhost.
14
+ response.setHeader('Set-Cookie', _concatInstanceProperty(_context = ["mcAccessToken=''", // <-- unset the value
15
+ 'Path=/', "Expires=".concat(new Date(0).toUTCString()), // <-- put a date in the past
16
+ 'HttpOnly']).call(_context, additionalCookieParameters).join('; '));
17
+ }
18
+
19
+ var pages$1 = {
20
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n <div class=\"info\">\n <small>\n Note that Single Sign On is not supported at the moment for the\n development login page. If you are interested in this functionality,\n let us know and open a\n <a\n href=\"https://github.com/commercetools/merchant-center-application-kit/issues/new/choose\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >support issue</a\n >.\n </small>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
21
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
22
+ };
23
+
24
+ var trimTrailingSlash$1 = function trimTrailingSlash(value) {
25
+ return value.replace(/\/$/, '');
26
+ };
27
+
28
+ function createMcDevAuthenticationMiddleware(applicationConfig) {
29
+ var htmlLogin = pages$1.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash$1(applicationConfig.env.mcApiUrl));
30
+ var htmlLogout = pages$1.logoutPage;
31
+ var isDevAuthenticationMiddlewareDisabled = String(applicationConfig.env.disableAuthRoutesOfDevServer) === 'true' || applicationConfig.env.servedByProxy;
32
+ return function (request, response, next) {
33
+ var _applicationConfig$en, _applicationConfig$en2;
34
+
35
+ if (request.originalUrl === '/api/graphql') {
36
+ response.statusCode = 404;
37
+ response.setHeader('Content-Type', 'application/json');
38
+ response.end(_JSON$stringify({
39
+ message: "This GraphQL endpoint is only available in production in the [Merchant Center Proxy Router](https://docs.commercetools.com/custom-applications/concepts/merchant-center-proxy-router). Please check that you are not calling this endpoint in development mode."
40
+ }));
41
+ return;
42
+ }
43
+
44
+ if ((_applicationConfig$en = applicationConfig.env.__DEVELOPMENT__) !== null && _applicationConfig$en !== void 0 && (_applicationConfig$en2 = _applicationConfig$en.oidc) !== null && _applicationConfig$en2 !== void 0 && _applicationConfig$en2.authorizeUrl) {
45
+ var _applicationConfig$en3, _applicationConfig$en4, _context;
46
+
47
+ // Handle login page for OIDC workflow when developing against a local MC API.
48
+ if ((_applicationConfig$en3 = applicationConfig.env.__DEVELOPMENT__) !== null && _applicationConfig$en3 !== void 0 && (_applicationConfig$en4 = _applicationConfig$en3.oidc) !== null && _applicationConfig$en4 !== void 0 && _startsWithInstanceProperty(_context = _applicationConfig$en4.authorizeUrl).call(_context, 'http://localhost')) {
49
+ var _context2;
50
+
51
+ if (_startsWithInstanceProperty(_context2 = request.originalUrl).call(_context2, '/login/authorize')) {
52
+ if (isDevAuthenticationMiddlewareDisabled) {
53
+ next();
54
+ } else {
55
+ response.end(htmlLogin);
56
+ }
57
+
58
+ return;
59
+ }
60
+ }
61
+ } else {
62
+ if (request.originalUrl === '/login') {
63
+ if (isDevAuthenticationMiddlewareDisabled) {
64
+ next();
65
+ } else {
66
+ response.end(htmlLogin);
67
+ }
68
+
69
+ return;
70
+ }
71
+
72
+ if (request.originalUrl === '/logout') {
73
+ logoutRoute(response);
74
+
75
+ if (isDevAuthenticationMiddlewareDisabled) {
76
+ next();
77
+ } else {
78
+ response.end(htmlLogout);
79
+ }
80
+
81
+ return;
82
+ }
83
+ }
84
+
85
+ next();
86
+ };
87
+ }
88
+
89
+ // https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros
90
+ var pages = {
91
+ "loginPage": "<html>\n <head>\n <title>Login (development only)</title>\n <style>\n html,\n body {\n font: 1em sans-serif;\n padding: 0;\n margin: 0;\n height: 100vh;\n width: 100vw;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n margin-top: 32px;\n }\n\n body > * + * {\n margin-top: 32px;\n }\n\n .title {\n width: 355px;\n }\n\n form {\n display: flex;\n flex-direction: column;\n width: 355px;\n }\n\n form > * + * {\n margin: 16px 0 0;\n }\n\n .field {\n border: 0;\n }\n\n .field > * + * {\n margin: 8px 0 0;\n }\n\n label {\n display: block;\n }\n\n input {\n width: 100%;\n height: 24px;\n outline: none;\n }\n\n input:focus {\n border: 1px solid cornflowerblue;\n }\n\n input:focus:invalid {\n border-color: red;\n }\n\n abbr {\n text-decoration: none;\n color: orangered;\n }\n\n #errors > div {\n background-color: red;\n color: #eee;\n padding: 8px;\n border-radius: 4px;\n }\n\n .info {\n background-color: #b5e1fd;\n padding: 8px;\n border-radius: 4px;\n }\n </style>\n </head>\n <body>\n <div class=\"title\">\n <h3>\n Welcome to the Merchant Center authorization page for local development\n </h3>\n <small>\n This page is only available in development mode and is necessary to\n authenticate yourself. In production environment, we use our own\n authentication service.\n </small>\n </div>\n <form id=\"login\">\n <div id=\"errors\"></div>\n <div class=\"field\">\n <label for=\"email\">\n Email<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input id=\"email\" name=\"email\" type=\"text\" required=\"required\" />\n </div>\n <div class=\"field\">\n <label for=\"password\">\n Password<abbr title=\"This field is mandatory\">*</abbr>\n </label>\n <input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required=\"required\"\n />\n </div>\n <div>\n <button type=\"submit\" aria-label=\"Sign in\">Sign in 🚀</button>\n </div>\n <div class=\"info\">\n <small>\n Note that Single Sign On is not supported at the moment for the\n development login page. If you are interested in this functionality,\n let us know and open a\n <a\n href=\"https://github.com/commercetools/merchant-center-application-kit/issues/new/choose\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >support issue</a\n >.\n </small>\n </div>\n </form>\n <script>\n /* eslint-disable no-var,vars-on-top */\n /**\n * NOTE:\n * This code is only used in development mode.\n * It authenticates a developer using the same mechanisms\n * as when not running in development. However,\n * this runs on the same domain as the developer.\n */\n window.addEventListener('load', function loaded() {\n var form = document.getElementById('login');\n form.addEventListener('submit', function onSubmit(event) {\n event.preventDefault();\n authorize();\n });\n\n function authorize() {\n var data = new FormData(form);\n var payload = {\n email: data.get('email'),\n password: data.get('password'),\n };\n\n var queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('response_type')) {\n // OIDC params\n payload.client_id = queryParams.get('client_id');\n payload.response_type = queryParams.get('response_type');\n payload.scope = queryParams.get('scope');\n payload.state = queryParams.get('state');\n payload.nonce = queryParams.get('nonce');\n }\n\n var container = document.getElementById('errors');\n // Clean up error message elements\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n const url = '__MC_API_URL__/tokens';\n\n window\n .fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n body: JSON.stringify(payload),\n })\n .then(function handleResponse(response) {\n if (response.ok) {\n return response.json().then(function onSuccess(result) {\n // Handle OIDC redirect.\n if (queryParams.has('response_type')) {\n window.location.replace(result.redirectTo);\n } else {\n window.localStorage.setItem('isAuthenticated', true);\n var searchParams = new URLSearchParams(\n window.location.search\n );\n var redirectTo = searchParams.get('redirectTo') || '/';\n window.location.replace(redirectTo);\n }\n });\n }\n return response.text().then(function onError(responseText) {\n var message;\n try {\n var parsedResponse = JSON.parse(responseText);\n message = parsedResponse.message;\n } catch (e) {\n console.warn(\n `Failed to parse error response for ${url}:`,\n responseText\n );\n\n message = responseText;\n }\n var errorMessage = document.createTextNode(message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n })\n .catch(function onNetworkError(error) {\n var errorMessage = document.createTextNode(error.message);\n var errorContainer = document.createElement('div');\n errorContainer.appendChild(errorMessage);\n container.appendChild(errorContainer, container);\n });\n }\n });\n </script>\n </body>\n</html>\n",
92
+ "logoutPage": "<html>\n <head>\n <title>Logout (development only)</title>\n <script>\n window.localStorage.removeItem('isAuthenticated');\n window.localStorage.removeItem('loginStrategy');\n window.localStorage.removeItem('activeProjectKey');\n </script>\n </head>\n <body>\n <div>\n <h3>This is the logout page for local development.</h3>\n <p>\n Be aware that you might still have an active session as the cookie is\n assigned to a production domain (e.g. commercetools.com) which we can't\n unset from localhost. This is only a problem on local development and we\n intend fix this in the future.\n </p>\n <p>\n You can\n <a href=\"#\" onclick=\"window.location='/login'+window.location.search;\"\n >go to the login page</a\n >\n now.\n </p>\n </div>\n </body>\n</html>\n"
93
+ };
94
+
95
+ var trimTrailingSlash = function trimTrailingSlash(value) {
96
+ return value.replace(/\/$/, '');
97
+ }; // Make sure any symlinks in the project folder are resolved:
98
+ // https://github.com/facebook/create-react-app/issues/637
99
+
100
+
101
+ var appDirectory = fs.realpathSync(process.cwd());
102
+
103
+ var resolveApp = function resolveApp(relativePath) {
104
+ return path.resolve(appDirectory, relativePath);
105
+ };
106
+
107
+ var paths = {
108
+ appBuild: resolveApp('public')
109
+ }; // This transformer will generate a development `login` and `logout` HTML files
110
+ // and copy them to the application public folder.
111
+ // This is necessary to run the application locally in production mode.
112
+
113
+ var transformerLocal = function transformerLocal(compiledHtml) {
114
+ var htmlLogin = pages.loginPage.replace(new RegExp('__MC_API_URL__', 'g'), trimTrailingSlash(compiledHtml.env.mcApiUrl));
115
+ var htmlLogout = pages.logoutPage;
116
+ fs.writeFileSync(path.join(paths.appBuild, 'login.html'), htmlLogin, 'utf8');
117
+ fs.writeFileSync(path.join(paths.appBuild, 'logout.html'), htmlLogout, 'utf8');
118
+ };
119
+
120
+ export { createMcDevAuthenticationMiddleware, transformerLocal };
@@ -0,0 +1,4 @@
1
+ import type { Request, Response, NextFunction } from 'express';
2
+ import type { TCustomApplicationRuntimeConfig } from './types';
3
+ declare function createMcDevAuthenticationMiddleware(applicationConfig: TCustomApplicationRuntimeConfig): (request: Request, response: Response, next: NextFunction) => void;
4
+ export default createMcDevAuthenticationMiddleware;
@@ -0,0 +1,2 @@
1
+ export { default as createMcDevAuthenticationMiddleware } from './create-mc-dev-authentication-middleware';
2
+ export { default as transformerLocal } from './transformer-local';
@@ -0,0 +1,3 @@
1
+ declare type Pages = { loginPage: string; logoutPage: string };
2
+ declare const pages: Pages;
3
+ export default pages;
@@ -0,0 +1 @@
1
+ export { default as logout } from './logout';
@@ -0,0 +1,3 @@
1
+ import type { Response } from 'express';
2
+ declare function logoutRoute(response: Response, additionalCookieParameters?: string[]): void;
3
+ export default logoutRoute;
@@ -0,0 +1,3 @@
1
+ import type { TCompiledHtml } from './types';
2
+ declare const transformerLocal: (compiledHtml: TCompiledHtml) => void;
3
+ export default transformerLocal;
@@ -0,0 +1,9 @@
1
+ import type { ApplicationRuntimeConfig } from '@commercetools-frontend/application-config';
2
+ export declare type TCustomApplicationRuntimeConfig = ApplicationRuntimeConfig<{
3
+ disableAuthRoutesOfDevServer?: boolean;
4
+ }>;
5
+ export declare type TCompiledHtml = {
6
+ env: TCustomApplicationRuntimeConfig['env'];
7
+ headers: Record<string, string>;
8
+ indexHtmlContent: string;
9
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercetools-frontend/mc-dev-authentication",
3
- "version": "21.0.0",
3
+ "version": "21.6.0",
4
4
  "description": "Authentication views when running webpack-dev-server in development mode",
5
5
  "bugs": "https://github.com/commercetools/merchant-center-application-kit/issues",
6
6
  "repository": {
@@ -14,8 +14,23 @@
14
14
  "publishConfig": {
15
15
  "access": "public"
16
16
  },
17
+ "main": "dist/commercetools-frontend-mc-dev-authentication.cjs.js",
18
+ "module": "dist/commercetools-frontend-mc-dev-authentication.esm.js",
19
+ "files": [
20
+ "dist",
21
+ "transformer-local.js",
22
+ "package.json",
23
+ "LICENSE",
24
+ "README.md"
25
+ ],
17
26
  "dependencies": {
18
- "pug": "3.0.2"
27
+ "@babel/runtime": "^7.17.9",
28
+ "@babel/runtime-corejs3": "^7.17.9"
29
+ },
30
+ "devDependencies": {
31
+ "@commercetools-frontend/application-config": "21.6.0",
32
+ "@tsconfig/node14": "^1.0.1",
33
+ "express": "4.18.1"
19
34
  },
20
35
  "engines": {
21
36
  "node": ">=14"
@@ -1,49 +1,12 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const pug = require('pug');
4
-
5
- const compileLoginView = pug.compileFile(
6
- path.join(__dirname, './views/login.pug')
7
- );
8
- const compileLogoutView = pug.compileFile(
9
- path.join(__dirname, './views/logout.pug')
10
- );
11
-
12
- // Make sure any symlinks in the project folder are resolved:
13
- // https://github.com/facebook/create-react-app/issues/637
14
- const appDirectory = fs.realpathSync(process.cwd());
15
- const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);
16
- const paths = {
17
- appBuild: resolveApp('public'),
18
- };
19
-
20
- // This transformer will generate a development `login` and `logout` HTML files
21
- // and copy them to the application public foder.
22
- // This is necessary to run the application locally in production mode.
23
- module.exports = ({ env }) => {
24
- const loginViewHtml = compileLoginView({ env });
25
- const logoutViewHtml = compileLogoutView({ env });
26
-
27
- fs.copyFileSync(
28
- path.join(__dirname, 'views', 'login.css'),
29
- path.join(paths.appBuild, 'login.css')
30
- );
31
- fs.copyFileSync(
32
- path.join(__dirname, 'views', 'login.js'),
33
- path.join(paths.appBuild, 'login.js')
34
- );
35
- fs.copyFileSync(
36
- path.join(__dirname, 'views', 'logout.js'),
37
- path.join(paths.appBuild, 'logout.js')
38
- );
39
- fs.writeFileSync(
40
- path.join(paths.appBuild, 'login.html'),
41
- loginViewHtml,
42
- 'utf8'
43
- );
44
- fs.writeFileSync(
45
- path.join(paths.appBuild, 'logout.html'),
46
- logoutViewHtml,
47
- 'utf8'
48
- );
49
- };
1
+ /**
2
+ * This file is expected to be included in the package as it's referenced for the `--transformer` option
3
+ * in the `compile-html` command.
4
+ *
5
+ * @example
6
+ * ```
7
+ * mc-scripts compile-html --transformer @commercetools-frontend/mc-dev-authentication/transformer-local.js
8
+ * ```
9
+ */
10
+
11
+ const { transformerLocal } = require('.');
12
+ module.exports = transformerLocal;
package/CHANGELOG.md DELETED
@@ -1,158 +0,0 @@
1
- # @commercetools-frontend/mc-dev-authentication
2
-
3
- ## 21.0.0
4
-
5
- ### Major Changes
6
-
7
- - [#2430](https://github.com/commercetools/merchant-center-application-kit/pull/2430) [`bb1f7d75`](https://github.com/commercetools/merchant-center-application-kit/commit/bb1f7d75ff54f7fef05c4d2b3328b88e400b4867) Thanks [@emmenko](https://github.com/emmenko)! - Drop Node.js `v12`. Recommended min Node.js version is `v14` or `v16`.
8
-
9
- * [#2430](https://github.com/commercetools/merchant-center-application-kit/pull/2430) [`bb1f7d75`](https://github.com/commercetools/merchant-center-application-kit/commit/bb1f7d75ff54f7fef05c4d2b3328b88e400b4867) Thanks [@emmenko](https://github.com/emmenko)! - Following breaking changes were introduced:
10
-
11
- - In `mc-scripts`, the `build` command additionally compiles the `index.html` by default.
12
- - Running the `compile-html` command by default should not be necessary anymore. However, you can pass `--build-only` to the `build` command to opt-out of the compilation step, in case you want to run it separately, for example to use the `--transformer`.
13
- - Running the `compile-html` command by default does not print to `stdout` the JSON string with the security headers. You can opt into the old behavior by passing the `--print-security-headers` option.
14
- - The `--inline-csp` of `compile-html` has been dropped, as it's now the built-in behavior.
15
- - The `dist` folder created by the `build` command has been removed. Instead, the `build` command writes the production bundles directly into the `public` folder.
16
-
17
- For more information see [Release notes v21](https://docs.commercetools.com/custom-applications/releases/2022-01-31-custom-applications-v21).
18
-
19
- ### Patch Changes
20
-
21
- - [#2430](https://github.com/commercetools/merchant-center-application-kit/pull/2430) [`bb1f7d75`](https://github.com/commercetools/merchant-center-application-kit/commit/bb1f7d75ff54f7fef05c4d2b3328b88e400b4867) Thanks [@emmenko](https://github.com/emmenko)! - Use version range for Babel packages.
22
-
23
- ## 21.0.0-rc.1
24
-
25
- ### Patch Changes
26
-
27
- - [#2430](https://github.com/commercetools/merchant-center-application-kit/pull/2430) [`5ea8baf1`](https://github.com/commercetools/merchant-center-application-kit/commit/5ea8baf1b2ca2661aac9a6a572d2c8e596ee0b2c) Thanks [@emmenko](https://github.com/emmenko)! - Use version range for Babel packages.
28
-
29
- ## 21.0.0-rc.0
30
-
31
- ### Major Changes
32
-
33
- - [#2430](https://github.com/commercetools/merchant-center-application-kit/pull/2430) [`1c363fad`](https://github.com/commercetools/merchant-center-application-kit/commit/1c363fad7ab770a739ac8080358e41ae4af42074) Thanks [@emmenko](https://github.com/emmenko)! - Drop Node.js `v12`. Recommended min Node.js version is `v14` or `v16`.
34
-
35
- * [#2430](https://github.com/commercetools/merchant-center-application-kit/pull/2430) [`07f5b00f`](https://github.com/commercetools/merchant-center-application-kit/commit/07f5b00f3045a3e30462a1150e6ba85fcecc9098) Thanks [@emmenko](https://github.com/emmenko)! - Following breaking changes were introduced:
36
-
37
- - In `mc-scripts`, the `build` command additionally compiles the `index.html` by default.
38
- - Running the `compile-html` command by default should not be necessary anymore. However, you can pass `--build-only` to the `build` command to opt-out of the compilation step, in case you want to run it separately, for example to use the `--transformer`.
39
- - Running the `compile-html` command by default does not print to `stdout` the JSON string with the security headers. You can opt into the old behavior by passing the `--print-security-headers` option.
40
- - The `--inline-csp` of `compile-html` has been dropped, as it's now the built-in behavior.
41
- - The `dist` folder created by the `build` command has been removed. Instead, the `build` command writes the production bundles directly into the `public` folder.
42
-
43
- For more information see [Release notes v21](https://docs.commercetools.com/custom-applications/releases/2022-01-31-custom-applications-v21).
44
-
45
- ## 20.10.6
46
-
47
- ### Patch Changes
48
-
49
- - [#2386](https://github.com/commercetools/merchant-center-application-kit/pull/2386) [`d7fcf6fc`](https://github.com/commercetools/merchant-center-application-kit/commit/d7fcf6fc8495d4eae68e0a4f4c1f1b3e0e394454) Thanks [@emmenko](https://github.com/emmenko)! - Upgrade to Yarn v3
50
-
51
- ## 20.10.3
52
-
53
- ### Patch Changes
54
-
55
- - [#2376](https://github.com/commercetools/merchant-center-application-kit/pull/2376) [`9d879503`](https://github.com/commercetools/merchant-center-application-kit/commit/9d879503f7af467729291d66a35625b6e7cbb385) Thanks [@emmenko](https://github.com/emmenko)! - > For commercetools only.
56
-
57
- Allow to use OIDC login when developing against a local running MC API.
58
-
59
- ## 20.10.1
60
-
61
- ### Patch Changes
62
-
63
- - [#2356](https://github.com/commercetools/merchant-center-application-kit/pull/2356) [`e34fe076`](https://github.com/commercetools/merchant-center-application-kit/commit/e34fe076aab6681cdcc54622d84123f2c22020e6) Thanks [@ByronDWall](https://github.com/ByronDWall)! - set node version to 16.8 in nvmrc to avoid a bug in node/v8
64
-
65
- ## 19.0.0
66
-
67
- ### Major Changes
68
-
69
- - [#2041](https://github.com/commercetools/merchant-center-application-kit/pull/2041) [`a240f657`](https://github.com/commercetools/merchant-center-application-kit/commit/a240f6574a9240a2ac82febb67b0f6c814db979f) Thanks [@emmenko](https://github.com/emmenko)! - - Changes required Node.js engine version to `>=12 || >=14` in `package.json`.
70
-
71
- * [#2041](https://github.com/commercetools/merchant-center-application-kit/pull/2041) [`a240f657`](https://github.com/commercetools/merchant-center-application-kit/commit/a240f6574a9240a2ac82febb67b0f6c814db979f) Thanks [@emmenko](https://github.com/emmenko)! - Upgrade and migrate packages to use `ui-kit@v12`
72
-
73
- ## 18.5.4
74
-
75
- ### Patch Changes
76
-
77
- - [`d44f5b69`](https://github.com/commercetools/merchant-center-application-kit/commit/d44f5b6916c3897ce198eb06757d29d40535b8d4) [#2076](https://github.com/commercetools/merchant-center-application-kit/pull/2076) Thanks [@tdeekens](https://github.com/tdeekens)! - refactor: to remove lerna and only use many-pkg
78
-
79
- ## 18.5.2
80
-
81
- ### Patch Changes
82
-
83
- - [`7f26c54e`](https://github.com/commercetools/merchant-center-application-kit/commit/7f26c54e55eff8aeac786ec0d011d36e40b0d263) [#2066](https://github.com/commercetools/merchant-center-application-kit/pull/2066) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update all dependencies
84
-
85
- ## 18.1.0
86
-
87
- ### Patch Changes
88
-
89
- - [`3bf32993`](https://github.com/commercetools/merchant-center-application-kit/commit/3bf329935a109a73a7c33580fdf618e60fdbcc2c) [#1971](https://github.com/commercetools/merchant-center-application-kit/pull/1971) Thanks [@tdeekens](https://github.com/tdeekens)! - Add internal opt-in support for combining feature flag adapters.
90
-
91
- ## 17.3.0
92
-
93
- ### Patch Changes
94
-
95
- - [`71c9111`](https://github.com/commercetools/merchant-center-application-kit/commit/71c9111308832009d1a27e91e4f2d2da4c53367c) [#1866](https://github.com/commercetools/merchant-center-application-kit/pull/1866) Thanks [@emmenko](https://github.com/emmenko)! - Update to uikit v10.39.8
96
-
97
- ## 17.2.0
98
-
99
- ### Patch Changes
100
-
101
- - [`e0ec004`](https://github.com/commercetools/merchant-center-application-kit/commit/e0ec004d611f93b24f015120d09f6f18389b219f) [#1854](https://github.com/commercetools/merchant-center-application-kit/pull/1854) Thanks [@emmenko](https://github.com/emmenko)! - chore: update deps
102
-
103
- ## 17.0.0
104
-
105
- ### Major Changes
106
-
107
- - [`e706232`](https://github.com/commercetools/merchant-center-application-kit/commit/e706232c152f3fed9cf44c10a0c4f25b27448a16) [#1805](https://github.com/commercetools/merchant-center-application-kit/pull/1805) Thanks [@emmenko](https://github.com/emmenko)! - Remove `mc-scripts extract-intl` command in favor of the official `@formatjs/cli` package.
108
- We recommend to update your script to extract Intl messages to use the `formatjs extract` command.
109
-
110
- See full release notes: https://docs.commercetools.com/custom-applications/releases/2020-10-14-custom-applications-v17
111
-
112
- * [`633d8c7`](https://github.com/commercetools/merchant-center-application-kit/commit/633d8c7b8ddc2f25128d8249579b7bb287a62e30) [#1805](https://github.com/commercetools/merchant-center-application-kit/pull/1805) Thanks [@emmenko](https://github.com/emmenko)! - Remove the CLI flag `--use-local-assets`. The default behavior of `mc-scripts compile-html` now is to compile the assets locally, which is the only reasonable thing to do.
113
-
114
- Furthermore, the `@commercetools-frontend/mc-http-server` package has been deprecated and won't be published anymore.
115
- With the `compile-html` command there is no need to have a pre-configured HTTP server anymore.
116
-
117
- When running the `mc-scripts compile-html` command, the `index.html` is compiled for production usage and it lives in the `public` folder, together with the other static assets. This is all you need to deploy your application.
118
- You can decide to [deploy the Custom Application statically to one of the popular cloud providers](https://docs.commercetools.com/custom-applications/deployment/compiling-a-custom-application#deployment), or serve the files on your own using a static server.
119
-
120
- For example, to run locally the Custom Application using the production bundles:
121
-
122
- ```console
123
- NODE_ENV=production MC_APP_ENV=development dotenv -- \
124
- mc-scripts compile-html \
125
- --transformer @commercetools-frontend/mc-dev-authentication/transformer-local.js
126
-
127
- mc-scripts serve
128
- ```
129
-
130
- ## 16.15.2
131
-
132
- ### Patch Changes
133
-
134
- - [`77eb38a`](https://github.com/commercetools/merchant-center-application-kit/commit/77eb38ace68e7f519dea9deda487ed4c612091a5) [#1641](https://github.com/commercetools/merchant-center-application-kit/pull/1641) Thanks [@emmenko](https://github.com/emmenko)! - Unify login/logout dev routes for http servers
135
-
136
- ## 16.9.1
137
-
138
- ### Patch Changes
139
-
140
- - [`f92ec54`](https://github.com/commercetools/merchant-center-application-kit/commit/f92ec54e78edb668e8dff53342e8542e96d8c319) [#1551](https://github.com/commercetools/merchant-center-application-kit/pull/1551) Thanks [@renovate](https://github.com/apps/renovate)! - chore(deps): update all dependencies
141
-
142
- ## 16.8.8
143
-
144
- ### Patch Changes
145
-
146
- - [`8600676`](https://github.com/commercetools/merchant-center-application-kit/commit/86006764f9fb75d82ffb01bcc7f14c912c61b698) [#1539](https://github.com/commercetools/merchant-center-application-kit/pull/1539) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency pug to v3
147
-
148
- ## 16.8.6
149
-
150
- ### Patch Changes
151
-
152
- - [`9391762`](https://github.com/commercetools/merchant-center-application-kit/commit/939176298df3558970a267b6e6478051a355ffae) [#1530](https://github.com/commercetools/merchant-center-application-kit/pull/1530) Thanks [@emmenko](https://github.com/emmenko)! - Update `@commercetools-uikit/*` packages to `10.21.0`
153
-
154
- ## 16.8.1
155
-
156
- ### Patch Changes
157
-
158
- - [`4c15deb`](https://github.com/commercetools/merchant-center-application-kit/commit/4c15deb750a652291bd0eeb30866198c7ab040ec) [#1487](https://github.com/commercetools/merchant-center-application-kit/pull/1487) Thanks [@tdeekens](https://github.com/tdeekens)! - Fix link to `/login` to preserve url query parameters such as `redirectTo`.
package/config/index.js DELETED
@@ -1,3 +0,0 @@
1
- module.exports = {
2
- viewEngine: 'pug',
3
- };
package/index.js DELETED
@@ -1,13 +0,0 @@
1
- const path = require('path');
2
- const middlewares = require('./middlewares');
3
- const routes = require('./routes');
4
- const config = require('./config');
5
-
6
- const views = path.join(__dirname, 'views');
7
-
8
- module.exports = {
9
- config,
10
- middlewares,
11
- routes,
12
- views,
13
- };
@@ -1,12 +0,0 @@
1
- const createLoginMiddleware = (env) => (request, response, next) => {
2
- if (
3
- String(env.disableAuthRoutesOfDevServer) === 'true' ||
4
- env.servedByProxy
5
- ) {
6
- next();
7
- } else {
8
- response.render('login', { env });
9
- }
10
- };
11
-
12
- module.exports = createLoginMiddleware;
@@ -1,16 +0,0 @@
1
- const { logout } = require('../routes');
2
-
3
- const createLogoutMiddleware = (env) => (request, response, next) => {
4
- logout(response);
5
-
6
- if (
7
- String(env.disableAuthRoutesOfDevServer) === 'true' ||
8
- env.servedByProxy
9
- ) {
10
- next();
11
- } else {
12
- response.render('logout', { env });
13
- }
14
- };
15
-
16
- module.exports = createLogoutMiddleware;
@@ -1,7 +0,0 @@
1
- const createLoginMiddleware = require('./create-login-middleware');
2
- const createLogoutMiddleware = require('./create-logout-middleware');
3
-
4
- module.exports = {
5
- createLoginMiddleware,
6
- createLogoutMiddleware,
7
- };
package/routes/index.js DELETED
@@ -1,5 +0,0 @@
1
- const logout = require('./logout');
2
-
3
- module.exports = {
4
- logout,
5
- };
package/routes/logout.js DELETED
@@ -1,16 +0,0 @@
1
- module.exports = (response, additionalCookieParameters = []) => {
2
- // NOTE: removing the cookie only works if your are running the MC API
3
- // locally, otherwise the cookie won't get removed as it's set to a
4
- // proper domain (e.g. commercetools.com), which we can't unset from localhost.
5
- response.setHeader(
6
- 'Set-Cookie',
7
- [
8
- `mcAccessToken=''`, // <-- unset the value
9
- 'Path=/',
10
- `Expires=${new Date(0).toUTCString()}`, // <-- put a date in the past
11
- 'HttpOnly',
12
- ]
13
- .concat(additionalCookieParameters)
14
- .join('; ')
15
- );
16
- };
package/views/login.css DELETED
@@ -1,78 +0,0 @@
1
- html,
2
- body {
3
- font: 1em sans-serif;
4
- padding: 0;
5
- margin: 0;
6
- height: 100vh;
7
- width: 100vw;
8
- }
9
-
10
- body {
11
- display: flex;
12
- flex-direction: column;
13
- justify-content: flex-start;
14
- align-items: center;
15
- margin-top: 32px;
16
- }
17
-
18
- body > * + * {
19
- margin-top: 32px;
20
- }
21
-
22
- .title {
23
- width: 355px;
24
- }
25
-
26
- form {
27
- display: flex;
28
- flex-direction: column;
29
- width: 355px;
30
- }
31
-
32
- form > * + * {
33
- margin: 16px 0 0;
34
- }
35
-
36
- .field {
37
- border: 0;
38
- }
39
-
40
- .field > * + * {
41
- margin: 8px 0 0;
42
- }
43
-
44
- label {
45
- display: block;
46
- }
47
-
48
- input {
49
- width: 100%;
50
- height: 24px;
51
- outline: none;
52
- }
53
-
54
- input:focus {
55
- border: 1px solid cornflowerblue;
56
- }
57
-
58
- input:focus:invalid {
59
- border-color: red;
60
- }
61
-
62
- abbr {
63
- text-decoration: none;
64
- color: orangered;
65
- }
66
-
67
- #errors > div {
68
- background-color: red;
69
- color: #eee;
70
- padding: 8px;
71
- border-radius: 4px;
72
- }
73
-
74
- .info {
75
- background-color: #b5e1fd;
76
- padding: 8px;
77
- border-radius: 4px;
78
- }
package/views/login.js DELETED
@@ -1,91 +0,0 @@
1
- /* eslint-disable no-var,vars-on-top */
2
- /**
3
- * NOTE:
4
- * This code is only used in development mode.
5
- * It authenticates a developer using the same mechanisms
6
- * as when not running in development. However,
7
- * this runs on the same domain as the developer.
8
- */
9
- window.addEventListener('load', function loaded() {
10
- var form = document.getElementById('login');
11
- form.addEventListener('submit', function onSubmit(event) {
12
- event.preventDefault();
13
- authorize();
14
- });
15
-
16
- function authorize() {
17
- var data = new FormData(form);
18
- var payload = {
19
- email: data.get('email'),
20
- password: data.get('password'),
21
- };
22
-
23
- var queryParams = new URLSearchParams(window.location.search);
24
- if (queryParams.has('response_type')) {
25
- // OIDC params
26
- payload.client_id = queryParams.get('client_id');
27
- payload.response_type = queryParams.get('response_type');
28
- payload.scope = queryParams.get('scope');
29
- payload.state = queryParams.get('state');
30
- payload.nonce = queryParams.get('nonce');
31
- }
32
-
33
- var container = document.getElementById('errors');
34
- // Clean up error message elements
35
- while (container.firstChild) {
36
- container.removeChild(container.firstChild);
37
- }
38
-
39
- const url = data.get('url');
40
-
41
- window
42
- .fetch(url, {
43
- method: 'POST',
44
- headers: {
45
- Accept: 'application/json',
46
- 'Content-Type': 'application/json',
47
- },
48
- credentials: 'include',
49
- body: JSON.stringify(payload),
50
- })
51
- .then(function handleResponse(response) {
52
- if (response.ok) {
53
- return response.json().then(function onSuccess(result) {
54
- // Handle OIDC redirect.
55
- if (queryParams.has('response_type')) {
56
- window.location.replace(result.redirectTo);
57
- } else {
58
- window.localStorage.setItem('isAuthenticated', true);
59
- var searchParams = new URLSearchParams(window.location.search);
60
- var redirectTo = searchParams.get('redirectTo') || '/';
61
- window.location.replace(redirectTo);
62
- }
63
- });
64
- }
65
- return response.text().then(function onError(responseText) {
66
- var message;
67
- try {
68
- var parsedResponse = JSON.parse(responseText);
69
- message = parsedResponse.message;
70
- } catch (e) {
71
- console.warn(
72
- `Failed to parse error response for ${url}:`,
73
- responseText
74
- );
75
-
76
- message = responseText;
77
- }
78
- var errorMessage = document.createTextNode(message);
79
- var errorContainer = document.createElement('div');
80
- errorContainer.appendChild(errorMessage);
81
- container.appendChild(errorContainer, container);
82
- });
83
- })
84
- .catch(function onNetworkError(error) {
85
- var errorMessage = document.createTextNode(error.message);
86
- var errorContainer = document.createElement('div');
87
- errorContainer.appendChild(errorMessage);
88
- container.appendChild(errorContainer, container);
89
- });
90
- }
91
- });
package/views/login.pug DELETED
@@ -1,51 +0,0 @@
1
- html
2
- head
3
- title Login (development only)
4
- style
5
- include login.css
6
- body
7
- div(class="title")
8
- h3 Welcome to the Merchant Center authorization page for local development
9
- small This page is only available in development mode and is necessary to authenticate yourself. In production environment, we use our own authentication service.
10
- form(id="login")
11
- div(id="errors")
12
- div(class="field")
13
- label(for="email") Email
14
- abbr(title="This field is mandatory") *
15
- input(
16
- id="email"
17
- name="email"
18
- type="text"
19
- required
20
- )
21
- div(class="field")
22
- label(for="password") Password
23
- abbr(title="This field is mandatory") *
24
- input(
25
- id="password"
26
- name="password"
27
- type="password"
28
- required
29
- )
30
- input(
31
- id="url"
32
- name="url"
33
- value=env.mcApiUrl.replace(/\/$/, '') + "/tokens"
34
- style="display: none;"
35
- )
36
- div
37
- button(
38
- type="submit"
39
- aria-label="Sign in"
40
- ) ➡ Sign in 🚀
41
-
42
- div(class="info")
43
- small
44
- | Note that Single Sign On is not supported at the moment for the development login page.
45
- | If you are interested in this functionality, let us know and open a
46
- |
47
- a(href="https://github.com/commercetools/merchant-center-application-kit/issues/new/choose" target="_blank" rel="noopener noreferrer") support issue
48
- | .
49
-
50
- script
51
- include login.js
package/views/logout.js DELETED
@@ -1,3 +0,0 @@
1
- window.localStorage.removeItem('isAuthenticated');
2
- window.localStorage.removeItem('loginStrategy');
3
- window.localStorage.removeItem('activeProjectKey');
package/views/logout.pug DELETED
@@ -1,10 +0,0 @@
1
- html
2
- head
3
- title Logout (development only)
4
- script
5
- include logout.js
6
- body
7
- div
8
- h3 This is the logout page for local development.
9
- p Be aware that you might still have an active session as the cookie is assigned to a production domain (e.g. commercetools.com) which we can't unset from localhost. This is only a problem on local development and we intend fix this in the future.
10
- p You can #[a(href="#" onclick="window.location='/login'+window.location.search;") go to the login page] now.