Skip to content

Instantly share code, notes, and snippets.

@abhishek0196
Last active October 18, 2022 01:56
Show Gist options
  • Save abhishek0196/cd8f1f2b3d1bc438d141bb2899c44274 to your computer and use it in GitHub Desktop.
Save abhishek0196/cd8f1f2b3d1bc438d141bb2899c44274 to your computer and use it in GitHub Desktop.
Firebase Custom claims using Firbase Function and Android

This tutorial is for those , who are looking to use firebase custom claims, using Android as a platform. Before using the claims , one must keep in mind that these claims should only be used for passing the very necessary details and should not be used for storing useless info like address.

Steps included are:

  1. First of all install firebase CLI in your system , and use the command firebase init functions . For installation you can use the following link

  2. Select typescript for firbase functions(in the functions folder ovveride the content of package.json file with the one given in this file)

3.Copy pase the index.ts file from this gist and deploy the function.

4.Now comes the android part now add a fucntion called addRole for that use the addClaim.java file from this gist,and then invoke the addRole() method (use the file callMethod.java for this)

5.Finally check the role , when the user login. (use the file getClaim.java),in this file in line 15 you get the role value, and you can use it accordingly.

//this methid calls the firebase function by its name , and passes the parameter using Map, the parameters are email and role.
private Task<String> addRole() {
// Create the arguments to the callable function.
Map<String, Object> data = new HashMap<>();
data.put("email", email);
data.put("push", true);
data.put("role",role);
return mFunctions
.getHttpsCallable("addRole")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>() {
@Override
public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
// This continuation runs on either success or failure, but if the task
// has failed then getResult() will throw an Exception which will be
// propagated down.
//Toast.makeText(SIgnUp.this, ""+task.getResult().getData().toString(), Toast.LENGTH_SHORT).show();
String result ;//(String) task.getResult().getData();
HashMap<String,String> res =(HashMap<String, String>) task.getResult().getData();
result = res.get("message");
// Toast.makeText(SIgnUp.this, ""+result, Toast.LENGTH_SHORT).show();
return result;
}
});
}
addRole()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Toast.makeText(SIgnUp.this, ""+task.getResult(), Toast.LENGTH_SHORT).show();
Exception e = task.getException();
if (e instanceof FirebaseFunctionsException) {
FirebaseFunctionsException ffe = (FirebaseFunctionsException) e;
FirebaseFunctionsException.Code code = ffe.getCode();
Object details = ffe.getDetails();
}
// ...
}
else {
Toast.makeText(SIgnUp.this, ""+task.getResult(), Toast.LENGTH_SHORT).show();
}
// ...
}
});
FirebaseAuth mAuth;
mAuth.signInWithEmailAndPassword(emailText,passwordText)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(MainActivity.this, "Successful", Toast.LENGTH_SHORT).show();
//Log.d("", "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
user.getIdToken(true)
.addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
@Override
public void onSuccess(GetTokenResult result) {
Object value = result.getClaims().get("roles");
}
});
} else {
Toast.makeText(MainActivity.this, "signInWithEmail:failure" +task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
//import necessary modules
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
exports.addRole = functions.https.onCall((data)=>{
//get the user by the email passed through the argument
return admin.auth().getUserByEmail(data.email).then((user)=>{
return admin.auth().setCustomUserClaims(user.uid,{
//set the role accordingly
roles:data.role
});
}).then(()=>{
return {
//pass the success message accordingly
message: `Success! ${data.email}`
}
}).catch((e)=>{
return {
//return error if any
error: e
};
})
});
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "^8.0.0",
"firebase-functions": "^3.1.0"
},
"devDependencies": {
"tslint": "^5.12.0",
"typescript": "^3.2.2"
},
"private": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment