chore: migrate AuthenticationWebView to hooks (#5054)
* chore: migrate AuthenticationWebView to hooks * minor tweak * remove navigation, tweak at useRoute --------- Co-authored-by: GleidsonDaniel <gleidson10daniel@hotmail.com>
This commit is contained in:
parent
3cf08c29e1
commit
c0660db06d
|
@ -1,4 +1,4 @@
|
||||||
import { useDebouncedCallback } from 'use-debounce';
|
import { useDebouncedCallback, Options } from 'use-debounce';
|
||||||
|
|
||||||
export function debounce(func: Function, wait?: number, immediate?: boolean) {
|
export function debounce(func: Function, wait?: number, immediate?: boolean) {
|
||||||
let timeout: ReturnType<typeof setTimeout> | null;
|
let timeout: ReturnType<typeof setTimeout> | null;
|
||||||
|
@ -24,6 +24,6 @@ export function debounce(func: Function, wait?: number, immediate?: boolean) {
|
||||||
return _debounce;
|
return _debounce;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDebounce(func: (...args: any) => any, wait?: number): (...args: any[]) => void {
|
export function useDebounce(func: (...args: any) => any, wait?: number, options?: Options): (...args: any[]) => void {
|
||||||
return useDebouncedCallback(func, wait || 1000);
|
return useDebouncedCallback(func, wait || 1000, options);
|
||||||
}
|
}
|
||||||
|
|
|
@ -50,11 +50,7 @@ const OutsideStackModal = () => {
|
||||||
screenOptions={{ ...defaultHeader, ...themedHeader(theme), ...ModalAnimation, presentation: 'transparentModal' }}
|
screenOptions={{ ...defaultHeader, ...themedHeader(theme), ...ModalAnimation, presentation: 'transparentModal' }}
|
||||||
>
|
>
|
||||||
<OutsideModal.Screen name='OutsideStack' component={OutsideStack} options={{ headerShown: false }} />
|
<OutsideModal.Screen name='OutsideStack' component={OutsideStack} options={{ headerShown: false }} />
|
||||||
<OutsideModal.Screen
|
<OutsideModal.Screen name='AuthenticationWebView' component={AuthenticationWebView} />
|
||||||
name='AuthenticationWebView'
|
|
||||||
component={AuthenticationWebView}
|
|
||||||
options={AuthenticationWebView.navigationOptions}
|
|
||||||
/>
|
|
||||||
</OutsideModal.Navigator>
|
</OutsideModal.Navigator>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,20 +1,20 @@
|
||||||
import React from 'react';
|
|
||||||
import { WebView, WebViewNavigation } from 'react-native-webview';
|
|
||||||
import { connect } from 'react-redux';
|
|
||||||
import parse from 'url-parse';
|
|
||||||
import { StackNavigationProp } from '@react-navigation/stack';
|
|
||||||
import { WebViewMessage } from 'react-native-webview/lib/WebViewTypes';
|
|
||||||
import { RouteProp } from '@react-navigation/core';
|
import { RouteProp } from '@react-navigation/core';
|
||||||
|
import { useNavigation, useRoute } from '@react-navigation/native';
|
||||||
|
import { StackNavigationProp } from '@react-navigation/stack';
|
||||||
|
import React, { useLayoutEffect, useState } from 'react';
|
||||||
|
import { WebView, WebViewNavigation } from 'react-native-webview';
|
||||||
|
import { WebViewMessage } from 'react-native-webview/lib/WebViewTypes';
|
||||||
|
import parse from 'url-parse';
|
||||||
|
|
||||||
import { OutsideModalParamList } from '../stacks/types';
|
|
||||||
import StatusBar from '../containers/StatusBar';
|
|
||||||
import ActivityIndicator from '../containers/ActivityIndicator';
|
import ActivityIndicator from '../containers/ActivityIndicator';
|
||||||
import { TSupportedThemes, withTheme } from '../theme';
|
|
||||||
import { userAgent } from '../lib/constants';
|
|
||||||
import { debounce } from '../lib/methods/helpers';
|
|
||||||
import * as HeaderButton from '../containers/HeaderButton';
|
import * as HeaderButton from '../containers/HeaderButton';
|
||||||
|
import StatusBar from '../containers/StatusBar';
|
||||||
|
import { ICredentials } from '../definitions';
|
||||||
|
import { userAgent } from '../lib/constants';
|
||||||
|
import { useAppSelector } from '../lib/hooks';
|
||||||
|
import { useDebounce } from '../lib/methods/helpers';
|
||||||
import { Services } from '../lib/services';
|
import { Services } from '../lib/services';
|
||||||
import { IApplicationState, ICredentials } from '../definitions';
|
import { OutsideModalParamList } from '../stacks/types';
|
||||||
|
|
||||||
// iframe uses a postMessage to send the token to the client
|
// iframe uses a postMessage to send the token to the client
|
||||||
// We'll handle this sending the token to the hash of the window.location
|
// We'll handle this sending the token to the hash of the window.location
|
||||||
|
@ -40,95 +40,56 @@ window.addEventListener('popstate', function() {
|
||||||
});
|
});
|
||||||
`;
|
`;
|
||||||
|
|
||||||
interface INavigationOption {
|
const AuthenticationWebView = () => {
|
||||||
navigation: StackNavigationProp<OutsideModalParamList, 'AuthenticationWebView'>;
|
const [logging, setLogging] = useState(false);
|
||||||
route: RouteProp<OutsideModalParamList, 'AuthenticationWebView'>;
|
const [loading, setLoading] = useState(false);
|
||||||
}
|
|
||||||
|
|
||||||
interface IAuthenticationWebView extends INavigationOption {
|
const navigation = useNavigation<StackNavigationProp<OutsideModalParamList, 'AuthenticationWebView'>>();
|
||||||
server: string;
|
const {
|
||||||
Accounts_Iframe_api_url: string;
|
params: { authType, url, ssoToken }
|
||||||
Accounts_Iframe_api_method: string;
|
} = useRoute<RouteProp<OutsideModalParamList, 'AuthenticationWebView'>>();
|
||||||
theme: TSupportedThemes;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IState {
|
const { Accounts_Iframe_api_method, Accounts_Iframe_api_url, server } = useAppSelector(state => ({
|
||||||
logging: boolean;
|
server: state.server.server,
|
||||||
loading: boolean;
|
Accounts_Iframe_api_url: state.settings.Accounts_Iframe_api_url as string,
|
||||||
}
|
Accounts_Iframe_api_method: state.settings.Accounts_Iframe_api_method as string
|
||||||
|
}));
|
||||||
|
|
||||||
class AuthenticationWebView extends React.PureComponent<IAuthenticationWebView, IState> {
|
const oauthRedirectRegex = new RegExp(`(?=.*(${server}))(?=.*(credentialToken))(?=.*(credentialSecret))`, 'g');
|
||||||
private oauthRedirectRegex: RegExp;
|
const iframeRedirectRegex = new RegExp(`(?=.*(${server}))(?=.*(event|loginToken|token))`, 'g');
|
||||||
private iframeRedirectRegex: RegExp;
|
|
||||||
|
|
||||||
static navigationOptions = ({ route, navigation }: INavigationOption) => {
|
// Force 3s delay so the server has time to evaluate the token
|
||||||
const { authType } = route.params;
|
const debouncedLogin = useDebounce((params: ICredentials) => login(params), 3000);
|
||||||
return {
|
|
||||||
headerLeft: () => <HeaderButton.CloseModal navigation={navigation} />,
|
|
||||||
title: ['saml', 'cas', 'iframe'].includes(authType) ? 'SSO' : 'OAuth'
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
constructor(props: IAuthenticationWebView) {
|
const login = (params: ICredentials) => {
|
||||||
super(props);
|
|
||||||
this.state = {
|
|
||||||
logging: false,
|
|
||||||
loading: false
|
|
||||||
};
|
|
||||||
this.oauthRedirectRegex = new RegExp(`(?=.*(${props.server}))(?=.*(credentialToken))(?=.*(credentialSecret))`, 'g');
|
|
||||||
this.iframeRedirectRegex = new RegExp(`(?=.*(${props.server}))(?=.*(event|loginToken|token))`, 'g');
|
|
||||||
}
|
|
||||||
|
|
||||||
componentWillUnmount() {
|
|
||||||
if (this.debouncedLogin && this.debouncedLogin.stop) {
|
|
||||||
this.debouncedLogin.stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dismiss = () => {
|
|
||||||
const { navigation } = this.props;
|
|
||||||
navigation.pop();
|
|
||||||
};
|
|
||||||
|
|
||||||
login = (params: ICredentials) => {
|
|
||||||
const { logging } = this.state;
|
|
||||||
if (logging) {
|
if (logging) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
setLogging(true);
|
||||||
this.setState({ logging: true });
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Services.loginOAuthOrSso(params);
|
Services.loginOAuthOrSso(params);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn(e);
|
console.warn(e);
|
||||||
}
|
}
|
||||||
this.setState({ logging: false });
|
setLogging(false);
|
||||||
this.dismiss();
|
navigation.pop();
|
||||||
};
|
};
|
||||||
|
|
||||||
// Force 3s delay so the server has time to evaluate the token
|
const tryLogin = useDebounce(
|
||||||
debouncedLogin = debounce((params: ICredentials) => this.login(params), 3000);
|
|
||||||
|
|
||||||
tryLogin = debounce(
|
|
||||||
async () => {
|
async () => {
|
||||||
const { Accounts_Iframe_api_url, Accounts_Iframe_api_method } = this.props;
|
|
||||||
const data = await fetch(Accounts_Iframe_api_url, { method: Accounts_Iframe_api_method }).then(response => response.json());
|
const data = await fetch(Accounts_Iframe_api_url, { method: Accounts_Iframe_api_method }).then(response => response.json());
|
||||||
const resume = data?.login || data?.loginToken;
|
const resume = data?.login || data?.loginToken;
|
||||||
if (resume) {
|
if (resume) {
|
||||||
this.login({ resume });
|
login({ resume });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
3000,
|
3000,
|
||||||
true
|
{ leading: true }
|
||||||
);
|
);
|
||||||
|
|
||||||
onNavigationStateChange = (webViewState: WebViewNavigation | WebViewMessage) => {
|
const onNavigationStateChange = (webViewState: WebViewNavigation | WebViewMessage) => {
|
||||||
const url = decodeURIComponent(webViewState.url);
|
const url = decodeURIComponent(webViewState.url);
|
||||||
const { route } = this.props;
|
|
||||||
const { authType } = route.params;
|
|
||||||
if (authType === 'saml' || authType === 'cas') {
|
if (authType === 'saml' || authType === 'cas') {
|
||||||
const { ssoToken } = route.params;
|
|
||||||
const parsedUrl = parse(url, true);
|
const parsedUrl = parse(url, true);
|
||||||
// ticket -> cas / validate & saml_idp_credentialToken -> saml
|
// ticket -> cas / validate & saml_idp_credentialToken -> saml
|
||||||
if (parsedUrl.pathname?.includes('validate') || parsedUrl.query?.ticket || parsedUrl.query?.saml_idp_credentialToken) {
|
if (parsedUrl.pathname?.includes('validate') || parsedUrl.query?.ticket || parsedUrl.query?.saml_idp_credentialToken) {
|
||||||
|
@ -140,28 +101,28 @@ class AuthenticationWebView extends React.PureComponent<IAuthenticationWebView,
|
||||||
} else {
|
} else {
|
||||||
payload = { cas: { credentialToken: ssoToken } };
|
payload = { cas: { credentialToken: ssoToken } };
|
||||||
}
|
}
|
||||||
this.debouncedLogin(payload);
|
debouncedLogin(payload);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authType === 'oauth') {
|
if (authType === 'oauth') {
|
||||||
if (this.oauthRedirectRegex.test(url)) {
|
if (oauthRedirectRegex.test(url)) {
|
||||||
const parts = url.split('#');
|
const parts = url.split('#');
|
||||||
const credentials = JSON.parse(parts[1]);
|
const credentials = JSON.parse(parts[1]);
|
||||||
this.debouncedLogin({ oauth: { ...credentials } });
|
debouncedLogin({ oauth: { ...credentials } });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authType === 'iframe') {
|
if (authType === 'iframe') {
|
||||||
if (this.iframeRedirectRegex.test(url)) {
|
if (iframeRedirectRegex.test(url)) {
|
||||||
const parts = url.split('#');
|
const parts = url.split('#');
|
||||||
const credentials = JSON.parse(parts[1]);
|
const credentials = JSON.parse(parts[1]);
|
||||||
switch (credentials.event) {
|
switch (credentials.event) {
|
||||||
case 'try-iframe-login':
|
case 'try-iframe-login':
|
||||||
this.tryLogin();
|
tryLogin();
|
||||||
break;
|
break;
|
||||||
case 'login-with-token':
|
case 'login-with-token':
|
||||||
this.debouncedLogin({ resume: credentials.token || credentials.loginToken });
|
debouncedLogin({ resume: credentials.token || credentials.loginToken });
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
// Do nothing
|
// Do nothing
|
||||||
|
@ -170,39 +131,31 @@ class AuthenticationWebView extends React.PureComponent<IAuthenticationWebView,
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
render() {
|
const isIframe = authType === 'iframe';
|
||||||
const { loading } = this.state;
|
|
||||||
const { route } = this.props;
|
|
||||||
const { url, authType } = route.params;
|
|
||||||
const isIframe = authType === 'iframe';
|
|
||||||
|
|
||||||
return (
|
useLayoutEffect(() => {
|
||||||
<>
|
navigation.setOptions({
|
||||||
<StatusBar />
|
headerLeft: () => <HeaderButton.CloseModal />,
|
||||||
<WebView
|
title: ['saml', 'cas', 'iframe'].includes(authType) ? 'SSO' : 'OAuth'
|
||||||
source={{ uri: url }}
|
});
|
||||||
userAgent={userAgent}
|
}, [authType, navigation]);
|
||||||
// https://github.com/react-native-community/react-native-webview/issues/24#issuecomment-540130141
|
|
||||||
onMessage={({ nativeEvent }) => this.onNavigationStateChange(nativeEvent)}
|
|
||||||
onNavigationStateChange={this.onNavigationStateChange}
|
|
||||||
injectedJavaScript={isIframe ? injectedJavaScript : undefined}
|
|
||||||
onLoadStart={() => {
|
|
||||||
this.setState({ loading: true });
|
|
||||||
}}
|
|
||||||
onLoadEnd={() => {
|
|
||||||
this.setState({ loading: false });
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{loading ? <ActivityIndicator size='large' absolute /> : null}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const mapStateToProps = (state: IApplicationState) => ({
|
return (
|
||||||
server: state.server.server,
|
<>
|
||||||
Accounts_Iframe_api_url: state.settings.Accounts_Iframe_api_url as string,
|
<StatusBar />
|
||||||
Accounts_Iframe_api_method: state.settings.Accounts_Iframe_api_method as string
|
<WebView
|
||||||
});
|
source={{ uri: url }}
|
||||||
|
userAgent={userAgent}
|
||||||
|
// https://github.com/react-native-community/react-native-webview/issues/24#issuecomment-540130141
|
||||||
|
onMessage={({ nativeEvent }) => onNavigationStateChange(nativeEvent)}
|
||||||
|
onNavigationStateChange={onNavigationStateChange}
|
||||||
|
injectedJavaScript={isIframe ? injectedJavaScript : undefined}
|
||||||
|
onLoadStart={() => setLoading(true)}
|
||||||
|
onLoadEnd={() => setLoading(false)}
|
||||||
|
/>
|
||||||
|
{loading ? <ActivityIndicator size='large' absolute /> : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export default connect(mapStateToProps)(withTheme(AuthenticationWebView));
|
export default AuthenticationWebView;
|
||||||
|
|
Loading…
Reference in New Issue