UNPKG

react-native-appwrite-oauth

Version:

React Native component that implements the OAuth2 flow for the Appwrite BaaS. It's based on a Modal implementation

168 lines (163 loc) 6.21 kB
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); } import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { Modal, View, Button, Platform, StyleSheet, ActivityIndicator } from 'react-native'; import { WebView } from 'react-native-webview'; import CookieManager from '@react-native-cookies/cookies'; // 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.createElement(View, { style: styles.container }, /*#__PURE__*/React.createElement(Button, { title: "Cancel", onPress: handleCancel }), /*#__PURE__*/React.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] = useState(''); const [loading, setLoading] = useState(false); 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 = 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}`; CookieManager.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 = 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 = useCallback(showLoading => setLoading(showLoading), [setLoading]); let ModalLayout = modalLayout ? modalLayout : DefaultLayout; // Protects in case the user pases an un-memoized layout as prop ModalLayout = useMemo(() => /*#__PURE__*/React.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 = useCallback(_ref3 => { let { style = {}, ...rest } = _ref3; return authenticating ? /*#__PURE__*/React.createElement(WebView, _extends({ style: [styles.fill, style] }, rest, { source: { uri: endpoint }, onError: handleError, onShouldStartLoadWithRequest: handleShouldStartLoadWithRequest })) : null; }, [endpoint, authenticating, handleError, handleShouldStartLoadWithRequest]); return /*#__PURE__*/React.createElement(Modal, { visible: authenticating, animationType: "slide" }, /*#__PURE__*/React.createElement(ModalLayout, { WebViewComponent: WebViewComponent, onSuccess: onSuccess, onFailure: onFailure, setLoadingState: setLoadingState }), loading ? /*#__PURE__*/React.createElement(View, { style: styles.loading }, /*#__PURE__*/React.createElement(ActivityIndicator, { size: "large", color: loadingColor })) : null); }; const styles = StyleSheet.create({ container: { flex: 1, marginTop: 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' } }); export default /*#__PURE__*/React.memo(AppwriteOauth); //# sourceMappingURL=index.js.map