I have a function that checks wether the password and user match before authenticating using a custom token.
function getUser(user, password) {
var usersRef = new Firebase("mydatabase/users");
var userRef = usersRef.child(user);
userRef.once("value",
function getHandler(snapshot) {
if (snapshot.val().password == password) {
var token = createToken(user);
ref.authWithCustomToken(token, authHandler);
} else {
alert("Gebruikersnaam en code komen niet overeen");
}
},
function errorHandler(errorObject) {
alert("Ophalen van gebruikersgegevens is mislukt: " + errorObject.code);
}
);
}
To create e token I instantiate the firebase class FirebaseTokenGenerator with the secret key. Like
function createToken(user) {
var tokenGenerator = new FirebaseTokenGenerator("<secret key...>");
var updatedObj = {
"uid": "custom:"+user,
"level": "docent"
}
return tokenGenerator.createToken(updatedObj);
However in that way the secret key would be visible for anyone looking into the .js source code. I'm pretty sure that is not how it should be done but what is the right way to do this then, the Firebase-way?
EDIT:
I tried to figure out the javascript way for this but got stuck there so switched back to php. Used the firebase-token-generator code from github (here), installed it including dependencies in my project with composer and that all seems to work fine (token is generated).
<?php
include_once "FirebaseToken.php";
$uid = $_POST['uid'];
$level = $_POST['level'];
$tokenGen = new Services_FirebaseTokenGenerator("<secret key>");
$token = $tokenGen->createToken(array("uid" => "custom:BAAJ"), array("admin" => False));
echo $token;
?>
Reading this SO post I found that following would be the way to embed it in my javascript code:
function createToken(user) {
$.post('php/createtoken.php', {uid: user, level: 'docent'}, function(data){
//successful ajax request
return data;
}).error(function(error){
alert("Create token mislukt: "+error);
});
};
But for som reason the token is not generated then. When called from getUser at first both the success and error part of the javascript createToken function are not executed at all (resulting in an undefined value for variable token. Then createToken is called a second time (??) and then the success part is executed however the data now does not contain the token but the complete php script...?
What is the problem and how to solve?