{"id":22707350,"url":"https://github.com/tutv/rn-firebase-authentication","last_synced_at":"2026-05-07T10:32:43.174Z","repository":{"id":85524341,"uuid":"143163868","full_name":"tutv/rn-firebase-authentication","owner":"tutv","description":"Using Firebase Authentication to build login/register feature in React Native","archived":false,"fork":false,"pushed_at":"2018-08-02T04:57:24.000Z","size":888,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-10T10:34:37.820Z","etag":null,"topics":["firebase","firebase-authentication","react-native"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tutv.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-08-01T14:01:41.000Z","updated_at":"2018-08-02T04:57:25.000Z","dependencies_parsed_at":null,"dependency_job_id":"65d4eba7-76cb-4ca9-b07e-7cce9b37ae18","html_url":"https://github.com/tutv/rn-firebase-authentication","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/tutv/rn-firebase-authentication","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tutv%2Frn-firebase-authentication","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tutv%2Frn-firebase-authentication/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tutv%2Frn-firebase-authentication/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tutv%2Frn-firebase-authentication/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tutv","download_url":"https://codeload.github.com/tutv/rn-firebase-authentication/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tutv%2Frn-firebase-authentication/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32733465,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-07T02:14:30.463Z","status":"ssl_error","status_checked_at":"2026-05-07T02:14:29.405Z","response_time":62,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["firebase","firebase-authentication","react-native"],"created_at":"2024-12-10T10:12:11.968Z","updated_at":"2026-05-07T10:32:43.158Z","avatar_url":"https://github.com/tutv.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Sử dụng Firebase để xây dựng chức năng đăng ký, đăng nhập\n\n## Mục tiêu\n\n- Hiểu được cách sử dụng các chức năng trong Firsebase.\n- Sử dụng **Firebase Authentication** để tạo xử lý các tác vục đăng nhập, đăng ký người dùng.\n\n## Nội dung\n\n- Đăng ký tài khoản trên: [Firebase](https://firebase.google.com).\n- Tạo 2 screen là `Account` và `Home` để demo tính năng đăng nhập và đăng ký.\n- Trong screen `Account` sẽ cho phép người dùng đăng nhập và đăng ký.\n- Trong screen `Home` sẽ tạo 1 message để hiện thông là người dùng đã đăng nhập hay chưa đăng nhập (guest).\n\n## Hướng dẫn\n\n### Bước 1\n\n- Đăng ký tài khoản free tại: [Firebase](https://firebase.google.com).\n\n- Trong phần `Authentication`, bật tính năng xác thực với **email/password**\n\n![Auth password](/demo/auth-password.png)\n\n### Bước 2\n\n- Khởi tạo project với `create-react-native-app`\n\n- Copy config của firebase vào file: `src/config/firebase.json` như sau:\n```\n{\n  \"apiKey\": \"xxxxx\",\n  \"authDomain\": \"project-xxx.firebaseapp.com\",\n  \"databaseURL\": \"https://project-xxx.firebaseio.com\",\n  \"projectId\": \"project-xxx\",\n  \"storageBucket\": \"project-xxx.appspot.com\",\n  \"messagingSenderId\": \"xxx\"\n}\n```\n\n![Config demo](/demo/firebase-config.png)\n\n```\n\n### Bước 3\n\n- Cài đặt package `firebase`\n```bash\nnpm i --save firebase\n```\n\n- Tạo 1 file `fire` để kết nối tới **firebase**\n```javascript\nimport firebase from 'firebase'\nimport configFirebase from './config/firebase.json'\n\nconst config = configFirebase || {}\nfirebase.initializeApp(config)\n\nexport default () =\u003e firebase\n```\n\n### Bước 4\n\n- Tạo 1 file `APIServices.js` để tạo các function `register` và `login` bằng cách sử dụng `Authentication` của **firebase**\n```javascript\nimport firebase from '../firebase'\n\nconst firebaseInstant = firebase()\nconst auth = firebaseInstant.auth()\n\nexport const register = ({email, password = '', name = ''}) =\u003e {\n    return auth.createUserWithEmailAndPassword(email, password)\n        .then(({user}) =\u003e {\n            return Promise.all([\n                user.getIdToken(),\n                user.updateProfile({displayName: name})\n            ]).then(([accessToken]) =\u003e {\n                const {refreshToken} = user\n\n                const {providerData} = user\n                const userData = Array.isArray(providerData) \u0026\u0026 providerData.length ? providerData[0] : {}\n\n                return {\n                    user: {\n                        ...userData,\n                        displayName: name\n                    },\n                    token: {\n                        accessToken,\n                        refreshToken\n                    }\n                }\n            })\n        })\n}\n\nexport const login = ({email, password = ''}) =\u003e {\n    return auth.signInWithEmailAndPassword(email, password)\n        .then(({user}) =\u003e {\n            return user.getIdToken()\n                .then(accessToken =\u003e {\n                    const {refreshToken} = user\n\n                    const {providerData} = user\n                    const userData = Array.isArray(providerData) \u0026\u0026 providerData.length ? providerData[0] : {}\n\n                    return {\n                        user: userData,\n                        token: {\n                            accessToken,\n                            refreshToken\n                        }\n                    }\n                })\n        })\n}\n```\n\n### Bước 5\n\n- Tạo 1 file `AuthServices.js` để quản lý state khi người dùng đã đăng nhập hoặc thoát.\n\n```javascript\nconst _store = {\n    isAuthenticated: false,\n    user: {},\n    token: {\n        accessToken: '',\n        refreshToken: ''\n    },\n    subscribers: []\n}\n\nexport const logout = () =\u003e {\n    _store.isAuthenticated = false;\n    _store.user = {}\n\n    _broadcast()\n}\n\nexport const loginSuccess = ({user, token}) =\u003e {\n    _store.user = {\n        ...user\n    }\n    _store.token = {\n        ...token\n    }\n    _store.isAuthenticated = true\n    _broadcast()\n\n    return Promise.resolve(true)\n}\n\nconst _broadcast = () =\u003e {\n    _store.subscribers.forEach(subscriber =\u003e {\n        typeof subscriber === 'function' \u0026\u0026 subscriber(_store.user)\n    })\n}\n\nexport const isAuthenticated = () =\u003e _store.isAuthenticated\n\nexport const getCurrentUser = () =\u003e _store.user\n\nexport const subscribeAuthentication = subscriber =\u003e {\n    if (typeof subscriber !== 'function') return\n    if (_store.subscribers.indexOf(subscriber) !== -1) return\n\n    _store.subscribers = [].concat(_store.subscribers, [subscriber])\n}\n\nexport const unsubscribeAuthentication = subscriber =\u003e {\n    _store.subscribers = _store.subscribers.filter(_sub =\u003e _sub !== subscriber)\n}\n```\n\n### Bước 6\n\n- Tạo 1 screens là `Account` và `Home`\n\n    * `Account`: Xử lý các tác vụ đăng nhập/đăng ký\n    * `Home`: Hiển thị một message và cho phép người dùng `logout`\n\n- Trong `Account` sẽ tạo 2 component:\n    * `LoginForm` xử lý tác vụ đăng nhập\n    ```javascript\n    import React, {Component} from 'react'\n    import PropTypes from 'prop-types'\n    import {View, TextInput, Text, TouchableOpacity, Button, Alert, StyleSheet} from 'react-native'\n    import {login} from \"../../services/APIServices\"\n    import {loginSuccess} from \"../../services/AuthServices\"\n\n    class LoginForm extends Component {\n        state = {\n            email: '',\n            password: ''\n        }\n\n        _handleTextInputChange = (field) =\u003e (value) =\u003e {\n            this.setState({\n                [field]: value\n            })\n        }\n\n        _handlePressLogin = () =\u003e {\n            const {email, password} = this.state\n\n            if (!email) return Alert.alert('Please enter your email')\n            if (!password) return Alert.alert('Please enter your password')\n\n            login({email, password})\n                .then(({user, token}) =\u003e {\n                    this.setState({\n                        email: '',\n                        password: ''\n                    })\n\n                    return loginSuccess({user, token})\n                })\n                .then(() =\u003e {\n                    this.props.navigation.navigate('Home')\n                })\n                .catch(error =\u003e {\n                    const {message} = error\n\n                    Alert.alert(message)\n                })\n        }\n\n        _handlePressRegister = () =\u003e {\n            this.props.onAction('register')\n        }\n\n        render() {\n            const {email, password} = this.state\n\n            return (\n                \u003cView style={styles.container}\u003e\n                    \u003cView style={styles.form}\u003e\n                        \u003cTextInput\n                            returnKeyType='done'\n                            style={styles.textInput}\n                            placeholder='Email'\n                            value={email}\n                            keyboardType='email-address'\n                            textContentType='emailAddress'\n                            onChangeText={this._handleTextInputChange('email')}/\u003e\n                        \u003cTextInput\n                            returnKeyType='done'\n                            style={styles.textInput}\n                            placeholder='Password'\n                            value={password}\n                            onChangeText={this._handleTextInputChange('password')}\n                            secureTextEntry/\u003e\n\n                        \u003cView style={styles.button}\u003e\n                            \u003cButton\n                                title='Login'\n                                onPress={this._handlePressLogin}/\u003e\n                        \u003c/View\u003e\n\n                        \u003cTouchableOpacity onPress={this._handlePressRegister}\u003e\n                            \u003cText style={styles.goTo}\u003eOr register now!\u003c/Text\u003e\n                        \u003c/TouchableOpacity\u003e\n                    \u003c/View\u003e\n                \u003c/View\u003e\n            )\n        }\n    }\n\n    const styles = StyleSheet.create({\n        container: {\n            flex: 1,\n            justifyContent: 'space-between',\n            width: '100%',\n            backgroundColor: '#eee',\n        },\n\n        form: {\n            flex: 1,\n            flexDirection: 'column',\n            alignItems: 'center',\n            justifyContent: 'center'\n        },\n\n        textInput: {\n            borderWidth: 1,\n            borderColor: '#999',\n            padding: 10,\n            marginBottom: 20,\n            minWidth: 200,\n            textAlign: 'center'\n        },\n\n        button: {\n            marginBottom: 30\n        },\n\n        goTo: {\n            color: '#999'\n        }\n    })\n\n    LoginForm.propTypes = {\n        navigation: PropTypes.object.isRequired,\n        onAction: PropTypes.func.isRequired,\n    }\n\n    export default LoginForm\n    ```\n\n    * `RegisterForm` xử lý tác vụ đăng ký\n    ```javascript\n    import React, {Component} from 'react'\n    import {View, TextInput, Button, Alert, StyleSheet, TouchableOpacity, Text} from 'react-native'\n    import {register} from '../../services/APIServices'\n    import PropTypes from 'prop-types'\n    import {loginSuccess} from \"../../services/AuthServices\"\n\n    class RegisterForm extends Component {\n        state = {\n            name: '',\n            email: '',\n            password: ''\n        }\n\n        _handleTextInputChange = (field) =\u003e (value) =\u003e {\n            this.setState({\n                [field]: value\n            })\n        }\n\n        _handlePressRegister = () =\u003e {\n            const {email, name, password} = this.state\n\n            if (!email) return Alert.alert('Please enter your email')\n            if (!password) return Alert.alert('Please enter your password')\n\n            register({email, password, name})\n                .then(({user, token}) =\u003e {\n                    return loginSuccess({user, token})\n                })\n                .then(() =\u003e {\n                    this.props.navigation.navigate('Home')\n                })\n                .catch(error =\u003e {\n                    const {message} = error\n\n                    Alert.alert(message)\n                })\n        }\n\n        _handlePressGoToLogin = () =\u003e {\n            this.props.onAction('login')\n        }\n\n        render() {\n            const {email, name, password} = this.state\n\n            return (\n                \u003cView style={styles.container}\u003e\n                    \u003cView style={styles.form}\u003e\n                        \u003cTextInput\n                            returnKeyType='done'\n                            style={styles.textInput}\n                            placeholder='Full name'\n                            value={name}\n                            textContentType='name'\n                            onChangeText={this._handleTextInputChange('name')}/\u003e\n                        \u003cTextInput\n                            returnKeyType='done'\n                            style={styles.textInput}\n                            placeholder='Email'\n                            value={email}\n                            textContentType='emailAddress'\n                            keyboardType='email-address'\n                            onChangeText={this._handleTextInputChange('email')}/\u003e\n                        \u003cTextInput\n                            returnKeyType='done'\n                            style={styles.textInput}\n                            placeholder='Password'\n                            value={password}\n                            onChangeText={this._handleTextInputChange('password')}\n                            secureTextEntry/\u003e\n\n                        \u003cView style={styles.button}\u003e\n                            \u003cButton\n                                title='Register'\n                                onPress={this._handlePressRegister}/\u003e\n                        \u003c/View\u003e\n\n                        \u003cTouchableOpacity onPress={this._handlePressGoToLogin}\u003e\n                            \u003cText style={styles.goTo}\u003eOr login now!\u003c/Text\u003e\n                        \u003c/TouchableOpacity\u003e\n                    \u003c/View\u003e\n                \u003c/View\u003e\n            )\n        }\n    }\n\n    const styles = StyleSheet.create({\n        container: {\n            flex: 1,\n            justifyContent: 'space-between',\n            width: '100%',\n            backgroundColor: '#eee',\n        },\n\n        form: {\n            flex: 1,\n            flexDirection: 'column',\n            alignItems: 'center',\n            justifyContent: 'center'\n        },\n\n        textInput: {\n            borderWidth: 1,\n            borderColor: '#999',\n            padding: 10,\n            marginBottom: 20,\n            minWidth: 200,\n            textAlign: 'center'\n        },\n\n        button: {\n            marginBottom: 30\n        },\n\n        goTo: {\n            color: '#999'\n        }\n    })\n\n    RegisterForm.propTypes = {\n        navigation: PropTypes.object.isRequired,\n        onAction: PropTypes.func.isRequired,\n    }\n\n    export default RegisterForm\n    ```\n\n- Trong `Home` component sẽ xử lý tác vụ `logout` và hiển thị **welcome message**\n\n```javascript\nimport React, {Component} from 'react'\nimport {View, StyleSheet} from 'react-native'\nimport {createStackNavigator} from 'react-navigation'\nimport {\n    getCurrentUser,\n    isAuthenticated,\n    subscribeAuthentication,\n    unsubscribeAuthentication\n} from \"../services/AuthServices\"\nimport WelcomeMessage from \"./home/WelcomeMessage\"\nimport LogoutButton from \"./home/LogoutButton\"\n\nclass HomePage extends Component {\n    static navigationOptions = {\n        title: 'Home',\n        headerStyle: {\n            backgroundColor: '#da552f'\n        },\n        headerTintColor: '#fff',\n        headerTitleStyle: {\n            color: '#fff'\n        }\n    }\n\n    state = {\n        isAuthenticated: isAuthenticated(),\n        user: getCurrentUser()\n    }\n\n    componentDidMount() {\n        subscribeAuthentication(this._handleOnChangeAuth)\n    }\n\n    componentWillUnmount() {\n        unsubscribeAuthentication(this._handleOnChangeAuth)\n    }\n\n    _handleOnChangeAuth = () =\u003e {\n        this.setState({\n            isAuthenticated: isAuthenticated(),\n            user: getCurrentUser()\n        })\n    }\n\n    render() {\n        const {isAuthenticated} = this.state\n\n        return (\n            \u003cView style={styles.container}\u003e\n                \u003cWelcomeMessage {...this.state}/\u003e\n\n                {\n                    isAuthenticated \u0026\u0026 \u003cLogoutButton/\u003e\n                }\n            \u003c/View\u003e\n        )\n    }\n}\n\nconst styles = StyleSheet.create({\n    container: {\n        width: '100%',\n        minHeight: '100%',\n        flex: 1,\n        alignItems: 'center',\n        justifyContent: 'center',\n    }\n})\n\nexport default createStackNavigator({\n    Home: {\n        screen: HomePage\n    },\n})\n```\n\nNote: Trong `Home` component sẽ chia thành 1 component nhỏ hơn là `WelcomeMessage` và `LogoutButton` để xử lý riêng biệt (tham khảo code mẫu).\n\n\n### Bước 7\n\n- Chạy chương trình và xem kết quả.\n\n## Code mẫu\n\nTham khảo tại: https://github.com/tutv/rn-firebase-authentication\n\n## Ảnh demo\n\n![Login](/demo/login.jpeg)\n\n![Register](/demo/register.jpeg)\n\n![Home page](/demo/home.jpeg)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftutv%2Frn-firebase-authentication","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftutv%2Frn-firebase-authentication","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftutv%2Frn-firebase-authentication/lists"}