您可以使用Firebase Custom Claims 分配“教师”声明,以便区分教师和学生。之后你可以Firebase Cloud Functions创建一个新的学生账户。
在云端函数中,可以验证调用该函数的用户是否为教师。
// Creates a new student account
exports.addStudent = functions.https.onCall((data, context) => {
//Getting data passed from frontend
const {name, email, password, ...rest} = data;
//Checking if the caller of function is a teacher
if (!context.auth.token.teacher) return "You are not a teacher!";
//Creating a new user account
return admin
.auth()
.createUser({
email,
password: 'secretPassword',
displayName: name,
})
.then((userRecord) => {
// See the UserRecord reference doc for the contents of userRecord.
console.log('Successfully created new user:', userRecord.uid);
return userRecord.uid;
})
.catch((error) => {
console.log('Error creating new user:', error);
return "An error occured"
});
});
现在由您决定如何创建教师帐户。您可以直接在 Firebase 控制台中创建它并编写一次性函数来将教师声明添加到它们。
export.addTeacherClaim = functions.https.onCall((data, context) => {
const {uid} = data;
return admin
.auth()
.setCustomUserClaims(uid, { teacher: true })
.then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
return true;
});
})
你可以像这样从你的 React 应用调用函数:
const addStudent = firebase.functions().httpsCallable('addStudent');
addMessage({ email: "name@domain.tld", name: "StudentName", password: "Password" })
.then((result) => {
// Read result of the Cloud Function.
const newUserUid = result.data;
});