import { c as createCommonjsModule, u as unwrapExports } from './_commonjsHelpers-0c4b6f40.js';
import './_to-object-a4107da3.js';
import './es6.string.iterator-c990c18c.js';
import './core.get-iterator-method-e1de7503.js';
import './web.dom.iterable-4439f05a.js';
import React__default, { useState, useEffect } from 'react';
import { _ as _slicedToArray } from './slicedToArray-641f241f.js';
import { Form } from 'react-bootstrap';
import { s as styleInject } from './style-inject.es-1f59c1d0.js';

var logger_1 = createCommonjsModule(function (module, exports) {

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var logger = {
  error(code) {
    for (var _len = arguments.length, message = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      message[_key - 1] = arguments[_key];
    }

    console.error("[next-auth][error][".concat(code.toLowerCase(), "]"), "\nhttps://next-auth.js.org/errors#".concat(code.toLowerCase()), ...message);
  },

  warn(code) {
    for (var _len2 = arguments.length, message = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      message[_key2 - 1] = arguments[_key2];
    }

    console.warn("[next-auth][warn][".concat(code.toLowerCase(), "]"), "\nhttps://next-auth.js.org/warnings#".concat(code.toLowerCase()), ...message);
  },

  debug(code) {
    var _process, _process$env;

    if (!((_process = process) !== null && _process !== void 0 && (_process$env = _process.env) !== null && _process$env !== void 0 && _process$env._NEXTAUTH_DEBUG)) return;

    for (var _len3 = arguments.length, message = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
      message[_key3 - 1] = arguments[_key3];
    }

    console.log("[next-auth][debug][".concat(code.toLowerCase(), "]"), ...message);
  }

};
var _default = logger;
exports.default = _default;
});

unwrapExports(logger_1);

var parseUrl_1 = createCommonjsModule(function (module, exports) {

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = parseUrl;

function parseUrl(url) {
  var defaultHost = 'http://localhost:3000';
  var defaultPath = '/api/auth';

  if (!url) {
    url = "".concat(defaultHost).concat(defaultPath);
  }

  var protocol = url.startsWith('http:') ? 'http' : 'https';
  url = url.replace(/^https?:\/\//, '').replace(/\/$/, '');
  var [_host, ..._path] = url.split('/');
  var baseUrl = _host ? "".concat(protocol, "://").concat(_host) : defaultHost;
  var basePath = _path.length > 0 ? "/".concat(_path.join('/')) : defaultPath;
  return {
    baseUrl,
    basePath
  };
}
});

unwrapExports(parseUrl_1);

var client = createCommonjsModule(function (module, exports) {

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getSession = getSession;
exports.signIn = signIn;
exports.signOut = signOut;
exports.default = exports.Provider = exports.useSession = void 0;



var _logger = _interopRequireDefault(logger_1);

var _parseUrl = _interopRequireDefault(parseUrl_1);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

var __NEXTAUTH = {
  baseUrl: (0, _parseUrl.default)(process.env.NEXTAUTH_URL || process.env.VERCEL_URL).baseUrl,
  basePath: (0, _parseUrl.default)(process.env.NEXTAUTH_URL).basePath,
  keepAlive: 0,
  clientMaxAge: 0,
  _clientLastSync: 0,
  _clientSyncTimer: null,
  _eventListenersAdded: false,
  _clientSession: undefined,
  _clientId: Math.random().toString(36).substring(2) + Date.now().toString(36),
  _getSession: () => {}
};

if (typeof window !== 'undefined') {
  if (__NEXTAUTH._eventListenersAdded === false) {
    __NEXTAUTH._eventListenersAdded = true;
    window.addEventListener('storage', function () {
      var _ref = _asyncToGenerator(function* (event) {
        if (event.key === 'nextauth.message') {
          var message = JSON.parse(event.newValue);

          if ((message === null || message === void 0 ? void 0 : message.event) === 'session' && message.data) {
            if (__NEXTAUTH._clientId === message.clientId) {
              return;
            }

            yield __NEXTAUTH._getSession({
              event: 'storage'
            });
          }
        }
      });

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }());
    var hidden, visibilityChange;

    if (typeof document.hidden !== 'undefined') {
      hidden = 'hidden';
      visibilityChange = 'visibilitychange';
    } else if (typeof document.msHidden !== 'undefined') {
      hidden = 'msHidden';
      visibilityChange = 'msvisibilitychange';
    } else if (typeof document.webkitHidden !== 'undefined') {
      hidden = 'webkitHidden';
      visibilityChange = 'webkitvisibilitychange';
    }

    var handleVisibilityChange = () => !document[hidden] && __NEXTAUTH._getSession({
      event: visibilityChange
    });

    document.addEventListener('visibilitychange', handleVisibilityChange, false);
  }
}

var setOptions = function setOptions() {
  var {
    baseUrl,
    basePath,
    clientMaxAge,
    keepAlive
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  if (baseUrl) {
    __NEXTAUTH.baseUrl = baseUrl;
  }

  if (basePath) {
    __NEXTAUTH.basePath = basePath;
  }

  if (clientMaxAge) {
    __NEXTAUTH.clientMaxAge = clientMaxAge;
  }

  if (keepAlive) {
    __NEXTAUTH.keepAlive = keepAlive;

    if (typeof window !== 'undefined' && keepAlive > 0) {
      if (__NEXTAUTH._clientSyncTimer !== null) {
        clearTimeout(__NEXTAUTH._clientSyncTimer);
      }

      __NEXTAUTH._clientSyncTimer = setTimeout(_asyncToGenerator(function* () {
        if (__NEXTAUTH._clientSession) {
          yield __NEXTAUTH._getSession({
            event: 'timer'
          });
        }
      }), keepAlive * 1000);
    }
  }
};

function getSession() {
  return _getSession2.apply(this, arguments);
}

function _getSession2() {
  _getSession2 = _asyncToGenerator(function* () {
    var {
      ctx,
      req = ctx === null || ctx === void 0 ? void 0 : ctx.req,
      triggerEvent = true
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    var baseUrl = _apiBaseUrl();

    var fetchOptions = req ? {
      headers: {
        cookie: req.headers.cookie
      }
    } : {};
    var session = yield _fetchData("".concat(baseUrl, "/session"), fetchOptions);

    if (triggerEvent) {
      _sendMessage({
        event: 'session',
        data: {
          trigger: 'getSession'
        }
      });
    }

    return session;
  });
  return _getSession2.apply(this, arguments);
}

function getCsrfToken() {
  return _getCsrfToken.apply(this, arguments);
}

function _getCsrfToken() {
  _getCsrfToken = _asyncToGenerator(function* () {
    var {
      ctx,
      req = ctx === null || ctx === void 0 ? void 0 : ctx.req
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    var baseUrl = _apiBaseUrl();

    var fetchOptions = req ? {
      headers: {
        cookie: req.headers.cookie
      }
    } : {};
    var data = yield _fetchData("".concat(baseUrl, "/csrf"), fetchOptions);
    return data && data.csrfToken ? data.csrfToken : null;
  });
  return _getCsrfToken.apply(this, arguments);
}

var getProviders = function () {
  var _ref3 = _asyncToGenerator(function* () {
    var baseUrl = _apiBaseUrl();

    return _fetchData("".concat(baseUrl, "/providers"));
  });

  return function getProviders() {
    return _ref3.apply(this, arguments);
  };
}();

var SessionContext = (0, React__default.createContext)();

var useSession = session => {
  var value = (0, React__default.useContext)(SessionContext);

  if (value === undefined) {
    return _useSessionHook(session);
  }

  return value;
};

exports.useSession = useSession;

var _useSessionHook = session => {
  var [data, setData] = (0, React__default.useState)(session);
  var [loading, setLoading] = (0, React__default.useState)(true);
  (0, React__default.useEffect)(() => {
    var _getSession = function () {
      var _ref4 = _asyncToGenerator(function* () {
        var {
          event = null
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        try {
          var triggredByEvent = event !== null;
          var triggeredByStorageEvent = !!(event && event === 'storage');
          var clientMaxAge = __NEXTAUTH.clientMaxAge;
          var clientLastSync = parseInt(__NEXTAUTH._clientLastSync);
          var currentTime = Math.floor(new Date().getTime() / 1000);
          var clientSession = __NEXTAUTH._clientSession;

          if (triggeredByStorageEvent === false && clientSession !== undefined) {
            if (clientMaxAge === 0 && triggredByEvent !== true) {
              return;
            } else if (clientMaxAge > 0 && clientSession === null) {
              return;
            } else if (clientMaxAge > 0 && currentTime < clientLastSync + clientMaxAge) {
              return;
            }
          }

          if (clientSession === undefined) {
            __NEXTAUTH._clientSession = null;
          }

          __NEXTAUTH._clientLastSync = Math.floor(new Date().getTime() / 1000);
          var triggerEvent = triggeredByStorageEvent === false;
          var newClientSessionData = yield getSession({
            triggerEvent
          });
          __NEXTAUTH._clientSession = newClientSessionData;
          setData(newClientSessionData);
          setLoading(false);
        } catch (error) {
          _logger.default.error('CLIENT_USE_SESSION_ERROR', error);
        }
      });

      return function _getSession() {
        return _ref4.apply(this, arguments);
      };
    }();

    __NEXTAUTH._getSession = _getSession;

    _getSession();
  });
  return [data, loading];
};

function signIn(_x2) {
  return _signIn.apply(this, arguments);
}

function _signIn() {
  _signIn = _asyncToGenerator(function* (provider) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var authorizationParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    var {
      callbackUrl = window.location,
      redirect = true
    } = options;

    var baseUrl = _apiBaseUrl();

    var providers = yield getProviders();

    if (!(provider in providers)) {
      window.location = "".concat(baseUrl, "/signin?callbackUrl=").concat(encodeURIComponent(callbackUrl));
      return;
    }

    var isCredentials = providers[provider].type === 'credentials';
    var signInUrl = isCredentials ? "".concat(baseUrl, "/callback/").concat(provider) : "".concat(baseUrl, "/signin/").concat(provider);
    var fetchOptions = {
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams(_objectSpread(_objectSpread({}, options), {}, {
        csrfToken: yield getCsrfToken(),
        callbackUrl,
        json: true
      }))
    };

    var _signInUrl = "".concat(signInUrl, "?").concat(new URLSearchParams(authorizationParams));

    var res = yield fetch(_signInUrl, fetchOptions);
    var data = yield res.json();

    if (redirect || !isCredentials) {
      var _data$url;

      window.location = (_data$url = data.url) !== null && _data$url !== void 0 ? _data$url : callbackUrl;
      return;
    }

    var error = new URL(data.url).searchParams.get('error');

    if (res.ok) {
      yield __NEXTAUTH._getSession({
        event: 'storage'
      });
    }

    return {
      error,
      status: res.status,
      ok: res.ok,
      url: error ? null : data.url
    };
  });
  return _signIn.apply(this, arguments);
}

function signOut() {
  return _signOut.apply(this, arguments);
}

function _signOut() {
  _signOut = _asyncToGenerator(function* () {
    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var {
      callbackUrl = window.location,
      redirect = true
    } = options;

    var baseUrl = _apiBaseUrl();

    var fetchOptions = {
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        csrfToken: yield getCsrfToken(),
        callbackUrl,
        json: true
      })
    };
    var res = yield fetch("".concat(baseUrl, "/signout"), fetchOptions);
    var data = yield res.json();

    _sendMessage({
      event: 'session',
      data: {
        trigger: 'signout'
      }
    });

    if (redirect) {
      var _data$url2;

      window.location = (_data$url2 = data.url) !== null && _data$url2 !== void 0 ? _data$url2 : callbackUrl;
      return;
    }

    yield __NEXTAUTH._getSession({
      event: 'storage'
    });
    return data;
  });
  return _signOut.apply(this, arguments);
}

var Provider = (_ref5) => {
  var {
    children,
    session,
    options
  } = _ref5;
  setOptions(options);
  return (0, React__default.createElement)(SessionContext.Provider, {
    value: useSession(session)
  }, children);
};

exports.Provider = Provider;

var _fetchData = function () {
  var _ref6 = _asyncToGenerator(function* (url) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    try {
      var res = yield fetch(url, options);
      var data = yield res.json();
      return Promise.resolve(Object.keys(data).length > 0 ? data : null);
    } catch (error) {
      _logger.default.error('CLIENT_FETCH_ERROR', url, error);

      return Promise.resolve(null);
    }
  });

  return function _fetchData(_x3) {
    return _ref6.apply(this, arguments);
  };
}();

var _apiBaseUrl = () => {
  if (typeof window === 'undefined') {
    if (!process.env.NEXTAUTH_URL) {
      _logger.default.warn('NEXTAUTH_URL', 'NEXTAUTH_URL environment variable not set');
    }

    return "".concat(__NEXTAUTH.baseUrl).concat(__NEXTAUTH.basePath);
  } else {
    return __NEXTAUTH.basePath;
  }
};

var _sendMessage = message => {
  if (typeof localStorage !== 'undefined') {
    var timestamp = Math.floor(new Date().getTime() / 1000);
    localStorage.setItem('nextauth.message', JSON.stringify(_objectSpread(_objectSpread({}, message), {}, {
      clientId: __NEXTAUTH._clientId,
      timestamp
    })));
  }
};

var _default = {
  getSession,
  getCsrfToken,
  getProviders,
  useSession,
  signIn,
  signOut,
  Provider,
  setOptions,
  options: setOptions,
  session: getSession,
  providers: getProviders,
  csrfToken: getCsrfToken,
  signin: signIn,
  signout: signOut
};
exports.default = _default;
});

unwrapExports(client);
var client_1 = client.getSession;
var client_2 = client.signIn;
var client_3 = client.signOut;
var client_4 = client.Provider;
var client_5 = client.useSession;

var client$1 = client.default;

var css = ".AuthWrapper-module_loginBox__3l-BE {\r\n  margin-bottom: 2rem;\r\n  width: 350px;\r\n  max-width: 90vw;\r\n  margin-left: auto;\r\n  margin-right: auto;\r\n  /* box-shadow: 2px 5px 12px rgba(0, 0, 0, 0.15); */\r\n  background: #fff;\r\n  z-index: 1;\r\n}\r\n.AuthWrapper-module_loginBox_title__12rGD {\r\n  margin-bottom: 2rem;\r\n  text-align: center;\r\n}\r\n.AuthWrapper-module_bar__1dafn {\r\n  background: #eee;\r\n  margin-left: unset;\r\n  margin-right: unset;\r\n}\r\n.AuthWrapper-module_bar__1dafn:nth-child(1) {\r\n  float: left;\r\n  border-right: 1rem solid #fff;\r\n  background: rgb(245, 245, 245);\r\n  height: 10rem;\r\n  width: 25%;\r\n  margin-left: auto;\r\n  margin-right: auto;\r\n  margin-bottom: 2rem;\r\n}\r\n.AuthWrapper-module_bar__1dafn:nth-child(2n) {\r\n  width: 97%;\r\n  height: 1.5rem;\r\n  margin-bottom: 0.25rem;\r\n}\r\n.AuthWrapper-module_bar__1dafn.AuthWrapper-module_bar__1dafn:nth-child(3n) {\r\n  width: 96%;\r\n  height: 1.5rem;\r\n  margin-bottom: 1.5rem;\r\n}\r\n.AuthWrapper-module_bar__1dafn.AuthWrapper-module_bar__1dafn:nth-child(4n) {\r\n  width: 72%;\r\n  height: 1.5rem;\r\n  margin-bottom: 0.25rem;\r\n}\r\n.AuthWrapper-module_bar__1dafn.AuthWrapper-module_bar__1dafn:nth-child(5n) {\r\n  width: 88%;\r\n  height: 1.5rem;\r\n  margin-bottom: 0.25rem;\r\n}\r\n\r\n.AuthWrapper-module_iframe__2wDJW {\r\n  margin-top: -3rem;\r\n  border: none;\r\n  width: 100%;\r\n  height: 1900px;\r\n}";
var styles = { "loginBox": "AuthWrapper-module_loginBox__3l-BE", "loginBox_title": "AuthWrapper-module_loginBox_title__12rGD", "bar": "AuthWrapper-module_bar__1dafn", "iframe": "AuthWrapper-module_iframe__2wDJW" };
styleInject(css);

var AuthWrapper = function AuthWrapper(_ref) {
  var children = _ref.children,
      needAuth = _ref.needAuth,
      _ref$formUrl = _ref.formUrl,
      formUrl = _ref$formUrl === undefined ? '' : _ref$formUrl;

  var _nextAuth$useSession = client$1.useSession(),
      _nextAuth$useSession2 = _slicedToArray(_nextAuth$useSession, 2),
      session = _nextAuth$useSession2[0],
      loading = _nextAuth$useSession2[1];

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      callbackUrl = _useState2[0],
      setCallbackUrl = _useState2[1];

  var _useState3 = useState(),
      _useState4 = _slicedToArray(_useState3, 2),
      email = _useState4[0],
      setEmail = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      showForm = _useState6[0],
      setShowForm = _useState6[1];

  var _useState7 = useState(),
      _useState8 = _slicedToArray(_useState7, 2),
      password = _useState8[0],
      setPassword = _useState8[1];

  useEffect(function () {
    setCallbackUrl(window.location.href);
  }, []);

  if (session || !needAuth) {
    return React__default.createElement(
      'div',
      null,
      children
    );
  }

  if (!loading) {
    return React__default.createElement(
      'div',
      { style: { position: 'relative', minHeight: '300px', paddingTop: '2rem' } },
      callbackUrl && React__default.createElement(
        'div',
        null,
        !showForm && React__default.createElement(
          'div',
          { className: styles.loginBox },
          React__default.createElement(
            'div',
            { className: styles.loginBox_title },
            React__default.createElement(
              'b',
              null,
              'Please log in to view this content.'
            )
          ),
          React__default.createElement(
            Form,
            { onSubmit: function onSubmit(e) {
                return e.preventDefault();
              } },
            React__default.createElement(
              Form.Group,
              { controlId: 'email' },
              React__default.createElement(Form.Control, { type: 'email', onChange: function onChange(e) {
                  return setEmail(e.target.value);
                }, placeholder: 'Email' })
            ),
            React__default.createElement(
              Form.Group,
              { controlId: 'password' },
              React__default.createElement(Form.Control, { type: 'password', onChange: function onChange(e) {
                  return setPassword(e.target.value);
                }, placeholder: 'Password' })
            ),
            React__default.createElement(
              'button',
              { className: 'btn btn-primary btn-block', onClick: function onClick() {
                  return client$1.signIn('credentials', { email: email, password: password, callbackUrl: callbackUrl });
                } },
              'Sign in'
            )
          ),
          React__default.createElement(
            'p',
            { style: { textAlign: 'center' }, className: 'mt-2 mb-0' },
            'Don\'t have an account?',
            ' ',
            React__default.createElement(
              'a',
              { style: { color: 'blue', textDecoration: 'underline' }, onClick: function onClick() {
                  return setShowForm(!showForm);
                } },
              'Click Here'
            ),
            ' to register.'
          ),
          React__default.createElement(
            'p',
            { className: 'mt-1', style: { fontSize: '.8em', textAlign: 'center' } },
            React__default.createElement(
              'em',
              null,
              React__default.createElement(
                'a',
                { href: '/forgotpassword', style: { color: 'blue', textDecoration: 'underline' } },
                'Forgot your password? '
              )
            )
          )
        ),
        showForm && React__default.createElement('iframe', { className: styles.iframe, src: formUrl })
      )
    );
  } else {
    return null;
  }
};

export default AuthWrapper;
