Skip to content

fix: ensure dev settings for url is only visible on dev #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/components/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,13 @@ class App extends Component {
const page = pages[store.modal.page] || {};
const pageLinkHandler = () => this.handlePage(page.link);

if (!store.gotrue) {
return <SiteURLForm onSiteURL={this.handleSiteURL} />;
if (store.isLocal && store.siteURL === null) {
return (
<SiteURLForm
devMode={store.siteURL != null}
onSiteURL={store.siteURL ? this.clearSiteURL : this.handleSiteURL}
/>
);
}
if (!store.settings) {
return;
Expand Down Expand Up @@ -127,7 +132,14 @@ class App extends Component {
{page.link_text}
</button>
)}
<SiteURLForm devMode="true" onSiteURL={this.clearSiteURL} />
{store.isLocal ? (
<SiteURLForm
devMode={store.siteURL != null}
onSiteURL={store.siteURL ? this.clearSiteURL : this.handleSiteURL}
/>
) : (
<div />
)}
</div>
);
}
Expand Down
231 changes: 121 additions & 110 deletions src/netlify-identity.js
Original file line number Diff line number Diff line change
@@ -1,100 +1,104 @@
import { h, render } from "preact"
import { observe } from "mobx"
import { Provider } from "mobx-preact"
import GoTrue from "gotrue-js"
import App from "./components/app"
import store from "./state/store"
import Controls from "./components/controls"
import modalCSS from "./components/modal.css"

const callbacks = {}
import { h, render } from "preact";
import { observe } from "mobx";
import { Provider } from "mobx-preact";
import GoTrue from "gotrue-js";
import App from "./components/app";
import store from "./state/store";
import Controls from "./components/controls";
import modalCSS from "./components/modal.css";

const callbacks = {};
function trigger(callback) {
;(callbacks[callback] || []).forEach((cb) => {
cb.apply(cb, Array.prototype.slice.call(arguments, 1))
})
(callbacks[callback] || []).forEach(cb => {
cb.apply(cb, Array.prototype.slice.call(arguments, 1));
});
}

const validActions = {
login: true,
signup: true,
error: true
}
};

const netlifyIdentity = {
on: (event, cb) => {
callbacks[event] = callbacks[event] || []
callbacks[event].push(cb)
callbacks[event] = callbacks[event] || [];
callbacks[event].push(cb);
},
open: (action) => {
action = action || "login"
open: action => {
action = action || "login";
if (!validActions[action]) {
throw new Error(`Invalid action for open: ${action}`)
throw new Error(`Invalid action for open: ${action}`);
}
store.openModal(store.user ? "user" : action)
store.openModal(store.user ? "user" : action);
},
close: () => {
store.closeModal()
store.closeModal();
},
currentUser: () => {
return store.gotrue && store.gotrue.currentUser()
return store.gotrue && store.gotrue.currentUser();
},
logout: () => {
return store.logout()
return store.logout();
},
get gotrue() {
if (!store.gotrue) {
store.openModal("login")
store.openModal("login");
}
return store.gotrue
return store.gotrue;
},
init: (options) => {
init(options)
init: options => {
init(options);
},
store
}
};

let queuedIframeStyle = null
let queuedIframeStyle = null;
function setStyle(el, css) {
let style = ""
let style = "";
for (const key in css) {
style += `${key}: ${css[key]}; `
style += `${key}: ${css[key]}; `;
}
if (el) {
el.setAttribute("style", style)
el.setAttribute("style", style);
} else {
queuedIframeStyle = style
queuedIframeStyle = style;
}
}

const localHosts = {
localhost: true,
"127.0.0.1": true,
"0.0.0.0": true
}
"0.0.0.0": true,
"identity.netlify.com": true
};

function instantiateGotrue(APIUrl) {
const isLocal = localHosts[document.location.host.split(":").shift()]
const siteURL = isLocal && localStorage.getItem("netlifySiteURL")
const isLocal = localHosts[document.location.host.split(":").shift()];
const siteURL = isLocal && localStorage.getItem("netlifySiteURL");
if (APIUrl) {
return new GoTrue({ APIUrl, setCookie: !isLocal })
return new GoTrue({ APIUrl, setCookie: !isLocal });
}
if (isLocal && siteURL) {
const parts = [siteURL]
const parts = [siteURL];
if (!siteURL.match(/\/$/)) {
parts.push("/")
parts.push("/");
}
parts.push(".netlify/identity")
return new GoTrue({ APIUrl: parts.join(""), setCookie: !isLocal })
parts.push(".netlify/identity");
store.setIsLocal(isLocal);
store.setSiteURL(siteURL);
return new GoTrue({ APIUrl: parts.join(""), setCookie: !isLocal });
}
if (isLocal) {
return null
store.setIsLocal(isLocal);
return null;
}

return new GoTrue({ setCookie: !isLocal })
return new GoTrue({ setCookie: !isLocal });
}

let root
let iframe
let root;
let iframe;
const iframeStyle = {
position: "fixed",
top: 0,
Expand All @@ -106,129 +110,136 @@ const iframeStyle = {
background: "transparent",
display: "none",
"z-index": 99
}
};

observe(store.modal, "isOpen", () => {
if (!store.settings) {
store.loadSettings()
store.loadSettings();
}
setStyle(iframe, {
...iframeStyle,
display: store.modal.isOpen ? "block !important" : "none"
})
});
if (store.modal.isOpen) {
trigger("open", store.modal.page)
trigger("open", store.modal.page);
} else {
trigger("close")
trigger("close");
}
})
});

observe(store, "siteURL", () => {
if (store.siteURL === null || store.siteURL === undefined) {
localStorage.removeItem("netlifySiteURL")
localStorage.removeItem("netlifySiteURL");
} else {
localStorage.setItem("netlifySiteURL", store.siteURL)
localStorage.setItem("netlifySiteURL", store.siteURL);
}
store.init(instantiateGotrue(), true)
})
store.init(instantiateGotrue(), true);
});

observe(store, "user", () => {
if (store.user) {
trigger("login", store.user)
trigger("login", store.user);
} else {
trigger("logout")
trigger("logout");
}
})
});

observe(store, "gotrue", () => {
store.gotrue && trigger("init", store.gotrue.currentUser())
})
store.gotrue && trigger("init", store.gotrue.currentUser());
});

observe(store, "error", () => {
trigger("error", store.error)
})
trigger("error", store.error);
});

const routes = /(confirmation|invite|recovery|email_change)_token=([^&]+)/
const errorRoute = /error=access_denied&error_description=403/
const accessTokenRoute = /access_token=/
const routes = /(confirmation|invite|recovery|email_change)_token=([^&]+)/;
const errorRoute = /error=access_denied&error_description=403/;
const accessTokenRoute = /access_token=/;

function runRoutes() {
const hash = (document.location.hash || "").replace(/^#\/?/, "")
const hash = (document.location.hash || "").replace(/^#\/?/, "");
if (!hash) {
return
return;
}

const m = hash.match(routes)
const m = hash.match(routes);
if (m) {
store.verifyToken(m[1], m[2])
document.location.hash = ""
store.verifyToken(m[1], m[2]);
document.location.hash = "";
}

const em = hash.match(errorRoute)
const em = hash.match(errorRoute);
if (em) {
store.openModal("signup")
document.location.hash = ""
store.openModal("signup");
document.location.hash = "";
}

const am = hash.match(accessTokenRoute)
const am = hash.match(accessTokenRoute);
if (am) {
const params = {}
hash.split("&").forEach((pair) => {
const [key, value] = pair.split("=")
params[key] = value
})
const params = {};
hash.split("&").forEach(pair => {
const [key, value] = pair.split("=");
params[key] = value;
});
if (!!document && params["access_token"]) {
document.cookie = `nf_jwt=${params["access_token"]}`
document.cookie = `nf_jwt=${params["access_token"]}`;
}
document.location.hash = ""
store.openModal("login")
store.completeExternalLogin(params)
document.location.hash = "";
store.openModal("login");
store.completeExternalLogin(params);
}
}

function init(options = {}) {
const { APIUrl, logo = true, namePlaceholder } = options
const controlEls = document.querySelectorAll("[data-netlify-identity-menu],[data-netlify-identity-button]")
Array.prototype.slice.call(controlEls).forEach((el) => {
let controls = null
const mode = el.getAttribute("data-netlify-identity-menu") === null ? "button" : "menu"
const { APIUrl, logo = true, namePlaceholder } = options;
const controlEls = document.querySelectorAll(
"[data-netlify-identity-menu],[data-netlify-identity-button]"
);
Array.prototype.slice.call(controlEls).forEach(el => {
let controls = null;
const mode =
el.getAttribute("data-netlify-identity-menu") === null
? "button"
: "menu";
render(
<Provider store={store}>
<Controls mode={mode} text={el.innerText.trim()} />
</Provider>,
el,
controls
)
})

store.init(instantiateGotrue(APIUrl))
store.modal.logo = logo
store.setNamePlaceholder(namePlaceholder)
iframe = document.createElement("iframe")
iframe.id = "netlify-identity-widget"
);
});

store.init(instantiateGotrue(APIUrl));
store.modal.logo = logo;
store.setNamePlaceholder(namePlaceholder);
iframe = document.createElement("iframe");
iframe.id = "netlify-identity-widget";
iframe.onload = () => {
const styles = iframe.contentDocument.createElement("style")
styles.innerHTML = modalCSS.toString()
iframe.contentDocument.head.appendChild(styles)
const styles = iframe.contentDocument.createElement("style");
styles.innerHTML = modalCSS.toString();
iframe.contentDocument.head.appendChild(styles);
root = render(
<Provider store={store}>
<App />
</Provider>,
iframe.contentDocument.body,
root
)
runRoutes()
}
setStyle(iframe, iframeStyle)
iframe.src = "about:blank"
const container = options.container ? document.querySelector(options.container) : document.body
container.appendChild(iframe)
);
runRoutes();
};
setStyle(iframe, iframeStyle);
iframe.src = "about:blank";
const container = options.container
? document.querySelector(options.container)
: document.body;
container.appendChild(iframe);
/* There's a certain case where we might have called setStyle before the iframe was ready.
Make sure we take the last style and apply it */
if (queuedIframeStyle) {
iframe.setAttribute("style", queuedIframeStyle)
queuedIframeStyle = null
iframe.setAttribute("style", queuedIframeStyle);
queuedIframeStyle = null;
}
}

export default netlifyIdentity
export default netlifyIdentity;
4 changes: 4 additions & 0 deletions src/state/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ store.loadSettings = action(function loadSettings() {
);
});

store.setIsLocal = action(function setIsLocal(isLocal) {
store.isLocal = isLocal;
});

store.setSiteURL = action(function setSiteURL(url) {
store.siteURL = url;
});
Expand Down