prevent user from automatically signing in after registration with firebase [duplicate] - angularjs

This question already has answers here:
Firebase kicks out current user
(19 answers)
Closed 6 years ago.
i'm using firebase 3.0.5
I want members to have the ability to register other members through their account. Is there a way to prevent firebase from auto-signing new registrants in using createUserWithEmailAndPassword?
https://firebase.google.com/docs/auth/web/password-auth#create_a_password-based_account
I'm sure I can find another way to do this, but not auto-signing them in would make things much much simpler for me.
EDIT:
when a new member is signed up via an existing member, a random password is created and emailed to the new member. the existing member never knows the new members password.

Use createUser instead of createUserWithEmailAndPassword
As documented here:
https://www.firebase.com/docs/web/api/firebase/createuser.html
Creates a new email / password user with the provided credentials.
This method does not authenticate the user. After the account is
created, the user may be authenticated with authWithPassword().
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.createUser({
email: "bobtony#firebase.com",
password: "correcthorsebatterystaple"
}, function(error, userData) {
if (error) {
switch (error.code) {
case "EMAIL_TAKEN":
console.log("The new user account cannot be created because the email is already in use.");
break;
case "INVALID_EMAIL":
console.log("The specified email is not a valid email.");
break;
default:
console.log("Error creating user:", error);
}
} else {
console.log("Successfully created user account with uid:", userData.uid);
}
});

Related

MS Teams permissions for creating a group

Can someone help me understand how to add a permission to a MS-Graph API call?
I'm trying to create a new team/group but I'm getting a permission error. Obviously I need add the Team.Create permission if I want to create a Team. Which I did as seen in the image below
Here's the sample code where I tried to add the permission to the MSAL client request:
// Initialize Graph client
const client = graph.Client.init({
// Implement an auth provider that gets a token
// from the app's MSAL instance
authProvider: async (done) => {
try {
// Get the user's account
const account = await msalClient
.getTokenCache()
.getAccountByHomeId(userId);
let scope = process.env.OAUTH_SCOPES.split(',');
scope.push("Team.Create");
console.log("Added a extra permission request");
console.log("scope = " + scope);
if (account) {
// Attempt to get the token silently
// This method uses the token cache and
// refreshes expired tokens as needed
const response = await msalClient.acquireTokenSilent({
scopes: scope,
redirectUri: process.env.OAUTH_REDIRECT_URI,
account: account
});
console.log("\nResponse scope = " + JSON.stringify(response) + "\n");
// First param to callback is the error,
// Set to null in success case
done(null, response.accessToken);
}
} catch (err) {
console.log(JSON.stringify(err, Object.getOwnPropertyNames(err)));
done(err, null);
}
}
});
return client;
Then I get the following error:
The user or administrator has not consented to use the application with ID 'xxxxxxx'
named 'Node.js Graph Tutorial'. Send an interactive authorization request for this user and resource
I did give permissions to Team.Create in the Azure Active Directory, so how do I consent to this app gaining access? Note this code is the tutorial for learning Graph: https://learn.microsoft.com/en-us/graph/tutorials/node
Judging by the screenshot, you can't give admin consent to the permission as it is grayed out.
You'll need to try if you can grant user consent.
acquireTokenSilent won't work in this case since consent is needed.
You need to use one of the interactive authentication methods to trigger user authentication, at which time you can consent to the permission on your user's behalf.
In that sample specifically, you probably need to modify the scopes here: https://github.com/microsoftgraph/msgraph-training-nodeexpressapp/blob/08cc363e577b41dde4f6a72ad465439af20f4c3a/demo/graph-tutorial/routes/auth.js#L11.
And then trigger the /signin route in your browser.

Firebase authentication with localId / idToken (instead of email / password)

In my app, when a user logs in, I use firebase.auth to authenticate the user based on the email/password the user typed:
firebase.auth().signInWithEmailAndPassword(userInputs.email.value, userInputs.password.value)
Then I dispatch it to the redux state and also set the received localId and idToken on the local storage:
localStorage.setItem('token', response.user.qa);
localStorage.setItem('localId', response.user.uid);
When the user closes the app window and then reopen the app later, the localId and idToken are still set in the localstorage, but to re-authenticate I need to supply email and password. Is it possible to authenticate with localId/idToken, or should I save the email/password on localStorage instead of saving the two tokens?
Upon checking if the user is authenticated:
var user = firebase.auth().currentUser;
console.log(user);
I get 'null'.
It seems that I must sign in even if I already have the localId, without signing in I don't have access to the database.
Also, obviously my database rules grant access to the db only to authenticated users:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Thanks in advance!
You don't have to store the email & password in the localstorage.
Firebase library automatically retain the auth infomation locally.
The cause of you get null is you are trying to get user info with Synchronous code.
Which means that you are trying to get user before the firebase library's initalization.
firebase.auth().currentUser; // <= synchronous
Following code runs Asynchronously and you can get user after the firebase library initalize.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});

Firebase function linkAndRetrieveDataWithCredential doesn't work

To link an anonymous user to a newly-created user via email&pass I use the following function linkAndRetrieveDataWithCredential
For some reason I get the following error:
__WEBPACK_IMPORTED_MODULE_12_firebase_app___default.a.auth(...).currentUser.linkAndRetrieveDataWithCredential is not a function
The function is documented in the official Firebase documentation on how to link an anonymous user.
https://firebase.google.com/docs/auth/web/anonymous-auth
background: I use React.js and hence install Firebase via NPM.
What am I doing wrong ?
My code:
//if the user is anonymous, then upgrade the anonymous user to be the email&pass user.
//get the Credential object
var credential = firebase.auth.EmailAuthProvider.credential(this.state.email, this.state.password);
//get the Credential object
firebase.auth().currentUser.linkAndRetrieveDataWithCredential(credential).then(function(usercred) {
var user = usercred.user;
console.log("Anonymous account successfully upgraded", user);
//the user was created. redirect to Home page
window.location.assign("/");
Apparently the function was deprecated.
the right solution is documented here:
Firebase Convert Anonymous User Account to Permanent Account Error
// (Anonymous user is signed in at that point.)
// 1. Create the email and password credential, to upgrade the
// anonymous user.
var credential = firebase.auth.EmailAuthProvider.credential(email, password);
// 2. Links the credential to the currently signed in user
// (the anonymous user).
firebase.auth().currentUser.linkWithCredential(credential).then(function(user) {
console.log("Anonymous account successfully upgraded", user);
}, function(error) {
console.log("Error upgrading anonymous account", error);
});

How to register and store user info in Firebase Real Time Database

I just want to know that how can i register user in Firebase and store user's additional details like First name, Last name etc i made a typical registration form in Angular I am successfully registering users with their user name and password but i want to store user's detail on success for future use. I've done this in angular 1 but could not find anyway to work with it Angular2
The best way is to create a user object in your Firebase Realtime Database using the Firebase Authentication uid from the newly created user:
this.af.auth.createUser({
// Create Firebase Auth user
email: formData.value.email,
password: formData.value.password
}).then((user) => {
// User created now create Firebase Database user
return this.af.database.object(`/users/${user.uid}`).update({
firstName: formData.value.firstName,
lastName: formData.value.lastName
});
}).then(() => {
// Success
}).catch((error) => {
// Error
console.log(error);
});
(Not had chance to test this)
Depending on how you've done registration you can obviously replace the formData.value with your model data if needed.
Also, this is done using the AngularFire2 library - https://github.com/angular/angularfire2

Adding Custom Attributes to Firebase Auth

I have hunted through Firebase's docs and can't seem to find a way to add custom attributes to FIRAuth. I am migrating an app from Parse-Server and I know that I could set a user's username, email, and objectId. No I see that I have the option for email, displayName, and photoURL. I want to be able to add custom attributes like the user's name. For example, I can use:
let user = FIRAuth.auth()?.currentUser
if let user = user {
let changeRequest = user.profileChangeRequest()
changeRequest.displayName = "Jane Q. User"
changeRequest.photoURL =
NSURL(string: "https://example.com/jane-q-user/profile.jpg")
changeRequest.setValue("Test1Name", forKey: "usersName")
changeRequest.commitChangesWithCompletion { error in
if error != nil {
print("\(error!.code): \(error!.localizedDescription)")
} else {
print("User's Display Name: \(user.displayName!)")
print("User's Name: \(user.valueForKey("name"))")
}
}
}
When I run the code, I get an error that "usersName" is not key value compliant. Is this not the right code to use. I can't seem to find another way.
You can't add custom attributes to Firebase Auth. Default attributes have been made available to facilitate access to user information, especially when using a provider (such as Facebook).
If you need to store more information about a user, use the Firebase realtime database. I recommend having a "Users" parent, that will hold all the User children. Also, have a userId key or an email key in order to identify the users and associate them with their respective accounts.
Hope this helps.
While in most cases you cannot add custom information to a user, there are cases where you can.
If you are creating or modifying users using the Admin SDK, you may create custom claims. These custom claims can be used within your client by accessing attributes of the claims object.
Swift code from the Firebase documentation:
user.getIDTokenResult(completion: { (result, error) in
guard let admin = result?.claims?["admin"] as? NSNumber else {
// Show regular user UI.
showRegularUI()
return
}
if admin.boolValue {
// Show admin UI.
showAdminUI()
} else {
// Show regular user UI.
showRegularUI()
}
})
Node.js code for adding the claim:
// Set admin privilege on the user corresponding to uid.
admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
});

Resources