UNPKG

2.82 kBJavaScriptView Raw
1"use strict";
2var __importStar = (this && this.__importStar) || function (mod) {
3 if (mod && mod.__esModule) return mod;
4 var result = {};
5 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6 result["default"] = mod;
7 return result;
8};
9var __importDefault = (this && this.__importDefault) || function (mod) {
10 return (mod && mod.__esModule) ? mod : { "default": mod };
11};
12Object.defineProperty(exports, "__esModule", { value: true });
13const React = __importStar(require("react"));
14const universal_cookie_1 = __importDefault(require("universal-cookie"));
15const exenv_1 = __importDefault(require("exenv"));
16const MEDIUM_USER_ID = require('../config/driver').keyMediumId;
17exports.isLoggedIn = () => {
18 const val = new universal_cookie_1.default().get(MEDIUM_USER_ID);
19 //console.log("forceLogin: ",val);
20 return val !== undefined;
21};
22const attach_request_1 = require("../../src/shared/components/attach-request");
23//req.headers.cookie
24// create a context with the default value: empty
25const LoggedInContext = React.createContext(undefined);
26/**
27 * implements [[RequireServerRenderingSpec]]
28 *
29 * the ForceLogin Component is a HOC that passes the userid to its child components
30 * the forceLogin gets the cookie value regardless on whether it runs on the server or in the browser
31 * see: https://www.npmjs.com/package/universal-cookie
32 *
33 * see hocs with context: https://itnext.io/combining-hocs-with-the-new-reacts-context-api-9d3617dccf0b
34 *
35 * how to check whether running on server or in browser: https://www.npmjs.com/package/exenv
36 */
37class ForceLogin extends React.Component {
38 /**
39 * When we run in the browser: if not logged in, then make the page reload from the server to
40 * make the login-middlewares apply
41 */
42 componentDidMount() {
43 if (!exports.isLoggedIn()) {
44 window.location.reload();
45 }
46 }
47 render() {
48 // we provide the information which user is logged in
49 return React.createElement(LoggedInContext.Provider, { value: exenv_1.default.canUseDOM ?
50 new universal_cookie_1.default().get(MEDIUM_USER_ID) :
51 new universal_cookie_1.default(this.props.request.headers.cookie).get(MEDIUM_USER_ID) }, this.props.children);
52 }
53}
54/**
55 * Pass the information on whether the user `isLoggedIn` as prop to the component
56 * @param Component
57 * @returns {function(any): any}
58 */
59function withUserId(Component) {
60 return function WrapperComponent(props) {
61 return (React.createElement(LoggedInContext.Consumer, null, value => React.createElement(Component, Object.assign({}, props, { userId: value }))));
62 };
63}
64exports.withUserId = withUserId;
65exports.default = attach_request_1.withRequest(ForceLogin);
66//# sourceMappingURL=force-login.js.map
\No newline at end of file