我正在开发一个 firebase+angularjs 应用程序,我正在使用简单的电子邮件和密码身份验证,它工作正常。
我只是想知道我是否可以在 firebase 电子邮件+密码身份验证正在使用的用户表上添加额外的用户数据,就像我想添加有关用户的帐单信息和其他详细信息而不在 firebase 上创建额外的节点/表来存储这些额外的数据。
我正在开发一个 firebase+angularjs 应用程序,我正在使用简单的电子邮件和密码身份验证,它工作正常。
我只是想知道我是否可以在 firebase 电子邮件+密码身份验证正在使用的用户表上添加额外的用户数据,就像我想添加有关用户的帐单信息和其他详细信息而不在 firebase 上创建额外的节点/表来存储这些额外的数据。
Firebase 将电子邮件/密码用户存储在您无法直接访问的单独位置。您无法展开此位置的数据。
由于许多应用程序开发人员希望在其应用程序代码中访问用户数据,因此将所有用户存储/users
在应用程序数据库本身的一个节点下是一种常见的做法。缺点是你必须自己做。但这样做的积极方面是,您可以根据需要存储任何额外信息。
有关示例代码,请参阅有关存储用户数据的 Firebase 指南。从那里:
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
if (authData && isNewUser) {
// save the user's profile into Firebase so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: getName(authData)
});
}
});
Firebase 用户具有一组固定的基本属性——唯一 ID、主电子邮件地址、姓名和照片 URL——存储在项目的用户数据库中,可由用户(iOS、Android、Web)进行更新。您不能直接向 Firebase User 对象添加其他属性;相反,您可以将其他属性存储在 Firebase 实时数据库中。
注意:此方法仅在您使用 Firebase Admin SDK 并且您需要在服务器上有端点来管理自定义令牌时才有效
Firebase Admin SDK 可以选择使用其他声明对象创建自定义令牌,该声明对象可以包含任意数据。这对于存储一些与用户相关的信息可能很有用,例如用户是否是高级用户。
可以使用auth
对象访问其他索赔数据。
例子
var uid = "some-uid"; //this can be existing user UID
var additionalClaims = {
premiumAccount: true,
some-user-property: 'some-value'
};
admin.auth().createCustomToken(uid, additionalClaims)
.then(function(customToken) {
// Send token back to client
})
.catch(function(error) {
console.log("Error creating custom token:", error);
});
additionalClaims
也可以在 Firebase 安全规则中访问。
有关更多信息,请阅读Firebase 自定义令牌
Firebase 有一组固定的用户属性,可以更新但不能添加。
但是,您可以使用序列化和反序列化添加少量数据JSON.stringify() and JSON.parse()
然后使用任何一个未使用的属性来存储字符串
在 DisplayName 或 photoURL 属性中。请记住,可以添加的数据必须很小并存储为字符串。
这只能通过使用 FIREBASE SDK 中的方法而不是 angularfire 来实现,如下图所示
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: "Jane Q. User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
// Update successful.
}, function(error) {
// An error happened.
});
您可以在此处以字符串的形式在 photoURL 或 displayName 变量中存储更多 json 数据。
我的答案与角度无关,但我安静地搜索了一下以了解如何使用Polymer和Polymerfire来完成它,所以我添加了这个答案以帮助人们比我更快地完成它。
正如 Frank van Puffelen 提到的,我必须向 db 添加一个单独的节点。
进口:
<link rel="import" href="../bower_components/polymerfire/firebase-app.html">
<link rel="import" href="../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../bower_components/polymerfire/firebase-document.html">
然后在你的应用程序的任何地方放置一个<firebase-app>
组件:
<firebase-app
name="yourAppName"
api-key= "{{yourApi}}"
auth-domain= "{{yourAuthDomain}}"
database-url= "{{yourDbUrl}}"
>
</firebase-app>
之后,您将需要使用<firebase-auth>
and < firebase-document>
:
模板 :
<firebase-auth
id="auth"
app-name="yourAppName"
signed-in="{{signedIn}}"
user="{{user}}">
</firebase-auth>
<firebase-document
id="document"
app-name="yourAppName"
path="{{usersPath}}" // e.g "/users"
data="{{userDocument}}">
</firebase-document>
脚本:
this._register = function(){
var formValid = this.querySelector('#register-form').validate();
var auth = this.querySelector('#auth');
if(formValid && this.passWordsIdentic){
//The actual registration
auth.createUserWithEmailAndPassword(this.email, this.password).then(function(user){
console.log('auth user registration succes');
//Example values
this.userDocument.uid = user.uid;
this.userDocument.email = user.email;
this.userDocument.firstName = this.firstName;
this.userDocument.lastName = this.lastName;
this.userDocument.userName = this.userName;
this.$.document.save(this.usersPath).then(() => {
console.log("custom user registration succes");
this.$.document.reset();
});
}.bind(this)).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log('error: ', errorCode);
);
}
}
就是这样,你可能想看看这个优秀的谷歌代码实验室,它很好地介绍了如何使用 firebase 和聚合物。
请注意,方法在 v4.0.0 中有所更改。因此,您需要使用以下代码来检索用户配置文件:
afAuth.authState.subscribe((user: firebase.User) => {
this.displayName = user.displayName;
this.email = user.email;
this.photoURL = user.photoURL;
});
这是一个快速版本。您的用户结构(“表”)就像
--users:
-------abc,d@email,com:
---------------email:abc.d@email.com
---------------name: userName
etc.
通过身份验证后,FIRAuth.auth()?.createUser
您可以在数据库中设置用户,如下所示:
let ref = FIRDatabase.database().reference()
let rootChild = ref.child("users")
let changedEmailChild = u.email?.lowercased().replacingOccurrences(of: ".", with: ",", options: .literal, range: nil) // Email doesn't support "," firebase doesn't support "."
let userChild = rootChild.child(changedEmailChild!)
userChild.child("email").setValue(u.email)
userChild.child("name").setValue(signup.name)
Frank 的回答很好,但 Angular6/Firebase5/Angularfire5 中的情况有些不同:
这是我用于登录用户的点击处理程序:
this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()).then((e) => {
console.log("Log-In Success" + e.additionalUserInfo.profile.name);
if (e.additionalUserInfo.isNewUser)
this.addUserToDatabase(/*...*/);
}).catch((error) => {
console.log("Log-In Error: Google Sign-In failed");
});
这是在用户表中添加额外字段的注册代码
import { AngularFireAuth } from "@angular/fire/auth";
constructor(private firebaseAuth: AngularFireAuth){}
registration(data: any, password: any) {
return this.firebaseAuth.auth.createUserWithEmailAndPassword(data.Email, password)
.then(res => {
res.user.updateProfile({
displayName: `${data.DisplayName}`
})
data.UserId = res.user.uid;
data.PhoneNumbers = [{
NumberType: '',
NumberValue: ''
}];
data.PhotoUrl = '';
data.Addresses = [{
AddressLine1: '',
AddressLine2: '',
City: '',
State: '',
Country: '',
PostalCode: '',
AddressType: ''
}];
data.IsDeleted = false;
this.fireStore.doc(`users/${res.user.uid}`).set(data);
this.toastr.success('User has been register successfully!', 'Successfull!');
return true;
}).catch(err => {
switch (err.code) {
case 'auth/email-already-in-use':
this.toastr.error(`Email address ${data.Email} already in use.`, 'Error!');
break;
case 'auth/invalid-email':
this.toastr.error(`Email address ${data.Email} is invalid.`, 'Error!');
break;
case 'auth/operation-not-allowed':
this.toastr.error('Error during sign up.', 'Error!');
break;
case 'auth/weak-password':
this.toastr.error('Password is not strong enough. Add additional characters including special characters and numbers.', 'Error!');
break;
default:
this.toastr.error(err.message, 'Error!');
break;
}
});
}