Skip to content

Commit

Permalink
Merge abba9a8 into 9a68c27
Browse files Browse the repository at this point in the history
  • Loading branch information
MrOrz committed Nov 29, 2021
2 parents 9a68c27 + abba9a8 commit a73bfa5
Show file tree
Hide file tree
Showing 6 changed files with 32,205 additions and 46 deletions.
11 changes: 11 additions & 0 deletions components/AppLayout/AppLayout.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import UpgradeDialog from './UpgradeDialog';
import { useLazyQuery } from '@apollo/react-hooks';
import LoginModal from './LoginModal';
import fetchAPI from 'lib/fetchAPI';
import { blockUserBrowserAndRefreshIfNeeded } from 'lib/isUserBlocked';
import Snackbar from '@material-ui/core/Snackbar';

const USER_QUERY = gql`
query AppLayoutQuery {
GetUser {
...AppSidebarUserData
...AppHeaderUserData
blockedReason
}
}
${AppSidebar.fragments.AppSidebarUserData}
Expand Down Expand Up @@ -73,6 +75,15 @@ function AppLayout({ children, container = true }) {
};
}, []);

// Mark blocked user's browser with cookie
//
const hasBlockedReason = !!data?.GetUser?.blockedReason;
useEffect(() => {
if (hasBlockedReason) {
blockUserBrowserAndRefreshIfNeeded();
}
}, [hasBlockedReason]);

return (
<Fragment>
<AppHeader
Expand Down
52 changes: 52 additions & 0 deletions lib/isUserBlocked.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Utility for user blocking mechanism.
* See: https://g0v.hackmd.io/rf0A7MRfTOC613QZmFehQA#User-Blocking
*/

import React, { useContext } from 'react';
import Cookies from 'js-cookie';

const COOKIE_KEY = 'isUserBlocked';
const COOKIE_TRUE_VALUE = '1';
const isUserBlockedContext = React.createContext(false);

/**
* The context provider for decendents to read if the current browser belongs to a blocked user.
* It reads from an independent cookie so that it remains true even after the blocked user is logged
* out.
*
* @param {Object} props
* @param {Object?} props.serverSideCookie - the cookie from server side, set by _document.js
* @returns {React.Provider<boolean>}
*/
export function IsUserBlockedProvider({ serverSideCookie, children }) {
const { Provider } = isUserBlockedContext;
const cookieValue = serverSideCookie
? serverSideCookie[COOKIE_KEY]
: Cookies.get(COOKIE_KEY);

return (
<Provider value={cookieValue === COOKIE_TRUE_VALUE}>{children}</Provider>
);
}

/**
* Reads from IsUserBlockedProvider
* @returns {boolean}
*/
export function useIsUserBlocked() {
return useContext(isUserBlockedContext);
}

/**
* Set cookie when we know this browser is blocked, if not set previously.
*
* After we set cookie, reload the page to update the server-rendered UI.
*/
export function blockUserBrowserAndRefreshIfNeeded() {
// No-op if cookie is already set
if (Cookies.get(COOKIE_KEY) === COOKIE_TRUE_VALUE) return;

Cookies.set(COOKIE_KEY, COOKIE_TRUE_VALUE);
location.reload();
}

0 comments on commit a73bfa5

Please sign in to comment.