2018-07-10 13:40:32 +00:00
import React from 'react' ;
import PropTypes from 'prop-types' ;
2019-02-07 16:04:41 +00:00
import { WebView } from 'react-native' ;
2018-07-10 13:40:32 +00:00
import { connect } from 'react-redux' ;
import RocketChat from '../lib/rocketchat' ;
2019-03-12 16:23:06 +00:00
import { isIOS } from '../utils/deviceInfo' ;
import { CloseModalButton } from '../containers/HeaderButton' ;
import StatusBar from '../containers/StatusBar' ;
2018-07-10 13:40:32 +00:00
const userAgentAndroid = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1' ;
2019-01-29 19:52:56 +00:00
const userAgent = isIOS ? 'UserAgent' : userAgentAndroid ;
2018-07-10 13:40:32 +00:00
@ connect ( state => ( {
server : state . server . server
} ) )
2018-08-31 18:13:30 +00:00
export default class OAuthView extends React . PureComponent {
2019-03-12 16:23:06 +00:00
static navigationOptions = ( { navigation } ) => ( {
headerLeft : < CloseModalButton navigation = { navigation } / > ,
title : 'OAuth'
} )
2018-07-10 13:40:32 +00:00
static propTypes = {
2019-03-12 16:23:06 +00:00
navigation : PropTypes . object ,
2018-07-10 13:40:32 +00:00
server : PropTypes . string
}
constructor ( props ) {
super ( props ) ;
2018-12-05 20:52:08 +00:00
this . state = {
logging : false
} ;
2018-07-10 13:40:32 +00:00
this . redirectRegex = new RegExp ( ` (?=.*( ${ props . server } ))(?=.*(credentialToken))(?=.*(credentialSecret)) ` , 'g' ) ;
}
2018-10-23 21:39:48 +00:00
dismiss = ( ) => {
2019-03-12 16:23:06 +00:00
const { navigation } = this . props ;
navigation . pop ( ) ;
2018-10-23 21:39:48 +00:00
}
2018-07-10 13:40:32 +00:00
login = async ( params ) => {
2018-12-05 20:52:08 +00:00
const { logging } = this . state ;
if ( logging ) {
return ;
}
this . setState ( { logging : true } ) ;
2018-07-10 13:40:32 +00:00
try {
2018-12-05 20:52:08 +00:00
await RocketChat . loginOAuth ( params ) ;
2018-07-10 13:40:32 +00:00
} catch ( e ) {
console . warn ( e ) ;
}
2018-12-05 20:52:08 +00:00
this . setState ( { logging : false } ) ;
this . dismiss ( ) ;
2018-07-10 13:40:32 +00:00
}
render ( ) {
2019-03-12 16:23:06 +00:00
const { navigation } = this . props ;
const oAuthUrl = navigation . getParam ( 'oAuthUrl' ) ;
2018-07-10 13:40:32 +00:00
return (
2019-03-12 16:23:06 +00:00
< React . Fragment >
< StatusBar / >
< WebView
source = { { uri : oAuthUrl } }
userAgent = { userAgent }
onNavigationStateChange = { ( webViewState ) => {
const url = decodeURIComponent ( webViewState . url ) ;
if ( this . redirectRegex . test ( url ) ) {
const parts = url . split ( '#' ) ;
const credentials = JSON . parse ( parts [ 1 ] ) ;
this . login ( { oauth : { ... credentials } } ) ;
}
} }
/ >
< / R e a c t . F r a g m e n t >
2018-07-10 13:40:32 +00:00
) ;
}
}