Authentication Native - lazaronixon/react-native-turbolinks GitHub Wiki
Sometimes you will want handle authentication natively maybe using fetch
method to set cookies on react-native and share this cookies with react-native-turbolinks and react-native-webview. React Native Turbolinks handle this on IOS injecting cookies on turbolinks webview before a reloadSession
, since cookies are shared with react-native-webview via sharedProcessPool
the cookies are set there too properly.
App.js
import React, { Component } from 'react'
import Turbolinks from 'react-native-turbolinks'
const baseUrl = 'http://192.168.1.103:9292'
export default class App extends Component {
componentDidMount() {
Turbolinks.addEventListener('turbolinksVisit', this.handleVisit)
Turbolinks.addEventListener('turbolinksError', this.handleError)
Turbolinks.addEventListener('turbolinksActionPress', this.handleActionPress)
Turbolinks.startSingleScreenApp({url: baseUrl, actions: [{id: 0, title: 'Login'}]})
}
handleActionPress = (actionId) => {
if (actionId == 0) {
fetch(baseUrl + '/sign-in', { method: 'post' }).then(() => { Turbolinks.reloadSession() })
}
}
handleVisit = (data) => {
Turbolinks.visit({url: data.url, action: data.action})
}
handleError = (data) => {
if (data.code == Turbolinks.Constants.ErrorCode.httpFailure && data.statusCode == 401) {
Turbolinks.visit({component: 'AuthenticationView', modal: true})
}
}
render() { return null }
}
AuthenticationView.js
import React, { Component } from 'react'
import { SafeAreaView } from 'react-native'
import { WebView } from 'react-native-webview'
import Turbolinks from 'react-native-turbolinks'
const signInUrl = 'http://192.168.1.103:9292/users/sign_in'
const signedUrl = 'http://192.168.1.103:9292/'
export default class AuthenticationView extends Component {
componentDidMount() { this.authenticatedFlag = false }
handleAuthentication = (event) => {
if (event.nativeEvent.url == signedUrl && this.authenticatedFlag == false) {
this.authenticatedFlag = true
this.webview.stopLoading()
Turbolinks.dismiss().then(() => Turbolinks.reloadSession())
}
}
render() {
return (
<SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
<WebView ref={webview => { this.webview = webview }}
source={{uri: signInUrl}}
onLoadStart={this.handleAuthentication}/>
</SafeAreaView>
)
}
}