Skip to content

Commit

Permalink
Amélioration de la gestion des users internes dans PostHog (#146)
Browse files Browse the repository at this point in the history
* Improve internal users management

* wip

* clear netlify cache

* remove useless variables

* Fix sitemap exclusioon key

* update posthog script

* Accidental change

* script key

* extract function getCookie
  • Loading branch information
fabienheureux authored Sep 24, 2024
1 parent 547d82f commit afb3d69
Show file tree
Hide file tree
Showing 9 changed files with 396 additions and 308 deletions.
11 changes: 2 additions & 9 deletions gatsby-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,10 @@ const config: GatsbyConfig = {
`gatsby-plugin-react-helmet`,
"gatsby-plugin-use-query-params",
`gatsby-plugin-root-import`,
`gatsby-plugin-sitemap`,
{
resolve: `gatsby-plugin-posthog`,
resolve: `gatsby-plugin-sitemap`,
options: {
apiKey: process.env.POSTHOG_API_KEY,
apiHost: "https://eu.i.posthog.com",
head: true,
isEnabledDevMode: false,
initOptions: {
persistence: "memory",
},
excludes: [`disableposthog`],
},
},
{
Expand Down
35 changes: 35 additions & 0 deletions gatsby-ssr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,41 @@ import React from "react";
import StyleProvider from "./src/components/providers/StyleProviderSSR";
import ReactQueryProvider from "./src/components/providers/ReactQueryProvider";

export const onRenderBody = ({ setHeadComponents, setPostBodyComponents }) => {
const posthogOptions = {
apiKey: process.env.POSTHOG_API_KEY,
apiHost: "https://eu.i.posthog.com",
head: true,
isEnabledDevMode: false,
initOptions: {
persistence: "memory",
},
};
const isEnabled =
process.env.NODE_ENV === "production" || posthogOptions.isEnabledDevMode;
if (!isEnabled) {
console.log("Posthog Analytics not enabled");
return null;
}
const posthogScript = (
<script
key={`posthog-analytics`}
dangerouslySetInnerHTML={{
__html: `
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
posthog.init('${posthogOptions.apiKey}',{api_host:'${posthogOptions.apiKey}', person_profiles: 'identified_only'
})`,
}}
/>
);
if (posthogOptions.head) {
setHeadComponents([posthogScript]);
} else {
setPostBodyComponents([posthogScript]);
}
return null;
};

export const wrapRootElement = ({ element }) => (
<ReactQueryProvider>
<StyleProvider>{element}</StyleProvider>
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@
"gatsby-plugin-manifest": "^5.13.1",
"gatsby-plugin-matomo": "^0.16.3",
"gatsby-plugin-offline": "^6.13.2",
"gatsby-plugin-posthog": "^1.0.1",
"gatsby-plugin-react-helmet": "^6.13.1",
"gatsby-plugin-sitemap": "^6.13.1",
"gatsby-plugin-styled-components": "^6.13.1",
"gatsby-plugin-use-query-params": "^1.0.1",
"gatsby-plugin-web-font-loader": "^1.0.4",
"iframe-resizer": "^4.4.5",
"pigeon-maps": "^0.21.6",
"posthog-js": "^1.160.3",
"query-string": "^7.1.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand Down Expand Up @@ -67,7 +67,7 @@
"webpack-cli": "^5.1.4"
},
"scripts": {
"build": "gatsby clean && yarn iframe && gatsby build",
"build": "yarn clean && yarn iframe && gatsby build",
"clean": "rm -rf ../cache && gatsby clean",
"iframe": "webpack",
"develop": "gatsby develop",
Expand Down
27 changes: 26 additions & 1 deletion src/components/layout/Web.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React, { useState, useEffect } from "react";
import styled from "styled-components";
import posthog from "posthog-js";

import { GlobalStyle } from "utils/styles";
import { getCookie } from "utils/cookies";
import ModalProvider from "components/providers/ModalProvider";
import UXProvider from "components/providers/UXProvider";
import SearchProvider from "components/providers/SearchProvider";
Expand Down Expand Up @@ -45,12 +47,32 @@ const FullScreen = styled.div`
export default function Web(props) {
const [iframe, setIframe] = useState(false);
const [noHeader, setnoHeader] = useState(false);
const [internalUser, setInternalUser] = useState(false);

useEffect(() => {
setIframe(window.location.search.includes("iframe"));
setnoHeader(window.location.search.includes("noheader"));
if (getCookie("disable-posthog", "1")) {
setInternalUser(true);
}
}, []);

useEffect(() => {
posthog.capture("$set", {
$set: {
admin: `${internalUser}`,
},
});
}, [internalUser]);

useEffect(() => {
posthog.capture("$set", {
$set: {
iframe: `${iframe}`,
},
});
}, [iframe]);

return (
<Wrapper>
<Seo title={props.title} />
Expand All @@ -61,7 +83,10 @@ export default function Web(props) {
<ThemeToggle />
<Content>
<FullScreen $iframe={iframe}>
<HeaderWrapper noHeader={noHeader} />
<HeaderWrapper
noHeader={noHeader}
internalUser={internalUser}
/>
{props.children}
<Bin />
</FullScreen>
Expand Down
31 changes: 20 additions & 11 deletions src/components/wrappers/HeaderWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,28 @@ const StyledSearchBar = styled(SearchBar)`
font-size: 0.875rem;
}
`;
export default function HeaderWrapper(props) {

const Disclaimer = styled.div`
background: red;
color: white;
padding: .25rem 1rem;
`;
export default function HeaderWrapper({ noHeader, internalUser }) {
const location = useLocation();
const { isFetched } = useWaste();
return (
<StyledHeader $small={location.pathname !== "/"} $noHeader={props.noHeader}>
{location.pathname !== "/" && (
<Wrapper>
{!props.noHeader && <GifTitle small />}
<SearchBarWrapper $noHeader={props.noHeader}>
<StyledSearchBar isFetched={isFetched} />
</SearchBarWrapper>
</Wrapper>
)}
</StyledHeader>
<>
{internalUser && <Disclaimer>Posthog est désactivé</Disclaimer>}
<StyledHeader $small={location.pathname !== "/"} $noHeader={noHeader}>
{location.pathname !== "/" && (
<Wrapper>
{!noHeader && <GifTitle small />}
<SearchBarWrapper $noHeader={noHeader}>
<StyledSearchBar isFetched={isFetched} />
</SearchBarWrapper>
</Wrapper>
)}
</StyledHeader>
</>
);
}
1 change: 1 addition & 0 deletions src/pages/404.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Web from "components/layout/Web";
import Suggestions from "components/misc/Suggestions";

export default function notfound() {

return (
<Web>
<Suggestions>
Expand Down
17 changes: 17 additions & 0 deletions src/pages/disableposthog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React, { useEffect } from "react";
import { setCookie } from "utils/cookies"
import Web from "components/layout/Web";

export default function Disableposthog() {
useEffect(() => {
setCookie("disable-posthog", "1", 365)
window.location.href = "/"
}, []);

return (
<Web>
Un cookie est en train d'être déposé.
Vous allez être redirigé vers la page d'accueil.
</Web>
);
}
10 changes: 10 additions & 0 deletions src/utils/cookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

export function setCookie(name: string, value: string, days: number) {
const expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${value}; expires=${expirationDate.toUTCString()}; path=/`
}

export function getCookie(name: string, value: string) {
return document.cookie.split("; ").find(row => row === `${name}=${value}`)
}
Loading

0 comments on commit afb3d69

Please sign in to comment.