react-native-appwrite-oauth
Version:
React Native component that implements the OAuth2 flow for the Appwrite BaaS. It's based on a Modal implementation
178 lines (172 loc) • 7.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _reactNativeWebview = require("react-native-webview");
var _cookies = _interopRequireDefault(require("@react-native-cookies/cookies"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
// Default layout used by the component. Not to be exposed. Can be overriden.
const DefaultLayout = _ref => {
let {
WebViewComponent,
setLoadingState,
onFailure
} = _ref;
const handleCancel = () => {
setLoadingState(false);
onFailure('User cancelled');
};
return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
style: styles.container
}, /*#__PURE__*/_react.default.createElement(_reactNative.Button, {
title: "Cancel",
onPress: handleCancel
}), /*#__PURE__*/_react.default.createElement(WebViewComponent, null));
};
const successUrl = 'http://localhost/auth/oauth2/success';
const failureUrl = 'http://localhost/auth/oauth2/failure';
const regex = /http:\/\/localhost(.*)?.+key=(.+)?&secret=(.+)/;
const AppwriteOauth = _ref2 => {
let {
account,
authenticating = false,
provider = '',
scopes = [],
cookieData = 'path=/; HttpOnly',
loadingColor = '#206fce',
onSuccess = () => {},
onFailure = () => {},
modalLayout
} = _ref2;
if (!account) {
throw new Error('Missing or invalid Appwrite "account" prop');
}
if (!provider) {
throw new Error('Missing or invalid Appwrite "provider" prop');
}
const [endpoint, setEndpoint] = (0, _react.useState)('');
const [loading, setLoading] = (0, _react.useState)(false);
(0, _react.useEffect)(() => {
if (authenticating) {
const url = account.createOAuth2Session(provider, successUrl, failureUrl, scopes);
setEndpoint(url.toString());
setLoading(true);
}
}, [authenticating, account, provider, scopes]);
// Intercept all requests before navigation happens in order to stop the
// navigation to "localhost", which might not exist, and we don't need to
// navigate there anyways, once we set the cookie we are as good as done
// with the webview in react native
const handleShouldStartLoadWithRequest = (0, _react.useCallback)(request => {
if (!request.url) {
return false;
}
const urlDomain = request.url.split('/').slice(0, 3).join('/');
const sdkDomain = account.client.config.endpoint.split('/').slice(0, 3).join('/');
// If we get into one of our urls, indicate loading, since we are redirecting
// to another state where we will be doing something meaningful. Disable then.
setLoading(urlDomain === sdkDomain || urlDomain === 'http://localhost');
const result = request.url.match(regex);
if (authenticating && result !== null) {
const [,, key, secret] = result;
// Ensures that HttpOnly is included in the cookie data
let cookieString = !cookieData.toLowerCase().includes('httponly') ? `HttpOnly; ${cookieData}` : cookieData;
cookieString = `${key}=${secret}; ${cookieString}`;
_cookies.default.setFromResponse(sdkDomain, cookieString).then(success => {
// This state change will trigger a re-render immediately since it's
// happening outside of a react handler (inside a promise)
setLoading(false);
if (success) {
onSuccess();
} else {
onFailure('Cookie not set');
}
}).catch(error => {
setLoading(false);
onFailure(error.message);
});
// Do not proceed with navigation
return false;
} else {
// Proceed with navigation
return true;
}
}, [account, authenticating, setLoading, onSuccess, onFailure, cookieData]);
const handleError = (0, _react.useCallback)(syntheticEvent => {
const {
nativeEvent
} = syntheticEvent;
setLoading(false);
// WebView errors send back extra error information to the caller
onFailure(nativeEvent.description, nativeEvent);
}, [setLoading, onFailure]);
const setLoadingState = (0, _react.useCallback)(showLoading => setLoading(showLoading), [setLoading]);
let ModalLayout = modalLayout ? modalLayout : DefaultLayout;
// Protects in case the user pases an un-memoized layout as prop
ModalLayout = (0, _react.useMemo)(() => /*#__PURE__*/_react.default.memo(ModalLayout), [ModalLayout]);
// Dynamically create the WebView component, since we need to have it bound
// to this component's props, in order to pass it as a prop itself, i.e. we
// don't know yet where will this be rendered (default layout or outside custom layout)
const WebViewComponent = (0, _react.useCallback)(_ref3 => {
let {
style = {},
...rest
} = _ref3;
return authenticating ? /*#__PURE__*/_react.default.createElement(_reactNativeWebview.WebView, _extends({
style: [styles.fill, style]
}, rest, {
source: {
uri: endpoint
},
onError: handleError,
onShouldStartLoadWithRequest: handleShouldStartLoadWithRequest
})) : null;
}, [endpoint, authenticating, handleError, handleShouldStartLoadWithRequest]);
return /*#__PURE__*/_react.default.createElement(_reactNative.Modal, {
visible: authenticating,
animationType: "slide"
}, /*#__PURE__*/_react.default.createElement(ModalLayout, {
WebViewComponent: WebViewComponent,
onSuccess: onSuccess,
onFailure: onFailure,
setLoadingState: setLoadingState
}), loading ? /*#__PURE__*/_react.default.createElement(_reactNative.View, {
style: styles.loading
}, /*#__PURE__*/_react.default.createElement(_reactNative.ActivityIndicator, {
size: "large",
color: loadingColor
})) : null);
};
const styles = _reactNative.StyleSheet.create({
container: {
flex: 1,
marginTop: _reactNative.Platform.select({
ios: 30,
android: 0
})
},
fill: {
flex: 1,
alignItems: 'stretch',
margin: 0,
padding: 0
},
loading: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
}
});
var _default = /*#__PURE__*/_react.default.memo(AppwriteOauth);
exports.default = _default;
//# sourceMappingURL=index.js.map