Вопрос о потоке аутентификации и React Navigation (React Native) - PullRequest
0 голосов
/ 25 сентября 2018

Я пытаюсь настроить поток аутентификации с моим приложением, но я не могу понять это точно.Вот как я хотел бы, чтобы поток был, но, пожалуйста, дайте мне знать, если у вас есть какие-либо репозитории, которые могут помочь в этом:

Вкладки:

  • Home
  • Поиск

Экраны:

  • AuthLoading
  • Вход
  • Главная
  • Поиск

Поток аутентификации поиска:

  1. Приложение запускается, проверяет userToken
  2. Если userToken, перенаправить на главный экран (с панелью нижних вкладок)
  3. Если нет userToken, перенаправить на экран входа в систему (на экране входа есть Facebook OAuth от Expo)
  4. Пользователь входит в систему с Facebook и проверяет firebase. В случае успеха, перенаправить на главный экран (с панелью нижних вкладок) 4. В случае неудачи перенаправить на экран входа в систему

router.js

import React from 'react';
import { Platform, StatusBar } from 'react-native';
import { createStackNavigator, createBottomTabNavigator, createSwitchNavigator } from 'react-navigation';
import { FontAwesome } from 'react-native-vector-icons';

import AuthLoadingScreen from '../screens/AuthLoadingScreen';
import LoginScreen from '../screens/LoginScreen';
import HomeScreen from '../screens/HomeScreen';
import SearchScreen from '../screens/SearchScreen';


export const UnauthenticatedStack = createStackNavigator({
  AuthLoading: {
    screen: AuthLoadingScreen,
    navigationOptions: {
      title: 'AuthLoading',
      tabBarVisible: false,
      header: null,
      headerLeft: null,
      headerRight: null,
    },
  },
  Login: {
    screen: LoginScreen,
    navigationOptions: {
      title: 'Login',
      tabBarVisible: false,
      header: null,
      headerLeft: null,
    },
  },
});

export const AuthenticatedStack = createBottomTabNavigator(
  {
    Home: {
      screen: HomeScreen,
      navigationOptions: {
        tabBarLabel: 'Home',
        tabBarIcon: ({ tintColor }) => (
          <FontAwesome name="home" size={24} color={tintColor} />
        ),
      },
    },
    Search: {
      screen: SearchScreen,
      navigationOptions: {
        tabBarLabel: 'Search',
        tabBarIcon: ({ tintColor }) => (
          <FontAwesome name="search" size={24} color={tintColor} />
        ),
      },
    },
  },
);

export default createSwitchNavigator({
  Home: AuthenticatedStack,
  Login: UnauthenticatedStack,
},
{
  initialRouteName: 'Home'
  ,
});

App.js

// Imports: Dependencies
import React from 'react';
import { View, StyleSheet } from 'react-native';
import firebase from 'firebase';
import { FirebaseAPIKey, authDomain, databaseURL, projectId, messagingSenderId } from './config/config';
import { UnauthenticatedStack, AuthenticatedStack } from './navigation/router';


// Firebase Config
export const firebaseConfig = {
  apiKey: FirebaseAPIKey,
  authDomain: `${authDomain}`,
  databaseURL: `${databaseURL}`,
  projectId: `${projectId}`,
  // storageBucket: "",
  messagingSenderId: `${messagingSenderId}`,
};

console.log(firebaseConfig)

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// React Native: Application
export default class App extends React.Component {
  render() {

    return (
      <View style={styles.container}>
        <UnauthenticatedStack />
      </View>
    );
  }
};


// Styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#CA3433',
  },
});

AuthLoading.js

import React from 'react';
import { ActivityIndicator, AsyncStorage, StatusBar, StyleSheet, View, Text } from 'react-native';

export default class AuthLoadingScreen extends React.Component {
  constructor(props) {
    super(props);
    this.checkUserToken();
  }

  async checkUserToken() {
    const userToken = await AsyncStorage.getItem('userToken');

    // If User Token
    if (userToken) {
      AsyncStorage.setItem(userToken);
      this.props.navigation.navigate('Home');

    }
    else {
      this.props.navigation.navigate('Login');
    }
  }

  // Render any loading content that you like here
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>Checking Authentication</Text>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}


// Styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#CA3433',
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    justifyContent: 'center',
    color: '#fff',
    fontSize: 18,
    fontWeight: '500',
  },
});

Home.js

// Imports: Dependencies
import React from 'react';
import { View, StyleSheet } from 'react-native';

// Imports: Components
import List from '../components/List';


// React Native Screen: Home
export default () => (
  <View style={styles.container}>
    <List />
  </View>
);


// Styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

Search.js

// Imports: Dependencies
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';

// Imports: Components


// React Native Screen: Search
export default class Search extends Component {
  // Render
  render() {
    return (
      <View styles={styles.container}>
          <Text>Search</Text>
      </View>
    )
  }
}


// Styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Ответы [ 2 ]

0 голосов
/ 09 мая 2019

Переместите AuthLoadingScreen для созданияSwitchNavigator:

const rootNavigator =  createSwitchNavigator({
  Home: AuthenticatedStack,
  Login: UnauthenticatedStack,
  AuthLoading: AuthLoadingScreen,
},
{
  initialRouteName: 'AuthLoading',
});

export const AppNavigation = createAppContainer(rootNavigator)

App.js

// React Native: Application
export default class App extends React.Component {
  render() {

    return (
      <View style={styles.container}>
        <AppNavigation />
      </View>
    );
  }
};
0 голосов
/ 13 февраля 2019

В App.js не экспортируйте часть конфигурации firebase.Класс приложения должен быть таким:

export default class App extends React.Component {
componentWillMount() {
    const firebaseConfig = {
    apiKey: FirebaseAPIKey,
    authDomain: `${authDomain}`,
    databaseURL: `${databaseURL}`,
    projectId: `${projectId}`,
    // storageBucket: "",
    messagingSenderId: `${messagingSenderId}`,
  }

    firebase.initializeApp(config);
}

  render() {

    return (
      <View style={styles.container}>
        <UnauthenticatedStack />
      </View>
    )
} 
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...