Day 9: Adding User Authentication and Profile Management


#UserAuthentication #ProfileManagement #ReactNativeAuth

Welcome to Day 9! Today, you’ll add user authentication and implement profile management in your fitness app. Authentication allows users to securely log in, while profile management provides a personalized experience.


What You’ll Learn Today

  1. Set up Firebase Authentication for user login and registration.
  2. Build a profile management screen to update user details.
  3. Handle secure user sessions.

Step 1: Set Up Firebase Authentication

1. Install Firebase Authentication

npm install @react-native-firebase/auth
npx pod-install

2. Configure Firebase Authentication

  • Go to the Firebase Console.
  • Enable Email/Password Authentication under Authentication > Sign-In Method.

Step 2: Build User Authentication

1. Create AuthenticationService

Create a file AuthenticationService.js:

import auth from '@react-native-firebase/auth';

export const registerUser = async (email, password) => {
  try {
    const userCredential = await auth().createUserWithEmailAndPassword(email, password);
    return userCredential.user;
  } catch (error) {
    console.error('Registration Error:', error);
    throw error;
  }
};

export const loginUser = async (email, password) => {
  try {
    const userCredential = await auth().signInWithEmailAndPassword(email, password);
    return userCredential.user;
  } catch (error) {
    console.error('Login Error:', error);
    throw error;
  }
};

export const logoutUser = async () => {
  try {
    await auth().signOut();
    console.log('User logged out');
  } catch (error) {
    console.error('Logout Error:', error);
  }
};

Step 3: Create Authentication Screen

1. Build Login and Registration Forms

Create a file AuthScreen.js:

import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import { registerUser, loginUser } from './AuthenticationService';

const AuthScreen = ({ onLoginSuccess }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isRegistering, setIsRegistering] = useState(false);

  const handleAuth = async () => {
    try {
      const user = isRegistering ? await registerUser(email, password) : await loginUser(email, password);
      onLoginSuccess(user);
    } catch (error) {
      alert(error.message);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>{isRegistering ? 'Register' : 'Login'}</Text>
      <TextInput
        style={styles.input}
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
        keyboardType="email-address"
        autoCapitalize="none"
      />
      <TextInput
        style={styles.input}
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
      />
      <Button title={isRegistering ? 'Register' : 'Login'} onPress={handleAuth} />
      <Button
        title={isRegistering ? 'Switch to Login' : 'Switch to Register'}
        onPress={() => setIsRegistering(!isRegistering)}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 10,
    marginBottom: 15,
  },
});

export default AuthScreen;

Step 4: Implement Profile Management

1. Create ProfileScreen

Create a file ProfileScreen.js:

import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import auth from '@react-native-firebase/auth';

const ProfileScreen = ({ onLogout }) => {
  const [user, setUser] = useState(null);
  const [displayName, setDisplayName] = useState('');

  useEffect(() => {
    const currentUser = auth().currentUser;
    setUser(currentUser);
    setDisplayName(currentUser?.displayName || '');
  }, []);

  const updateProfile = async () => {
    try {
      await auth().currentUser.updateProfile({ displayName });
      alert('Profile updated');
    } catch (error) {
      console.error('Profile Update Error:', error);
      alert(error.message);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Profile</Text>
      <Text>Email: {user?.email}</Text>
      <TextInput
        style={styles.input}
        placeholder="Display Name"
        value={displayName}
        onChangeText={setDisplayName}
      />
      <Button title="Update Profile" onPress={updateProfile} />
      <Button title="Logout" onPress={onLogout} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  input: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 10, marginBottom: 15 },
});

export default ProfileScreen;

Step 5: Combine Authentication and Profile Screens

Update App.js:

import React, { useState } from 'react';
import AuthScreen from './AuthScreen';
import ProfileScreen from './ProfileScreen';
import { logoutUser } from './AuthenticationService';

const App = () => {
  const [user, setUser] = useState(null);

  const handleLogout = async () => {
    await logoutUser();
    setUser(null);
  };

  return user ? (
    <ProfileScreen onLogout={handleLogout} />
  ) : (
    <AuthScreen onLoginSuccess={(loggedInUser) => setUser(loggedInUser)} />
  );
};

export default App;

Step 6: Test Authentication and Profiles

  1. Run the app: npx react-native run-android npx react-native run-ios
  2. Register a new user, log in, and update the profile.
  3. Verify session persistence by restarting the app.
See also  Day 3: Implementing User Authentication with Firebase/Auth0

Enhance Authentication (Optional)

  1. Social Login: Add Google or Facebook login to simplify authentication.
  2. Password Reset: Allow users to reset their passwords via email.
  3. Session Management: Use Firebase’s built-in session persistence to maintain user login.

SEO Optimization for This Tutorial

Keywords: Firebase React Native authentication, fitness app profile management, user login React Native, user session management, fitness app authentication.

Meta Description: Learn how to add user authentication and profile management to your React Native fitness app with Firebase. Full tutorial with secure session handling.


Summary

Today, you implemented user authentication and profile management, enabling secure user logins and personalized experiences.

What’s Next: Tomorrow, you’ll deploy your fitness app and set up analytics to track user progress.

Stay tuned for Day 10: Deploying the App and Setting Up Analytics.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.