Add user information with Firebase authentication. - ios

I'm implementing an Authenticate with Firebase using Password-Based Accounts on iOS. After sign-in a user we can get particular information like user.email, user.uid, user.photoURL, user.displayName. However I can set email and password as follows.
[[FIRAuth auth]
createUserWithEmail:username
password:password
completion:^(FIRUser *_Nullable user,
NSError *_Nullable error) {
}];
In here no problem to get user.email. But I didn't set other information here. How to set other information such as user.photoURL, user.displayName with above createUserWithEmail method.

You need to call FIRUserProfileChangeRequest after the user authentication to update the profile info.
FIRUserProfileChangeRequest *changeRequest =
[[FIRAuth auth].currentUser profileChangeRequest];
changeRequest.displayName = userInput;
[changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
// ...
}];
Read more on https://firebase.google.com/docs/auth/ios/manage-users

You can check my answer here.
It can help You. But its on Swift language.
Main tip that You need to store Users in database too. And have a link to image in it.
Hope it helps

Related

Firebase Phone Auth

I'm trying to add Firebase Phone Auth to an app that I'm making in XCode. However, I'm having trouble with steps 3 of the firebase documentation and everything after that.
I don't understand where my code is supposed to go. I try some of it already and I attached the image of what I have done so far. Please help.
Thank you.
Ok, the code seems right.
Now you must add another textfield where the user can add the verification code arrived from the SMS.
In a new method triggered by the user after adding the code you must set a FIRAuthCredential like in the code of the example:
FIRAuthCredential *credential = [[FIRPhoneAuthProvider provider]
credentialWithVerificationID:verificationID
verificationCode:newTextField.text!];
And then do the signin with:
[[FIRAuth auth] signInAndRetrieveDataWithCredential:credential
completion:^(FIRAuthDataResult * _Nullable authResult,
NSError * _Nullable error) {
if (error) {
// ...
return;
}
// User successfully signed in. Get user data from the FIRUser object
if (authResult == nil) { return; }
FIRUser *user = authResult.user;
// ...
}];

Swift: Firebase auth observer not called if observers of child removed

Assume ref = Firebase(url: "your firebase url").
A child of ref would be childRef = ref.childByAppendingPath("child")
If I have ref.observeAuthEventWithBlock listening for authentication changes at ref, and I then use childRef.removeAllObservers(), the auth observer at ref is no longer listening for changes.
Why is this?
I crafted up a small app to duplicate the issue (ObjC code to follow)
The code to watch for auth'ing is:
[myRootRef observeAuthEventWithBlock:^(FAuthData *authData) {
NSLog(#"got an auth event");
}];
and we have the child node
child = [myRootRef childByAppendingPath:#"child_path"];
then the initial auth is
[myRootRef authUser:#"dude#thing.com" password:#"pw" withCompletionBlock:^(NSError *error, FAuthData *authData) {
NSLog(#"authentication 1 success");
[child removeAllObservers];
[self doAuth];
}
}];
The doAuth method simply auth's another user and outputs 'authentication 2 success'
got an auth event
got an auth event
authentication 1 success
authentication 2 success
So as you can see it worked as advertised - I was unable to duplicate the issue. My guess is the error may lie somewhere else in your code.

New FBSDK 4.0+ , log in or share using access token

I am using new FBSDK. Able to get access token generated by FBSDK using
[[FBSDKAccessToken currentAccessToken]tokenString]
How can I use this to share or post without prompting user to login again?
Scenario : User Logs in via Facebook, access token gets generated, we store this access token in defaults. User shares something for this session. For future sessions when user wants to share something we use access token stored inside defaults for posting.
Please correct me if I am not getting function of access tokens...
check Permission like this...don't store access token...following code use you don't need everytime login...
if ([[FBSDKAccessToken currentAccessToken]hasGranted:#"email"])
{
// add your coding here after login call this block
}
else
{
//login code
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithReadPermissions:#[#"public_profile", #"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
}];
}
You can use this method:
- (void)continueSystemLogInWithTokenString:(NSString *)oauthToken error:(NSError *)accountStoreError state:(FBSDKLoginManagerSystemAccountState *)state;
Where oauthToken is your accessToken String
Once you have app token, you can do this:
if (oauthToken) {
completer = [[FBSDKLoginSystemAccountCompleter alloc] initWithTokenString:oauthToken appID:[FBSDKSettings appID]];
}
Note: All these methods are defined in FBSDKLoginCompletion class.
Call Heirarchy:
This method:
initWithTokenString in FBSDKLoginCompletion.m is called in continueSystemLogInWithTokenString in FBSDKLoginManager.m
and continueSystemLogInWithTokenString is called in performSystemLogIn method in FBSDKLoginManager.
performSystemLogIn is called from beginSystemLogIn in FBSDKLoginManager.
beginSystemLogIn is called from logInWithBehavior in FBSDKLoginManager.
logInWithBehavior is called from following places:
logInWithPermissions in FBSDKLoginManager
fallbackToNativeBehavior in FBSDKLoginManager
attemptBrowserLogIn in FBSDKLoginCompletion
completeLogIn in FBSDKLoginCompletion

Using Swift, Parse and the iOS FacebookSDK, how do I obtain user's name and email at login?

So I've been banging my head on this for a couple days now, and I'm hoping someone here could shed some light on this for me!
So I'm using Parse in my Swift project, and am looking to leverage the Facebook integration to make logging in and signing up a user pretty effortless.
I have managed to get as far as logging in a user, but the part where I'm stuck is that I don't know how to access the data that I requested with permissions.
In my AppDelegate Swift file, I have this block of code..
// INITIALISE FACEBOOK
let permissions = ["email", "public_profile"]
PFFacebookUtils.initializeFacebook()
PFFacebookUtils.logInWithPermissions(permissions, {
(user: PFUser!, error: NSError!) -> Void in
if user == nil {
if (error == nil) {
println("User cancelled Facebook login")
} else {
println("FB Login Error \n(error)")
}
} else if user.isNew {
println("User has signed in through Facebook!")
} else {
println("User logged in through Facebook!")
}
})
Everything is all well and dandy, and I get the "User has signed in through Facebook!" message.
According to the Parse documentation, this then creates a new User object in my database.
In my database, I see that there is indeed a new user, but the only fields that are populated are..
ObjectID - random string characters
username - random string characters
authData - a facebook type ID.
Not the username or email.
From what I have gathered, I need to now further leverage the FacebookSDK and GraphUser, but I really dont know exactly how.. or at least not in Swift.
The Parse documentation says
"The Facebook iOS SDK provides a number of helper classes for interacting with Facebook's API. Generally, you will use the FBRequest class to interact with Facebook on behalf of your logged-in user. You can read more about the Facebook SDK here.
Our library manages the user's FBSession object for you. You can simply call [PFFacebookUtils session] to access the session instance, which can then be passed to FBRequests."
But I really dont know what to type or where to type it. :(
It feels like I'm really close with this, but I'm just hitting blanks..
If someone could be kind enough to shed some light into this (how to access the details I requested permission for, i.e. full name and email) I would be incredibly grateful!
Thank you.. :)
You may try this (for Swift):
// Obtain User Data via Facebook Login
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"name, email"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
}
else
{
let userName: String = result.valueForKey("name") as! String
let Email: String = result.valueForKey("email") as! String
println(userName)
println(Email)
}
})
}
According to this: https://parse.com/questions/how-can-i-get-the-facebook-id-of-a-user-logged-in-with-facebook
You get the Facebook ID with this Objective-C
// After logging in with Facebook
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *facebookId = [result objectForKey:#"id"];
}
}];
Which is this in Swift (not tested)
FBRequestConnection.startForMeWithCompletionHandler { connection, result, error in
if (!error) {
let facebookId = result["id"]
// use facebookID
}
}

iOS Parse validating user

I want to write code in AppDelegate.m that checks if PFUser.currentUser credentials are still valid. The reason I am doing this is for this scenario. Assume user logged in successfully and now currentUser has the basic information of that user. If the user changes the password at some time, when application launch, it should check if those credentials are up to date or not. If email & password doesn't match the one in table, it should log the user out.
I tried to do this but apparently PFUser.currentUser.password is always set to null while PFUser.currentUser.email has the actual value of email used to log in. How can I achieve this validation without the password being accessible?
Here is the code I have for guidance:
PFQuery *query = [PFQuery queryWithClassName:#"User"];
[query whereKey:#"objectId" equalTo: PFUser.currentUser.objectId];
[query whereKey:#"password" equalTo: PFUser.currentUser.password];
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!object) {
/*Credentials changed! Logout user and request login again*/
NSLog(#"Credentials Changed!");
[PFUser logOut];
[[[navigationController viewControllers] objectAtIndex:0] performSegueWithIdentifier:#"loginSegue" sender:self];
}
else {
/*Credentials are still valid..proceed!*/
NSLog(#"Credentials Correct!");
[[[navigationController viewControllers] objectAtIndex:0] performSegueWithIdentifier:#"skipLoginSegue" sender:self];
}
}];
When this failed I tried to NSLog the password and got null so I understood that this was the problem.
I would write a cloud code function using the master key: Parse.Cloud.useMasterKey();
When you include this in your function you will be able to access/check the user's password and send back a "verified" variable or something of that sort.
Here is my cloud code function to modify a user, but you can easily modify it to verify a user's info. There are also many answers on the parse forums on this as well as lots of info in the docs.
Parse.Cloud.define("editUser", function(request, response) {
//var GameScore = Parse.Object.extend("SchoolHappening");
// Create a new instance of that class.
//var gameScore = new GameScore();
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.get(request.params.myUser, {
success: function(myUser) {
// The object was retrieved successfully.
myUser.set("cabinetPosition", request.params.myPosition);
// Save the user.
myUser.save(null, {
success: function(myUser) {
// The user was saved successfully.
response.success("Successfully updated user.");
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
response.error("Could not save changes to user.");
}
});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
}
});
});
If you want to verify your current password, you can store your password locally, then use loginWithUsernameInBackground: to verify. Something like,
[PFUser logInWithUsernameInBackground:[PFUser currentUser].username
password:password
block:^(PFUser *user, NSError *error) {
}];

Resources