Home > OS >  Flutter/Firebase read specific user's file from app
Flutter/Firebase read specific user's file from app

Time:06-14

I have question regarding Firebase, I'm making a Flutter App that uses Firebase for user authentication with email & password which is already done, now each user would have specific document (.pdf) uploaded in Storage via console and only that user would have access to his own document that would be shown in the app once he's logged in.

My question is, based on quick research I've noticed that I cannot set a unique ID to a file in storage (if i upload an image for example), so how can I determine that only a specific user can have access to a specific file. I've also taken a look into Firebase Security Rules but I'm not sure if that's enough to determine or do I need custom written code in Flutter as well?

Thanks.

CodePudding user response:

enter image description hereget .pdf location from firebase storage(access token) then you should have 'users' collection with documentId of current user(like shown on the picture) and save .pdf location in the document.

so every time user loggedin get current user id

var firebaseUser = await FirebaseAuth.instance.currentUser().uid;

 @override
 void initState() {
   super.initState();
    setState(() {
     getPdf();
   });
  }




void getPdf(){
Firestore.instance
    .collection("user")
    .document(firebaseUser)
    .get()

CodePudding user response:

Expanding on @brookyounas's answer: Get the pdf location from firebase storage then you should have a 'users' collection with documentId of the current user and save the pdf location (link) in that document.

For getting this storage file link, use:

String fileUrl = "";
Future uploadFile() async {
  showLoading();
  String fileName = ""; //give your file name or just use the firebaseUserId
  var ref = FirebaseStorage.instance
    .ref()
    .child('UserPDFs')
    .child('$fileName.pdf');
  await ref.putFile(file!).then((val) async {
    fileUrl = await val.ref.getDownloadURL();
    setState(() {});
    log("file url: $fileUrl");
    await FirebaseFirestore.instance.collection("users").update({"pdfFileUrl":fileUrl});
    dismissLoadingWidget();
  });
}

so every time user is logged-in, get the current user-id and then use it.

var firebaseUserId = await FirebaseAuth.instance.currentUser().uid;
String pdfFileUrl = "";

 @override
 void initState() {
   super.initState();
    setState(() {
     getPdf();
   });
  }




void getPdf(){
Firestore.instance
    .collection("users")
    .doc(firebaseUserId) //changed to .doc because .document is deprecated
    .get().then({
     pdfFileUrl = value[fileUrl];         
    });

after this use this link with : syncfusion_flutter_pdfviewer - a package for viewing pdfs online

more on this here: A StackOverflow post about this

  • Related