Learn Courses My Dashboard

Stuck on custom login

Am a beginner and I just enrolled for membership am learning to build iOS app in SWIFTUI/firebase I just got login n sign up .my login goes to home page but I want to have roles so I have customised pages for different users I have read documentation and tutorials but I don’t understand how to go about it
could someone help me please

Kind regards,
Mary

Hi Mary,

I note that you already have a thread on this subject where Mikaela has been trying to help you with users that have different roles.

You have indicated that you are a beginner and for anyone new to Firebase, it can be difficult to understand how to code.

The best advice I can offer you is to follow a number of tutorials that have Firebase integrated into the App so that you get used to the syntax of how to read and write to Firestore.

Hi Chris yes I noted that I tried also the link sent by Mikaela but it’s not working I don’t get how the roles part is intergrates.
I can already login to home page but I now want to have roles to different users that’s what is hard for me.

Can someone help me

I assume you already have gone through the firebase courses in the learn swiftui (database) course.

When you are going through the sign-in workflow, make sure you add a way to associate the user role to that particular user’s metadata ( which would be in a collection called users in your firestore database )

In your app, after the user logs in, put an if statement up to check what the role of that particular user is. Based on the result, you can decide which view to show

PS: If u have trouble with firestore authentication, or just firebase in general I would advise going through modules 1-4 of the swiftui(databases) course

Hi Abdul

Thanks for your reply,yes indeed I have and I have set up basic sign up and sign in
My challenge is on how to add a way to associate the user role with that particular metadata as stated below :point_down:

(When you are going through the sign-in workflow, make sure you add a way to associate the user role to that particular user’s metadata ( which would be in a collection called users in your firestore database )

Do you have a source that specifies how to do this?

Am really in trouble for over a week with this part.

Regards

This is a sort of sample code that I whipped up from an old project.

In your view, you have to use an input to get the role when the user first signs up. Then pass it over to this function which would upload it to firebase

static func createProfile(userId: String, username: String, role: String, completion: @escaping (PhotoUser?) -> Void) {
        
        let profileData = ["username": username, "role": role]// <----- You add a role property to the profile data dict which you would upload to firebase
        
        let db = Firestore.firestore()
        
        db.collection("users").document(userId).setData(profileData) { error in
            
            if error == nil {
                
                // Succesfully created profile
                // Create and return a photo user
                let user = PhotoUser(userId: userId, username: username)
                completion(user)
                
            } else {
                
                // There was an error
                print("Couldnt create profile")
                print(error!.localizedDescription)
                completion(nil)
            }
            
        }
        
    }

This would give a database which looks like:

You can then check the user after login using something like this:

if currentUser.role == "admin" {
    // Show admin view over here
} else {
    // Show normal view over here
}

Note that this is a very high-level visualization of how to implement this, and it probably won’t work if u just copy and paste this. Since You are in the firebase courses, I assume you already know how to get the input from the user and how show different views conditionally

Hi Abdul

Thanks for your reply I will try this one and let you know how it goes

Kind regards,
Mary

Hi Abdul

Thanks for your reply I will try this one and let you know how it goes

Kind regards,
Mary

1 Like

Let me know how it goes, and if ur stuck don’t hesitate to ask :grin:

yes and thank you so much, i will let you know immediately how it goes

Kind regards.

Haha there is small progress have managed to register users with default user role, for admin I hardcoded one user in the db…
However the login code as shown below brings out a blank page when the app loads :sweat_smile:

import SwiftUI
import FirebaseAuth

struct ContentView: View {
@EnvironmentObject var userInfo:UserInfo
var body: some View {
Group{

       if userInfo.isUserAuthenticated == .undefined{
            Text("Loading")
        }
        if userInfo.isUserAuthenticated == .signedOut{
          LoginView()
        }
       if userInfo.user.role=="user"{
    
           UserNavigationView()
        }
       else if userInfo.user.role=="admin"{
           AdminHomePage()
       }
    }//end of grouup
    .onAppear{
        self.userInfo.configureFirebaseStateDidChange()
    }
}

}

changed to this code but still blank page

struct ContentView: View {
@EnvironmentObject var userInfo:UserInfo
var body: some View {
Group{

       if userInfo.isUserAuthenticated == .undefined{
            Text("Loading")
        }
        else if userInfo.isUserAuthenticated == .signedOut{
          LoginView()
        }
       //This means user is logged in cz isauthentiated==signedIn
        else{
            
            if(userInfo.user.role=="user"){
              UserNavigationView()
            }
            if (userInfo.user.role=="admin"){
               AdminHomePage()
            }
         
        }
    }//end of grouup
    .onAppear{
        self.userInfo.configureFirebaseStateDidChange()
    }
}

}

can you change the statement in your else block

to this:

if userInfo.user.role == "user"{
    
    UserNavigationView()
    
} else if (userInfo.user.role == "admin"){
    
    AdminHomePage()
    
} else {
    
    Text("Error: Not user or admin")
    
}

And let me know what you see?

Yes thanks I will and let you know

Hi Abdul
I get this

the last else for error is getting executed

here is the code after the change
if userInfo.isUserAuthenticated == .undefined{
Text(“Loading”)
}
else if userInfo.isUserAuthenticated == .signedOut{
LoginView()
}
if userInfo.user.role == “user”{

           UserNavigationView()
           
       } else if (userInfo.user.role == "admin"){
           
           AdminHomePage()
           
       } else {
           
           Text("Error: Not user or admin")
           
       }

After it executed the last statement for error have changed the code to be like this but in both cases if I log admin or user it also executes the last statement and shows user NAVIGATIONVIEW but now it can bring the login page…
Still I am wondering why does it not differentiate roles or first statement isn’t executed.
What do you think is problem?

     Group{

       if userInfo.isUserAuthenticated == .undefined{
            Text("Loading")
        }
        else if userInfo.isUserAuthenticated == .signedOut{
          LoginView()
        }
       //This means user is logged in cz isauthentiated==signedIn
           else if userInfo.isUserAuthenticated == .signedIn {
            if userInfo.user.role=="admin"{
                 HomeView()
            }
               else{
                UserNavigationView()
               
            }
         
        }
   }//Group
       .onAppear{
           self.userInfo.configureFirebaseStateDidChange()

    

   }

So it’s showing the view which should be shown if the user is not an admin…

Are you sure you have signed in with the admin user, and also that the userinfo.user.role is parsed as admin?


yes I have only 2 users admin and user…also tried to print role elsewhere and for sure the role is being retrieved correctly just done know why for sign in it aint working

maybe the parsing is the problem
tried to print role and its not being passed in this else that is being displayed

                   Text("profile for \(userInfo.user.role)")....only prints profile for  then shows the view so I think role here isn't being passed
                UserNavigationView()

changed to this too and renders same view for user

else if (userInfo.isUserAuthenticated == .signedIn )
{
if (userInfo.user.role==“admin”){
HomeView()
}

               else{
                UserNavigationView()
               
            }

I assume your issue is elsewhere in the app

Could you maybe put your XCode project in a dropbox file and share the link so I could take a look at what could be the issue?

Hi Abdul

send you as a message