i want to make a screen where only admin can be redirected on his admin-panel here…
- User
i want to make a screen where only admin can be redirected on his admin-panel here import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import { Feather } from ‘@expo/vector-icons’; import React, { useState, useEffect } from ‘react’; import { useNavigation } from ‘@react-navigation/native’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’;
export default function Header() { const [searchTerm, setSearchTerm] = useState(‘’);
const [searchResult, setSearchResult]= useState(‘’);
const navigation = useNavigation();
const handleSearch = async ()=>{ if(!searchTerm.trim()){ setSearchResult([]); return; } const futureMKSnapshot = await firebase .firestore() .collection(‘FutureMK’) .where(‘name’,‘>=’,searchTerm) .where(‘name’,‘<=’,searchTerm + ‘\uf8ff’) .get();
const pastMKSnapshot = await firebase .firestore() .collection(‘PastMK’) .where(‘name’,‘>=’,searchTerm) .where(‘name’,‘<=’,searchTerm + ‘\uf8ff’) .get();
const futureMKData = futureMKSnapshot.docs.map(doc => ({ id: doc.id, …doc.data(), }));
const pastMKData = pastMKSnapshot.docs.map(doc => ({ id: doc.id, …doc.data(), }));
const results = […futureMKData, …pastMKData].filter(item=> item.name.toLowerCase().includes(searchTerm.toLowerCase())); const storage=firebase.storage(); const resultWithImages = await Promise.all( results.map(async item=>{ try{ const imagePath=item.image; const imageRef=storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {… item, image:url}; }catch(error){ console.log(‘Ошибка загрузки изображения: ‘, error); return item; } }) ); setSearchResult(resultWithImages); navigation.navigate(‘Search’, { results: resultWithImages }); };
const [userAuthenticated, setUserAuthenticated] = useState(false);
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => { setIsModalVisible(true); };
const hideModal = () => { setIsModalVisible(false); };
useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } });
return unsubscribe; }, []); return ( <Image source={require(’…/assets/logo.png’)} style={gStyle.logoImg} /> Х <TouchableOpacity onPress={()=>navigation.navigate(‘Home’)}
Главная <TouchableOpacity onPress={()=>navigation.navigate(‘AllFutureMK’)}
Будущие мастер-классы <TouchableOpacity onPress={()=>navigation.navigate(‘AllPastMK’)}
Архив мастер-классов <TouchableOpacity onPress={()=>navigation.navigate(‘Sales’)}
- Assistant
To make the screen where only admin can be redirected to his admin-panel, you can add an if statement inside the TouchableOpacity that leads to the admin panel.
First, you need to create a state variable to track the user role:
const [userRole, setUserRole] = useState('');
Then, inside your useEffect function, you need to get the user role from your Firebase database:
useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); const userId = user.uid; firebase .database() .ref(
users/${userId}/role) .once('value') .then(snapshot => { const role = snapshot.val(); setUserRole(role); }); } else { setUserAuthenticated(false); } });return unsubscribe;}, []);
Now, in your TouchableOpacity that leads to the admin panel, you can add an if statement to check if the user role is admin:
{userAuthenticated ? userRole === 'admin' ? <TouchableOpacity onPress={() => navigation.navigate('AdminPanel')}> Админ-панель : null : null }
- User
- Assistant
Your code looks good, but there's a small mistake in the conditional statement inside the TouchableOpacity that leads to the admin panel.
Instead of having an if statement inside the ternary operator, you should have another ternary operator inside the original one:
{userAuthenticated ? (userRole === 'admin' ? <TouchableOpacity onPress={() => navigation.navigate('AdminPanel')}> Админ-панель : null) : null }
This way, the second ternary operator will only be evaluated if the user is authenticated, and will return the TouchableOpacity if the user has the role of admin, or null otherwise.
- User
and how can i make an admin so they can create update and delete posts? For example i have collection in firebase called Sale, how they can create post there?
- Assistant
To allow your admin users to create, update, and delete posts in your Firebase Firestore, you can set up a separate web app with Firebase Admin SDK.
First, you need to create a new service account by going to your Firebase console and selecting "Project settings" -> "Service accounts". Then, click on "Generate new private key" to download a new JSON file with your credentials.
Next, you can install the Firebase Admin SDK by running the following command in your terminal:
npm install firebase-adminAfter installing the Firebase Admin SDK, you can set up a new web app with the following code:
const admin = require('firebase-admin'); const serviceAccount = require('./path/to/serviceAccountKey.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); const db = admin.firestore(); - User
where i need to put this cod?
- Assistant
To use the Firebase Admin SDK, you need to create a separate web app in your backend server and then use it to access your Firebase Firestore.
Here are the steps you can follow to set up the Firebase Admin SDK in your Node.js environment:
-
Install the Firebase Admin SDK by running
npm install firebase-admin. -
Go to the Firebase console, select your project, and navigate to "Project settings" -> "Service accounts".
-
Click on "Generate new private key" to download a JSON file with your service account key.
-
Move the downloaded JSON file to a secure location outside of your codebase.
-
In your Node.js application, import the
firebase-adminmodule and initialize the Firebase Admin SDK with your service account key path:
-
- User
import { Text, View, TextInput, Pressable, ScrollView, Image } from 'react-native'; import { gStyle } from '../styles/style'; import Footer from '../components/Footer'; import Header from '../components/Header'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState,} from 'react';
export default function FormAddMK() { return ( Добавить скидку Название скидки ссылка Изображение {imageData ? ( <Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} /> ) : null} Выбрать изображение Сохранить
); }
do i need to add there this code or what?
- Assistant
Yes, if you want to add a new discount post to your Firebase Firestore, you can add the necessary code to your component's
addHandlerfunction:import { Text, View, TextInput, Pressable, ScrollView, Image } from 'react-native'; import { gStyle } from '../styles/style'; import Footer from '../components/Footer'; import Header from '../components/Header'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, { useState } from 'react'; export