Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

[iOS]FCMを用いたプッシュ通知を、以前の HTTP から HTTP v1 に移行する方法について [closed]

以前の HTTP から HTTP v1 に移行するために、サーバーキーではなく、OAuth 2.0 アクセス トークンが必要になりました。 ただ、この取得方法がわかりません。

旧 Authorization: key=AIzaSyZ-1u...0GBYzPu7Udno5aA 新(↓これを取得したい) Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

swiftでコーディングしたいのですが、どうしたら良いでしょうか?

秘密鍵をダウンロードし、OAuth2のアクセストークンを取得しようとしたのですが、クライアントIDはあっても、クライアントシークレットの情報がなく、できませんでした。

react-router-dom is not working for nested page and sub-pages for react application in sub-directory

I am working on react application using vite and I am using latest version of react-router-dom v 6.23.0. My react application is build on the subdirectory (./new-mobile/dist) of main directory.

Here is my main.tsx file

import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import store from '../redux/store.js'
import { Provider } from 'react-redux'
import {RouterProvider, createBrowserRouter} from 'react-router-dom';
import App3 from './App3'
import TestFile from './TestFile'

const basename = '/new-mobile/dist';

const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        path: 'testfile',
        element: <TestFile />
      }
    ]
  },
  {
    path: 'app3',
    element: <App3 />
  }
],
{
  basename: basename
});

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <Provider store={store}>
    <RouterProvider router={router} />
  </Provider>
);

And here is the vite.config.ts file

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import Checker from 'vite-plugin-checker';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    Checker({ typescript: true }),
  ],
  base: './new-mobile/dist'
})

The main problem is when i am going on home page https://my-domain/new-mobile/dist it it working correctly, but when I go to its nested page (https://my-domain/new-mobile/dist/testfile) or child/sub-page like (https://my-domain/new-mobile/dist/app3) it breaks outs.

Also, this router is working fine on my local setup but breaks on test environment.

Things I tried: I tried adding basename but is is also not working. I tried jsx version of router, but still not working.

when I try to access /app3, this comes. broser image

App attestation failed with Firebase App check in release on Android

I'm integrating Firebase App Check into my Android app and have configured it with the SHA-256 certificate fingerprint from my Google key. However, the setup isn't working, and all requests to Firebase are blocked.

Error output: Error getting App Check token; using placeholder token instead. Error: n8.j: Error returned from API. code: 403 body: App attestation failed.

I've followed the docs:

Enabled APIs

Add the code in my app

 Firebase.initialize(context = this)
        if (BuildConfig.DEBUG) {
            Firebase.appCheck.installAppCheckProviderFactory(
                DebugAppCheckProviderFactory.getInstance(),
            )
        } else {
            Firebase.appCheck.installAppCheckProviderFactory(
                PlayIntegrityAppCheckProviderFactory.getInstance(),
            )
        }

Added the SHA256 of the signature key provided in the Play console -> key management section

It works on debug but not on release.

Is there a specific setting that I might be missing, or could this be an issue with the fingerprint itself?

Question about firebase data management and data restructuring

I am currently writing a chat app using react native. In my app, I am trying to fetch data from firebase and restructure it so that it can be displayed in the flatList of the chatscreen of my app. I have written the below code to achieve the aforementioned action:

const [groupChatMessageData, setGroupChatMessageData] = useState();
const [testMessages, setTestMessages] = useState();
const groupId = props.route.params && props.route.params.chatId;

const getNewGroupMessages = async (chatId) => {
  try {
    const app = getFirebaseApp();
    const dbRef = ref(getDatabase(app));
    const messagesRef = child(dbRef, `messages/${chatId}`);

    const snapshot = await get(messagesRef);
    return snapshot.val();
  } catch (error) {
    console.log(error);
  }
};

useEffect(() => {
    if (!groupId) return;
    const getGroupMessages = async () => {
      const data = await getNewGroupMessages(groupId);
      setGroupChatMessageData(data);
    };
    getGroupMessages();

    if (groupChatMessageData) {
      const groupChatMessages = [];
      for (const key in groupChatMessageData) {

        const message = groupChatMessageData[key];

        groupChatMessages.push({
          key,
          ...message,
        });
      }

      setTestMessages(groupChatMessages);
    } else {
      return;
    }
  }, []);

  console.log("groupChatMessageData");
  console.log(groupChatMessageData);

  console.log("groupChatMessages");
  console.log(groupChatMessages);

  console.log("testMessages");
  console.log(testMessages);


The data structure of "groupChatMessageData" is as follows:

{"-abcdefg": {"readBy": {" abcdefg ": [Object]}, "sentAt": "2024-04-26T07:16:19.414Z", "sentBy": "abc123", "text": "Hi"}, "-bcdefgh": {"readBy": {" bcdefgh ": [Object]}, "sentAt": "2024-04-27T05:17:36.020Z", "sentBy": " bcd234 ", "text": "Hi"}}

After running the code, I expect that there would be terminal logs showing for "groupChatMessageData", "groupChatMesages" and "testMesages". However, it appears that only the "groupChatMessageData"can be fetched from the firebase but the data restructuring of "groupChatMessageData" to "groupChatMesages" failed. Moreover, it appears weird that the "testMessages" can sometimes be shown on the terminal log (when I commented out the "groupChatMessages") but sometimes failed. Regardless of the aforemtnioned, the data stored in the "testMessages" can never be displayed in the flatList.

Grateful if anyone could help. Thanks in advance!

How to fix this : Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)

I am a newbie for create mobile app on Android studio. I got an error that is ,show below

Logcat show

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

at comm.example.login_logout.Login.onCreate(Login.java:64)

// i go to this line but i don't have any idea. When i run app it can built but it still crash.

my xml file : activity_login.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Login"
android:orientation="vertical"
android:gravity="center"
android:padding="15dp">

<!--Login-->
<TextView
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:gravity="center"
    android:text="@string/login"
    android:textSize="25sp"
    android:textStyle="bold" />

<!--Email-->
<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/email"
        android:hint="@string/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>

<!--Password-->
<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/password"
        android:hint="@string/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>

<ProgressBar
    android:id="@+id/progressBar"
    android:visibility="gone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<!--Button-->
<Button
    android:id="@+id/btn_login"
    android:text="@string/login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:textStyle="bold"
    android:textSize="15sp"
    android:gravity="center"
    android:layout_marginTop="20dp"
    android:id="@+id/registerNow"
    android:text="@string/click_to_register"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

Java file : Login.java

    package com.example.login_logout;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.login_logout.R.id;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.util.concurrent.CountedCompleter;

public class Login extends AppCompatActivity {

TextInputEditText editTextEmail, editTextPassword;
Button buttonLogin;
FirebaseAuth mAuth;
ProgressBar progressBar;
TextView textView;

@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if(currentUser != null){
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        finish();
    }
}


@SuppressLint("MissingInflatedId")
@Override
protected  void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);


    mAuth = FirebaseAuth.getInstance();
    editTextEmail = findViewById(R.id.email);
    editTextPassword = findViewById(R.id.password);
    buttonLogin = findViewById(R.id.btn_login);
    progressBar = findViewById(R.id.progressBar);
    textView = findViewById(R.id.registerNow);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), Register.class);
            startActivity(intent);
            //finish();
        }
    });

    buttonLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressBar.setVisibility(View.VISIBLE);
            String email,password;
            email = String.valueOf(editTextEmail.getText());
            password = String.valueOf(editTextPassword.getText());

            // check it empty or not
            if (TextUtils.isEmpty(email)) {
                Toast.makeText(Login.this,"Enter email", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(Login.this,"Enter password", Toast.LENGTH_SHORT).show();
                return;
            }

            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            progressBar.setVisibility(View.GONE);
                            if (task.isSuccessful()) {
                                Toast.makeText(getApplicationContext(), "Login Successful",Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(Login.this, "Authentication failed.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    });
}
}

How can I fix this problem ?

Setting a hosting site in a firebase project

I am facing some weird problem with setting a hosting site in a firebase project.

Here is the situation.

I want to use this name as a hosting site in my firebase project:

https://worldwonders.webapp.com/

But if I try to set it up, I get this message:

Site ID is unavailable. Available: worldwonders-9709b

At this point all is clear since I am already using the URL:

https://worldwonders.webapp.com/

inside another firebase project.

From now on things get less clear. I go to my other project and remove the site using worldwonders.webapp.com. It therefore becomes available for use.

The problem is that when I come back to my original project to set the hosting site the way I want, I still get the same kind of message as before, though the URL has been freed. What am I missing ? Or what do I need to do to keep using the URL below ? (that I was using up to now)

https://worldwonders.webapp.com/

Get URL Image From Firebase Storage

i have already stored the image in the firebase storage with the path is "Avatar/Assists/0654234.jpg". and i use this code from chat gpt. But the problem i have is it's said "firebase.storage is not a function". IS there another way that i can get URL image from storage?

 const express = require('express')
     const bodyParser = require('body-parser')
     const admin = require('firebase-admin')
     const serviceAccount = require("./serviceAccountKey.json")
     const functions = require('firebase-functions')
        const path = require('path')
        const firebase = require('firebase/app');
     require('firebase/storage');

const firebaseConfig = {
  apiKey: "AIzaSyDioYAzvJooHpspr8Z58bImI0s2jaIRU90",
  authDomain: "testlogin-c11b6.firebaseapp.com",
  projectId: "testlogin-c11b6",
  storageBucket: "testlogin-c11b6.appspot.com",
  messagingSenderId: "598921663451",
  appId: "1:598921663451:web:8bc05bbb07d312f1650dfe",
  measurementId: "G-4N0GNYZQ8J"
};

firebase.initializeApp(firebaseConfig);


admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL : "https://testlogin-c11b6-defaultrtdb.firebaseio.com/"
})


const app = express()
const db = admin.database();
const PORT = 80

let paths = "Avatar/Assist/0654234.jpg"
const storageRef = firebase.storage().ref().child(paths);
storageRef.getDownloadURL()
  .then((url) => {
console.log( url);

  })
  .catch((error) => {
   console.error(error);
 });

Firebase screenshot uploading system in unity

i am trying to code a screenshot system the takes a screenshot then uploads it to firebase storage idk how to do it can someone make me one i can just edit i just cant figure it out ive been trying to find someone to help but i cant find anyone to help i need someone to just help make this reach out if you can help it would really be needed for my app i am making in unity and i would be very thankful.

ive been trying to find someone to help but i cant find anyone to help i need someone to just help make this reach out if you can help it would really be needed for my app i am making in unity and i would be very thankful.

Protect OpenAI key using Firebase function

I have an app that uses OpenAI and like many others my key was recently compromised.

I have this simple code:

const functions = require('firebase-functions');
const OpenAI = require("openai");

const openai = new OpenAI({
    apiKey: functions.config().openai.key,
});

exports.generateText = functions.https.onCall(async (data, context) => {

  try {

    const response = await openai.chat.completions.create({
      messages: [{ role: 'user', content:  data.prompt }],
      model: 'gpt-3.5-turbo',
   });

   return { response: response.choices[0].message.content };

   } catch (error) {

    throw new functions.https.HttpsError('internal', 'Failed to generate text from OpenAI.');
  }
});

that I then call within my iOS app as follows:

let functions = Functions.functions()
func generateText(prompt: String, completion: @escaping (String?, Error?) -> Void) {
    
    functions.httpsCallable("generateText").call(["prompt": prompt]) { result, error in
        
        if let error = error as NSError? {
            if error.domain == FunctionsErrorDomain {
                let code = FunctionsErrorCode(rawValue: error.code)
                let message = error.localizedDescription
                let details = error.userInfo[FunctionsErrorDetailsKey]
                
                print(code, message, details)
                return
            }
        }
        
        if let textResponse = (result?.data as? [String: Any])?["response"] as? String {
            completion(textResponse, nil)
        } else {
            completion(nil, NSError(domain: "AppErrorDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to parse function response"]))
        }
    }
}

However as I'm not a backend engineer, I'm wondering if this is secure, or what is to stop someone using this endpoint? E.g. is this automatically restricted to being called from my app? Is there a way to do that?

I note other responses ask to authenticate the user via a login, but I would rather avoid that within my app.

Thank you!

How to read new child from firebase in an android app?

I am creating a app that will read data from firebase and display it on a map. The app keeps crashing because there are hell lot of records to retrieve from the database. I need a way with which I get only the latest node data and not the entire data snapshot.

MainActivity.java:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback{
    FirebaseDatabase db;
    DatabaseReference dbReference;
    TextView speed_disp;
    public List<LatLng> polygon;

    public double getLatitude() {
        return latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    private GoogleMap googleMap;

    private double latitude=19.10815888216128;
    private double longitude=72.83706388922495;

    public void setCord(String lat,String lon){
        this.latitude=Double.parseDouble(lat);
        this.longitude=Double.parseDouble(lon);
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        polygon = new PolyList<>(10);
        setContentView(R.layout.activity_main);

        db = FirebaseDatabase.getInstance();
        speed_disp=findViewById(R.id.speed);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
//        }

        try{
            dbReference = db.getReference("Data");
            dbReference.addValueEventListener(new ValueEventListener() {



                @Override
                public void onDataChange(@NonNull DataSnapshot datasnapshot) {
                    Log.d("Lat",datasnapshot.getValue().toString());
                    for (DataSnapshot snapshot: datasnapshot.getChildren()) {

                        String latitude = snapshot.child("lat").getValue(String.class);
                        String longitude = snapshot.child("lon").getValue(String.class);
                        String speed = snapshot.child("speed").getValue(String.class);

                        speed_disp.setText(speed);
                        setCord(latitude,longitude);
                        googleMap.clear();


                        double lat = getLatitude();
                        double lon = getLongitude();

                        LatLng current=new LatLng(lat,lon);


                        // Add marker position to polygon list
                        polygon.add(current);

                        // Draw polyline
                        if (polygon.size() >= 2) {
                            PolylineOptions polylineOptions = new PolylineOptions()
                                    .addAll(polygon)
                                    .width(5)
                                    .color(Color.RED);
                            googleMap.addPolyline(polylineOptions);
                        }

                        googleMap.addMarker(new MarkerOptions().position(current).title("Current Location"));

                        // Move camera to marker
                        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(current,20 ));

                    }


                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Toast.makeText(MainActivity.this,"Read error!!!",Toast.LENGTH_SHORT).show();
                }


            });
        }catch (Error e) {
            Toast.makeText(MainActivity.this, "Read module error", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap=googleMap;
        googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

//        LatLng current=new LatLng(19.10815888216128,72.83706388922495);
//        this.googleMap.addMarker(new MarkerOptions().position(current).title("Dub maro pls!!"));
//        this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(current));



    }


}

Firebase:

The keys are uniquely generated

I want to read only the newest node from the real-time database. Also, I would appreciate if you guys could improve my code.

NuxtImage with IPX Provider Returns 404 for Images on Firebase Hosting

I've deployed a Nuxt 3 application with Server-Side Rendering (SSR) on Firebase, utilizing Firebase Hosting and Cloud Functions. My app uses the Nuxt Image module with the default IPX provider for image optimization. While everything functions as expected in the local development environment, I encounter a persistent issue in production: all optimized images return a 404 Not Found error.

Example issue:

In production, attempting to access optimized images via URLs structured like /_ipx/f_webp&s_1460x722/images/hero.png results in a 404 error. These URLs are generated by the Nuxt Image module and work without issue locally.

Example use (default configuration):

<NuxtPicture src="/hero.png" preload sizes="sm:100vw lg:1460px" height="722" width="1460" alt="Hero billede" :img-attrs="{ class: 'w-full' }" />

Does anyone know how to fix this?

Show Spinner selection in text view

I have this code below which grabs data from my firebase database, works great! However I now wish to add another feature. when the have made a selection how do I then get the text to show in a text view. My text view Id is 'mTxt'. Please could someone kindly help, I have been trying for hours. I have watched many tutorials however still no luck. Thanks in advance.

My Spinner code:

spinnerV = findViewById(R.id.spinner);

    spinnerRef = FirebaseDatabase.getInstance().getReference("Spinner");

    spinnerList = new ArrayList<>();
    adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, spinnerList);

    spinnerV.setAdapter(adapter);
    Showdata();

}

private void Showdata() {
    spinnerRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            for (DataSnapshot item : snapshot.getChildren()) {
                spinnerList.add(item.getValue().toString());

            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

when inserting value into firebase database it wont store correctly

I have been trying to resolve this, with no joy..

I have a text box, when you enter a name into the text box, and press submit it will upload to firebase. Then a spinner in an app will show they names.

this is the code to upload which uploads the input data to the Realtime database.

function InsertData() {
        push(ref(db, "Spinner/" ),{
            Name: enterName.value
        })

I have attached a picture. the code above when I submitted the name 'Matthew' you will see it sores it as a child under the random key. I need it to store inline exactly like the 'test one you can see at the top.I hope this makes sense.

enter image description here

How to pass MUI Datagrid props to Modal on Action Button Click

I have a datagrid that displays some user data that I have existin in my Firebase DB. At the end of each row on the table, I have an action button that I am looking to display a modal when clicked.

I have the table and modal set up, but am wondering how I should pass the data from each row to the modal when it is clicked.

Here is the code for the datagrid:

const columns = [
{ field: 'firstName', headerName: 'First Name', width: 100 },
{ field: 'lastName', headerName: 'Last Name', width: 100 },
{ field: 'email', headerName: 'Email', width: 150 },
{ field: 'permission', headerName: 'Role', width: 100 },
{ field: 'street', headerName: 'Address', width: 150 },
{ field: 'city', headerName: 'City', width: 100 },
{ field: 'livingState', headerName: 'State', width: 100 },
{ field: 'zip', headerName: 'Zip', width: 100 },
{
    field: "action",
    headerName: "Action",
    sortable: false,
    renderCell: (params) => {
      const onClick = (e) => {
        // Enter logic to pass data to modal here
      };

      return <Button onClick={handleOpen}>
      <ModeIcon />
      
      </Button>;
    }
  },

];

Here is what the table looks like (Action button on the end of each row)

Datagrid

React frontend Admin panel ( Firebase Auth email/password ) & Mongodb

im buildig ReactJS Frontend Admin panel for my Nodejs project it uses Firebase Auth and mongodb my proble is whatever i do the Dashboard always blank after redirect succuess login Files as following:

App.js

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { AuthContextProvider } from './AuthContext';
import PrivateRoute from './PrivateRoute';
import Login from './Login';
import Dashboard from './Dashboard'; // Import Dashboard.js here
import './App.css';

function App() {
  return (
    <BrowserRouter>
      <AuthContextProvider>
        <Routes>
          <Route path="/" element={<Login />} /> {/* Public route */}
          <Route
            path="/dashboard"
            element={
              <PrivateRoute>
                <Dashboard /> {/* Dashboard component here */}
              </PrivateRoute>
            }
          />
        </Routes>
      </AuthContextProvider>
    </BrowserRouter>
  );
}

export default App;

and AuthContext.js

import React, { createContext, useContext, useState } from 'react';

const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);

  const login = (user) => {
    setCurrentUser(user);
  };

  const logout = () => {
    setCurrentUser(null);
  };

  return (
    <AuthContext.Provider value={{ currentUser, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthContextProvider');
  }
  return context;
};

and PrivateRoute.js

import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from './AuthContext'; // Import useAuth hook

const PrivateRoute = () => {
  const { currentUser } = useAuth(); // Use the useAuth hook to access currentUser

  return currentUser ? <Outlet /> : <Navigate to="/" replace />;
};

export default PrivateRoute;

and index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

and Login.js

import React, { useState } from "react";
import { auth } from "./firebase-config"; // Import your Firebase app
import { signInWithEmailAndPassword } from "firebase/auth"; // Import from Firebase
import { useNavigate } from "react-router-dom"; // Import for navigation
import { useAuth } from "./AuthContext"; // Import AuthContext using useAuth

const Login = () => {
  const [error, setError] = useState(null);
  const navigate = useNavigate();
  const { login } = useAuth(); // Use the useAuth hook to access setCurrentUser

  const handleLogin = async (e) => {
    e.preventDefault();
    try {
      const userCredential = await signInWithEmailAndPassword(
        auth,
        e.target.email.value,
        e.target.password.value
      );

      // Set a success message
      setError("Login Successful!");

      // Update currentUser in AuthContext (assuming your AuthContext manages user state)
      login(userCredential.user);

      // Redirect to Dashboard after successful login
      navigate("/dashboard");
    } catch (error) {
      setError(error.message); // Set the error message in the state
    }
  };

  return (
    <div className="login-container">
      <div id="root" className="min-h-100vh flex grow bg-slate-50 dark:bg-navy-900" x-cloak="true">
        <main className="grid w-full grow grid-cols-1 place-items-center">
          <div className="w-full max-w-[26rem] p-4 sm:px-5">
            <div className="text-center">
              <img className="mx-auto w-32" src="assets/images/logo.png" alt="logo"/>
              <div className="mt-4">
                <h2 className="text-2xl font-semibold text-slate-600 dark:text-navy-100">
                  Welcome Back
                </h2>
                <p className="text-slate-400 dark:text-navy-300">
                  Please sign in to continue
                </p>
              </div>
            </div>
            <form onSubmit={handleLogin} className="card mt-5 rounded-lg p-5 lg:p-7">
              <label className="block">
                <span>Username:</span>
                <span className="relative mt-1.5 flex">
                  <input className="form-input peer w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 pl-9 placeholder:text-slate-400/70 hover:z-10 hover:border-slate-400 focus:z-10 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" placeholder="Enter Username" type="email" id="email" required/>
                  <span className="pointer-events-none absolute flex h-full w-10 items-center justify-center text-slate-400 peer-focus:text-primary dark:text-navy-300 dark:peer-focus:text-accent">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 transition-colors duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                    </svg>
                  </span>
                </span>
              </label>
              <label className="mt-4 block">
                <span>Password:</span>
                <span className="relative mt-1.5 flex">
                  <input className="form-input peer w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 pl-9 placeholder:text-slate-400/70 hover:z-10 hover:border-slate-400 focus:z-10 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent" placeholder="Enter Password" type="password" id="password" required/>
                  <span className="pointer-events-none absolute flex h-full w-10 items-center justify-center text-slate-400 peer-focus:text-primary dark:text-navy-300 dark:peer-focus:text-accent">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 transition-colors duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
                    </svg>
                  </span>
                </span>
              </label>
              
    {error && (<div class="alert flex space-x-2 rounded-lg border border-error px-4 py-4 text-error">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
      <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
    </svg>
    <p>{error === 'Login Successful!' ? 'Success!' : error}</p>
    </div>)}

      <p className="error-message"></p>
                <button type="submit" className="btn mt-5 w-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">Login</button>
            </form>
          </div>
        </main>
      </div>

      <div id="x-teleport-target"></div>
    </div>
  );
};

export default Login;

the package.json

{
  "name": "admin-panel",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.11.4",
    "@emotion/styled": "^11.11.0",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "firebase": "^10.8.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.22.3",
    "react-scripts": "^3.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8000",
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Finally the Dashboard.js component

import React, { useState, useEffect } from 'react';
import { useAuth } from './AuthContext'; // Import useAuth hook

const Dashboard = () => {
  const { currentUser } = useAuth(); // Access currentUser from AuthContext
  const [error, setError] = useState(null); // State for error message

  // Fetch error data from your backend or state management solution (if applicable)
  useEffect(() => {
    const fetchErrorData = async () => {
      try {
        // Replace with your actual error data fetching logic (e.g., API call)
        const response = await fetch('/api/dashboard/errors'); // Example API call
        const errorData = await response.json();
        setError(errorData?.message); // Update error state with fetched message
      } catch (error) {
        console.error('Error fetching error data:', error);
      }
    };

    fetchErrorData();
  }, []);

  return (
    <div className="dashboard-container">
      <h1 className="dashboard-heading">Welcome, {currentUser.displayName || currentUser.email}!</h1>
      {error && (
        <div className="error-log alert alert-error">
          <svg className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.7-7.29a4 4 0 00-2.82-2.82L13.7 6.9l-1.41-1.41a4 4 0 00-2.82 2.82l-1.41 1.41L6.9 13.7a4 4 0 002.82 2.82L10 16.1l1.41 1.41a4 4 0 002.82-2.82l1.41-1.41z" clipRule="evenodd" />
          </svg>
          <p>{error}</p>
        </div>
      )}
      <p className="dashboard-message">You are now logged in to your dashboard.</p>

      {/* Additional dashboard content and features go here */}
    </div>
  );
};

export default Dashboard;

i almost tried everything without any success also i browser consoel i got the following error : Uncaught SyntaxError: Identifier 'observeDomChanges' has already been declared (at ruleApplier.js:1:1)

but there is no ruleApplier.js in the project at all and the docx for react and firebase have nothing about it :( anyone faced such issue ?!! any suggestion will be helpful at this point :D

Unable to send Firebase push notification via remote server

I have a springboot project and added firebase dependency and all related things. When I run the project locally, everything works fine. I am using firebase admin sdk to send notifications. The code for sending is:

try {
            messagingService.send(message);
            logger.info("Firebase notification sent to user: "+user.getUsername());
            saveLog(true, "Notification Sent", pushNotificationLog);
            return true;
        }catch (FirebaseMessagingException e) {
            logger.info("Firebase did not send notification to user: "+user.getUsername()+ " Error Message: "+e.getMessage());
            saveLog(false, e.getMessage(), pushNotificationLog);
            return false;
        }

As soon as I do the same on my remote server with different application properties, I get the exception while sending the notification, this is what it says: 2024-03-18 07:27:14.759 INFO 1 --- [nio-8091-exec-4] c.p.service.FirebaseNotificationService : Firebase did not send notification to user: zubair Error Message: Unknown error while making a remote service call: Error getting access token for service account: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext), iss: [email protected]

I have used cryptographic algos in some places of my code and they are working fine, only this isn't.

I tried running my local with the application properties of the remote server and it worked fine. I am unable to figure out the issue.

Firebase error: Assertion failed resolving hosting target of a site with no site name or target name

I'm going through the Firebase tutorial for create a "FriendlyChat" web app. I made it to Step 6.

At this point, it tells you to run the following command

firebase emulators:start

When I do this, however, I get an error.

firebase emulators:start i emulators: Starting emulators: auth, functions, firestore, hosting, storage i emulators: Shutting down emulators. i hub: Stopping emulator hub

Error: Assertion failed: resolving hosting target of a site with no site name or target name. This should have caused an error earlier

I've looked at my firebase.json file and see the following for hosting. Is there something wrong here?

  "hosting": [
    {
      "source": ".",
      "ignore": [
        "firebase.json",
        "**/.*",
        "**/node_modules/**"
      ],
      "frameworksBackend": {
        "region": "us-central1"
      }
    },
    {
      "target": "friendlychat",
      "source": ".",
      "frameworksBackend": {}
    }
  ],

Per the tutorial instructions, running the command "firebase emulators:start" should have resulted in the following response. hosting: Local server: http://localhost:5000. Instead, I get the described error.

Flutter UI don't display image that user uploaded even firebase storage have file

I want to build editable profile screen that user can upload their image file to profile.

When user upload image, CircleAvatar is changing but application don't save user statement. If I restart application or push another screen, It come back default image. What I confuse thing is firebase storage have image file that user uploaded.

profile_screen.dart

Uint8List? _image;

  void selectImage() async {
    Uint8List img = await imageSelector(ImageSource.gallery);
    setState(() {
      _image = img;
    });
    saveProfile();
  }

  void saveProfile() async {
    String resp = await StoreData().saveData(file: _image!);
  }
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<DocumentSnapshot>(
        stream:
            _firestore.collection('Users').doc(currentUser.email).snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final userData = snapshot.data!.data() as Map<String, dynamic>;

            return ListView(
              children: [
                const SizedBox(
                  height: 50.0,
                ),
                Stack(
                  alignment: Alignment.center,
                  children: [
                    _image != null
                        ? CircleAvatar(
                            radius: 80,
                            backgroundImage: MemoryImage(_image!),
                          )
                        : const CircleAvatar(
                            radius: 80,
                            backgroundImage: NetworkImage(
                                'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png'),
                          ),
                    Positioned(
                      bottom: -10.0,
                      right: 60.0,
                      child: IconButton(
                          onPressed: selectImage,
                          icon: const Icon(
                            Icons.edit,
                            color: Colors.grey,
                          )),
                    )
                  ],
                ),
                const SizedBox(
                  height: 15.0,
                ),
                Text(
                  currentUser.email!,
                  textAlign: TextAlign.center,
                  style: kSmallText.copyWith(color: Colors.grey[800]),
                ),
                const SizedBox(
                  height: 50.0,
                ),
                MyTextBox(
                  sectionName: 'username',
                  text: userData['username'],
                  onPressed: () => editField('username'),
                ),
                MyTextBox(
                  sectionName: 'empty bio',
                  text: userData['bio'],
                  onPressed: () => editField('bio'),
                ),
                const SizedBox(
                  height: 15.0,
                ),
                Center(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey[200],
                    ),
                    onPressed: () {
                      _auth.signOut();
                      Navigator.pushNamedAndRemoveUntil(
                          context, WelcomeScreen.id, (route) => false);
                    },
                    child: const Text(
                      'Logout',
                      style: TextStyle(
                          color: mediumComb,
                          fontSize: 15,
                          fontWeight: FontWeight.w600),
                    ),
                  ),
                ),
              ],
            );
          } else if (snapshot.hasError) {
            return Center(
              child: Text('Error${snapshot.error}'),
            );
          }
          return const CircularProgressIndicator();
        },
      ),
    );
  }
}

add_data.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'dart:typed_data';

final FirebaseStorage _storage = FirebaseStorage.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;

class StoreData {
  Future<String> uploadImageToStorage(String childName, Uint8List file) async {
    Reference ref = _storage.ref().child(childName);
    UploadTask uploadTask = ref.putData(file);
    TaskSnapshot snapshot = await uploadTask;
    String downloadUrl = await snapshot.ref.getDownloadURL();
    return downloadUrl;
  }

  Future<String> saveData({
    required Uint8List file,
  }) async {
    String resp = "Some Error Occured";
    try {
      String imageURL = await uploadImageToStorage('ProfileImage', file);
      _firestore.collection('userProfile').add({
        'imageLink': imageURL,
      });
      resp = 'success';
    } catch (err) {
      resp = err.toString();
    }
    return resp;
  }
}

image_selector.dart

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

imageSelector(ImageSource source) async {
  final ImagePicker imagePicker = ImagePicker();
  XFile? file = await imagePicker.pickImage(source: source);
  if (file != null) {
    return await file.readAsBytes();
  }
  print('No Images Selected');
}

I think it is related user statement setting or something but I don't really know how to figure out.

Image file have successfully uploaded :

enter image description here

pubspec.yaml or ios/info.plist or firebase rule setting was done.

enter image description here

enter image description here

enter image description here

I was following this two video.

https://youtu.be/BjowvNSdWYE?si=31Y4lf67LHgWHHLk

https://youtu.be/5kjjkIdwwN8?si=y45OWVVnNf8yeDPN

Thanks for reading this question

Error in Flutter : RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)

I am building an E-commerce app in flutter [Dart]. I am trying to get data from firebase where I have collection name (Vendor Collection). In this collection I have documents and some fields in that documents but when I try to access those data it return Range error.

This is my code where I got error: (https://i.stack.imgur.com/dFHcg.png)
This is my file where I created method: (https://i.stack.imgur.com/mg0TA.png)
This is my Firebase : (https://i.stack.imgur.com/X4y34.png)

Suggestions will be appreciated. Thanks in advance.

I try to print vendor name and vendor details which has in documents but I got an error. I want to access those data from firebase
❌
❌