this is the code base soo far: a. Initialize the Project First, set up a new Node.js…
- User
this is the code base soo far: a. Initialize the Project First, set up a new Node.js project and install necessary dependencies. mkdir fitness-app-backend cd fitness-app-backend npm init -y npm install express mongoose bcryptjs jsonwebtoken cors dotenv
b. Basic Server Setup (server.js) // server.js require('dotenv').config(); const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors');
const app = express();
// Middleware app.use(cors()); app.use(express.json());
// Connect to MongoDB mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log('MongoDB Connected')) .catch(err => console.log(err));
// Routes app.get('/', (req, res) => { res.send('Fitness App Backend'); });
// Start Server const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(
Server running on port ${PORT}); });c. Environment Variables (.env) Create a .env file in the root directory: PORT=5000 MONGO_URI=your_mongodb_connection_string JWT_SECRET=your_jwt_secret_key
d. User Authentication i. User Model (models/User.js): // models/User.js const mongoose = require('mongoose'); const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, desiredPhysique: { type: String, enum: ['lean', 'muscular', 'athletic'], required: true }, fitnessGoals: [String], // e.g., ['strength', 'endurance'] dietaryPreferences: [String], dietaryRestrictions: [String], }, { timestamps: true });
// Password hashing middleware UserSchema.pre('save', async function(next) { if (!this.isModified('password')) return next(); try { const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); next(); } catch(err) { next(err); } });
// Password comparison method UserSchema.methods.comparePassword = function(candidatePassword) { return bcrypt.compare(candidatePassword, this.password); }
module.exports = mongoose.model('User', UserSchema);
ii. Authentication Routes (routes/auth.js): // routes/auth.js const express = require('express'); const router = express.Router(); const User = require('../models/User'); const jwt = require('jsonwebtoken');
// Register router.post('/register', async (req, res) => { const { username, email, password, desiredPhysique, fitnessGoals, dietaryPreferences, dietaryRestrictions } = req.body; try { const newUser = new User({ username, email, password, desiredPhysique, fitnessGoals, dietaryPreferences, dietaryRestrictions, }); await newUser.save(); res.status(201).json({ message: 'User registered successfully' }); } catch(err) { res.status(500).json({ error: err.message }); } });
// Login router.post('/login', async (req, res) => { const { email, password } = req.body; try { const user = await User.findOne({ email }); if (!user) return res.status(400).json({ message: 'Invalid credentials' });
const isMatch = await user.comparePassword(password); if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' }); const payload = { userId: user._id }; const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' }); res.json({ token }); } catch(err) { res.status(500).json({ error: err.message }); }});
module.exports = router;
iii. Protecting Routes (middleware/auth.js): // middleware/auth.js const jwt = require('jsonwebtoken');
const auth = (req, res, next) => { const token = req.header('Authorization');
if (!token) return res.status(401).json({ message: 'No token, authorization denied' }); try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded.userId; next(); } catch(err) { res.status(401).json({ message: 'Token is not valid' }); }}
module.exports = auth;
iv. Integrate Routes in server.js: // server.js (additional lines) const authRoutes = require('./routes/auth');
app.use('/api/auth', authRoutes); // Similarly, add other route files like /api/exercises, /api/diets, etc.
- Implementing Features Due to the extensive features, I'll provide an example implementation for one feature: Customized Exercise Plans. a. Exercise Model (models/Exercise.js): // models/Exercise.js const mongoose = require('mongoose');
const ExerciseSchema = new mongoose.Schema({ name: { type: String, required: true }, description: String, musclesTargeted: [String], equipment: [String], imageUrl: String, videoUrl: String, difficulty: { type: String, enum: ['beginner', 'intermediate', 'advanced'], default: 'beginner' }, }, { timestamps: true });
module.exports = mongoose.model('Exercise', ExerciseSchema);
b. Exercise Routes (routes/exercises.js): // routes/exercises.js const express = require('express'); const router = express.Router(); const Exercise = require('../models/Exercise'); const auth = require('../middleware/auth');
// Get exercises based on user goals router.get('/', auth, async (req, res) => { const userId = req.user; try { // Fetch user data const User = require('../models/User'); const user = await User.findById(userId);
// Example logic: Recommend exercises based on desiredPhysique and fitnessGoals let query = {}; if (user.desiredPhysique === 'muscular') { query = { musclesTargeted: { $in: ['chest', 'biceps', 'triceps'] }, difficulty: 'intermediate' }; } else if (user.desiredPhysique === 'lean') { query = { musclesTargeted: { $in: ['legs', 'core'] }, difficulty: 'beginner' }; } // Add more logic based on fitnessGoals const exercises = await Exercise.find(query).limit(20); res.json(exercises); } catch(err) { res.status(500).json({ error: err.message }); }});
// Add new exercise (Admin use) router.post('/', auth, async (req, res) => { // Implement admin authentication if necessary const { name, description, musclesTargeted, equipment, imageUrl, videoUrl, difficulty } = req.body; try { const newExercise = new Exercise({ name, description, musclesTargeted, equipment, imageUrl, videoUrl, difficulty, }); await newExercise.save(); res.status(201).json(newExercise); } catch(err) { res.status(500).json({ error: err.message }); } });
module.exports = router;
c. Integrate Exercise Routes in server.js: // server.js (additional lines) const exerciseRoutes = require('./routes/exercises');
app.use('/api/exercises', exerciseRoutes);
d. Frontend: Fetching and Displaying Exercises Assuming you're using React Native with functional components and hooks. i. Install Dependencies: yarn add axios
or
npm install axios
ii. Sample Component (ExerciseList.js): // components/ExerciseList.js import React, { useEffect, useState } from 'react'; import { View, Text, FlatList, Image, StyleSheet } from 'react-native'; import axios from 'axios';
const ExerciseList = ({ token }) => { const [exercises, setExercises] = useState([]);
useEffect(() => { const fetchExercises = async () => { try { const res = await axios.get('http://your-backend-url/api/exercises', { headers: { Authorization: token } }); setExercises(res.data); } catch (err) { console.error(err); } }; fetchExercises(); }, []); const renderItem = ({ item }) => ( <View style={styles.itemContainer}> {item.imageUrl && <Image source={{ uri: item.imageUrl }} style={styles.image} />} <Text style={styles.title}>{item.name}</Text> <Text>{item.description}</Text> {item.videoUrl && <Text>Video Tutorial: {item.videoUrl}</Text>} </View> ); return ( <FlatList data={exercises} keyExtractor={item => item._id} renderItem={renderItem} /> );};
const styles = StyleSheet.create({ itemContainer: { padding: 10, borderBottomWidth: 1, borderColor: '#ccc' }, image: { width: '100%', height: 200 }, title: { fontSize: 18, fontWeight: 'bold' }, });
export default ExerciseList;
how do i do this part?
iii. Using the Component Ensure you have the user's JWT token after authentication and pass it to the ExerciseList component. // Example usage in a screen import React from 'react'; import { View } from 'react-native'; import ExerciseList from '../components/ExerciseList';
const ExercisesScreen = ({ route }) => { const { token } = route.params; // assuming token is passed via navigation
return ( <View style={{ flex: 1 }}> <ExerciseList token={token} /> </View> );};
export default ExercisesScreen;
- Assistant
To effectively use the
ExerciseListcomponent by passing the user's JWT token, you'll need to establish a robust authentication flow within your React Native application. This involves:- Authenticating the User and Obtaining the JWT Token
- Storing the JWT Token Securely
- Accessing the Token Across Your Application
- Passing the Token to Components like
ExerciseList - Ensuring Token Persistence Across App Restarts
Below, I’ll guide you through each of these steps with detailed explanations and code examples.
1. Authenticating the User and Obtaining the JWT Token
Assuming you have a login screen where users can authenticate, you'll need to send their credentials to your backend and receive a JWT token in response. Here's how you can implement the login functionality.
a. Create a Login Screen
// screens/LoginScreen.js import React, { useState, useContext } from 'react'; import { View, TextInput, Button, Text, StyleSheet } from 'react-native'; import axios from 'axios'; import { AuthContext } from '../context/AuthContext'; const LoginScreen = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const { signIn } = useContext(AuthContext); const [error, setError] = useState(null); const handleLogin = async () => { try { const res = await axios.post('http://your-backend-url/api/auth/login', { email, password }); const { token } = res.data; signIn(token); } catch (err) { setError(err.response?.data?.message || 'Login failed'); } }; return ( <View style={styles.container}> <TextInput placeholder="Email" value={email} onChangeText={setEmail} style={styles.input} keyboardType="email-address" autoCapitalize="none" /> <TextInput placeholder="Password" value={password} onChangeText={setPassword} style={styles.input} secureTextEntry /> {error && <Text style={styles.error}>{error}</Text>} <Button title="Login" onPress={handleLogin} /> </View> ); }; const styles = StyleSheet.create({ container: { padding: 20, flex: 1, justifyContent: 'center' }, input: { height: 40, borderColor: '#ccc', borderWidth: 1, marginBottom: 10, paddingHorizontal: 10 }, error: { color: 'red', marginBottom: 10 }, }); export default LoginScreen;b. Handling Registration (Optional)
Similarly, you can create a registration screen to handle user sign-ups. The process is analogous to the login screen but hits the
/api/auth/registerendpoint instead.
2. Storing the JWT Token Securely
To make the JWT token accessible throughout your application, you should use a centralized state management system. React Context API is a great choice for this purpose. Additionally, to persist the token across app restarts, you'll utilize AsyncStorage.
a. Install Necessary Dependencies
npm install @react-native-async-storage/async-storageb. Create an Authentication Context
// context/AuthContext.js import React, { createContext, useState, useEffect } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; export const AuthContext = createContext(); export const AuthProvider = ({ children }) => { const [authToken, setAuthToken] = useState(null); const [loading, setLoading] = useState(true); const signIn = async (token) => { setAuthToken(token); await AsyncStorage.setItem('authToken', token); }; const signOut = async () => { setAuthToken(null); await AsyncStorage.removeItem('authToken'); }; const loadToken = async () => { try { const token = await AsyncStorage.getItem('authToken'); if (token) setAuthToken(token); } catch (e) { console.log('Failed to load token'); } finally { setLoading(false); } }; useEffect(() => { loadToken(); }, []); return ( <AuthContext.Provider value={{ authToken, signIn, signOut }}> {!loading && children} </AuthContext.Provider> ); };c. Wrap Your App with the AuthProvider
// App.js import React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { AuthProvider } from './context/AuthContext'; import AppNavigator from './navigation/AppNavigator'; const App = () => { return ( <AuthProvider> <NavigationContainer> <AppNavigator /> </NavigationContainer> </AuthProvider> ); }; export default App;
3. Accessing the Token Across Your Application
With the
AuthContextset up, any component wrapped withinAuthProvidercan access the authentication state.a. Setting Up Navigation
Assuming you are using
react-navigation, set up your navigation to handle authenticated and unauthenticated states.npm install @react-navigation/native @react-navigation/stack// navigation/AppNavigator.js import React, { useContext } from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import { AuthContext } from '../context/AuthContext'; import LoginScreen from '../screens/LoginScreen'; import ExercisesScreen from '../screens/ExercisesScreen'; import HomeScreen from '../screens/HomeScreen'; // Example other screen const Stack = createStackNavigator(); const AppNavigator = () => { const { authToken } = useContext(AuthContext); return ( <Stack.Navigator> {authToken ? ( // Screens available after authentication <> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Exercises" component={ExercisesScreen} /> {/* Add other protected screens here */} </> ) : ( // Authentication screens <Stack.Screen name="Login" component={LoginScreen} options={{ headerShown: false }} /> )} </Stack.Navigator> ); }; export default AppNavigator;
4. Passing the Token to Components like
ExerciseListNow that the token is accessible via
AuthContext, you can pass it directly to any component that requires it, such asExerciseList.a. Update the
ExercisesScreento Use AuthContextInstead of relying on navigation parameters, access the token directly from
AuthContext.// screens/ExercisesScreen.js import React, { useContext } from 'react'; import { View, StyleSheet, Button } from 'react-native'; import ExerciseList from '../components/ExerciseList'; import { AuthContext } from '../context/AuthContext'; const ExercisesScreen = () => { const { authToken, signOut } = useContext(AuthContext); return ( <View style={styles.container}> <Button title="Logout" onPress={signOut} /> <ExerciseList token={authToken} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1 }, }); export default ExercisesScreen;b. Modify
ExerciseListto Handle Token PropEnsure your
ExerciseListcomponent correctly receives and utilizes the token.// components/ExerciseList.js import React, { useEffect, useState } from 'react'; import { View, Text, FlatList, Image, StyleSheet } from 'react-native'; import axios from 'axios'; const ExerciseList = ({ token }) => { const [exercises, setExercises] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchExercises = async () => { try { const res = await axios.get('http://your-backend-url/api/exercises', { headers: { Authorization: token, }, }); setExercises(res.data); } catch (err) { setError(err.response?.data?.message || 'Failed to fetch exercises'); } finally { setLoading(false); } }; fetchExercises(); }, [token]); const renderItem = ({ item }) => ( <View style={styles.itemContainer}> {item.imageUrl && <Image source={{ uri: item.imageUrl }} style={styles.image} />} <Text style={styles.title}>{item.name}</Text> <Text>{item.description}</Text> {item.videoUrl && <Text style={styles.link}>Video Tutorial: {item.videoUrl}</Text>} </View> ); if (loading) return <Text>Loading exercises...</Text>; if (error) return <Text style={styles.error}>{error}</Text>; return ( <FlatList data={exercises} keyExtractor={(item) => item._id} renderItem={renderItem} /> ); }; const styles = StyleSheet.create({ itemContainer: { padding: 10, borderBottomWidth: 1, borderColor: '#ccc' }, image: { width: '100%', height: 200 }, title: { fontSize: 18, fontWeight: 'bold' }, link: { color: 'blue', marginTop: 5 }, error: { color: 'red', padding: 10 }, }); export default ExerciseList;
5. Ensuring Token Persistence Across App Restarts
Using
AsyncStoragewithin theAuthContextensures that the token persists even after the app is closed or restarted.a. Load Token on App Start
As defined earlier in the
AuthContext, theloadTokenfunction retrieves the token fromAsyncStoragewhen the app initializes.useEffect(() => { loadToken(); }, []);Explanation:
- When the
AuthProvidermounts, it callsloadTokento fetch any existing token fromAsyncStorage. - If a token exists, it sets it in the state, allowing the user to remain authenticated without logging in again.
Additional Recommendations
1. Secure Storage
While
AsyncStorageis convenient, it's not the most secure method for storing sensitive information like JWT tokens. For enhanced security, especially for production apps, consider using libraries likereact-native-keychainorexpo-secure-storeif you're using Expo.2. Handling Token Expiration
Implement logic to handle token expiration gracefully:
-
Auto Logout: Detect when the token has expired (e.g., receiving a 401 Unauthorized response) and prompt the user to log in again.
-
Token Refresh: Implement refresh tokens on the backend to issue new JWT tokens without requiring the user to log in again.
3. Protecting Admin Routes
In your backend, ensure that certain routes (e.g., adding new exercises) are protected and accessible only by admin users. This typically involves:
- Extending your JWT payload to include user roles.
- Creating middleware that checks for both authentication and authorization.
4. User Feedback and Loading States
Enhance user experience by adding loading indicators and better error handling across your screens and components.
Full Example Flow
To tie everything together, here's a simplified flow of how the authentication and token passing works within your app:
-
User Launches App:
AuthProviderchecksAsyncStoragefor an existing token.- If a token exists, sets
authTokenin state, and the user is navigated to the main app screens. - If no token exists, the user is presented with the
LoginScreen.
-
User Logs In:
- User enters email and password on
LoginScreen. - Credentials are sent to the backend
/api/auth/loginendpoint. - On success, the backend responds with a JWT token.
signInfunction is called with the token, storing it inAuthContextandAsyncStorage.- User is navigated to the main app screens.
- User enters email and password on
-
Accessing Protected Resources:
ExercisesScreenaccesses the token fromAuthContext.- Passes the token to
ExerciseList. ExerciseListuses the token in theAuthorizationheader to fetch exercises from the backend.
-
User Logs Out:
- User taps the logout button in
ExercisesScreen. signOutclears the token fromAuthContextandAsyncStorage.- The user is navigated back to the
LoginScreen.
- User taps the logout button in
By following this approach, you create a scalable and secure authentication system within your React Native application, ensuring that components like
ExerciseListreceive the necessary JWT token to function correctly.Feel free to ask if you need further clarifications or assistance with any specific part of this implementation!