Closed yashhema closed 3 years ago
Could you clarify what you mean about validation? Note that the Functions Framework itself doesn't have anything Firestore-specific... so any validation you need to perform wouldn't be specific to the Functions Framework.
In terms of the title of your issue, see https://github.com/GoogleCloudPlatform/dotnet-docs-samples/tree/master/functions/firebase for the examples we've got, including an example using the Firestore library with dependency injection.
Hello, I am unable to understand , how I can do something similar with c# http functions This is what I how I did things in python -- `
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from firebase_admin import auth
from firebase_admin import storage
from google.cloud.firestore_v1 import Increment
import sys,traceback
from datetime import datetime
from google.cloud.firestore_v1 import ArrayUnion
@firebase_auth_required
def MyHttpFunction(request, decoded_token = None):
{ My function body here}
def firebase_auth_required(f):
@wraps(f)
def wrapper(request):
print("in firebase auth")
print(request)
authorization = request.headers.get('Authorization')
id_token = None
if authorization and authorization.startswith('Bearer '):
id_token = authorization.split('Bearer ')[1]
else:
print ("cant find bearer, aborting")
json_abort(401, message="Invalid authorization")
try:
print (id_token)
decoded_token = auth.verify_id_token(id_token)
except Exception as e: # ValueError or auth.AuthError
print ("decode error")
json_abort(401, message="Invalid authorization")
return f(request, decoded_token)
return wrapper
app = firebase_admin.initialize_app(cred,{
'storageBucket': mstoragebucket
})
db = firestore.client()
bucket = storage.bucket()
`
An HTTP function in the .NET Functions Framework receives an HttpContext
, from which you can get the HttpRequest
- those are just standard ASP.NET Core types, so there's nothing Functions-specific about them.
In terms of the Firebase Admin interaction, I suggest you look at https://firebase.google.com/docs/reference/admin/dotnet - I don't have any experience with the Firebase Admin SDK myself, but I'd expect it to work within Google Cloud Functions just as easily as anywhere else. I don't see anything within the Admin SDK that's the exact equivalent of verify_id_token
... I'd suggest asking in one of the Firebase support channels for that.
Hello, I was able to make the below code working in local machine, but on deploying on gcp getting error
For Cloud Build Stackdriver Logs, visit: https://console.cloud.google.com/logs/viewer?project=brindavan-c61b7&advancedFilter=resource.type%3Dbuild%0Aresource.labels.build_id%3D88406010-4e60-4ee6-9242-466711ff926c%0AlogName%3Dprojects%2Fbrindavan-c61b7%2Flogs%2Fcloudbuild Deploying function (may take a while - up to 2 minutes)...failed. ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
using FirebaseAdmin;
using FirebaseAdmin.Auth;
using Google.Cloud.Firestore;
using Google.Cloud.Functions.Framework;
using Google.Cloud.Functions.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Google.Cloud.Functions.Examples.Middleware
{
/// <summary>
/// The startup class can be used to perform additional configuration, including
/// adding application configuration sources, reconfiguring logging, providing services
/// for dependency injection, and adding middleware to the eventual application pipeline.
/// In this case, we add a simple piece of middleware to the request pipeline.
/// </summary>
public class Startup : FunctionsStartup
{
public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
{
//string credential_path = "D:/firebaseDatabase/Key/brindavan_in_brindavan-c61b7-firebase-adminsdk-k3966-039804b43a.json";
//System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);
// Bind the connection options based on the current configuration.
Console.WriteLine("Configured firebaseapp");
FirebaseApp myfirebaseapp = FirebaseApp.Create();
Console.WriteLine("Configured firebaseapp {0}", myfirebaseapp.Options.ProjectId == null ? "Not set " : myfirebaseapp.Options.ProjectId);
services.AddSingleton(myfirebaseapp);
//services.AddMvc();
}
public override void Configure(WebHostBuilderContext context, IApplicationBuilder app) =>
app.UseMiddleware<SampleMiddleware>();
}
/// <summary>
/// This middleware just provides a single log entry per successful request.
/// (This is not terribly useful as middleware, but it demonstrates the concept simply.)
/// </summary>
public class SampleMiddleware
{
private readonly RequestDelegate _next;
public SampleMiddleware(RequestDelegate next) =>
_next = next;
private static void ReadCustomHeader(out string customHeader, string headerval, HttpContext context)
{
customHeader = string.Empty;
if (context.Request.Headers.TryGetValue(headerval, out var traceValue))
{
customHeader = traceValue;
}
}
public async Task InvokeAsync(HttpContext context, ILogger<SampleMiddleware> logger)
{
string sauthorization = string.Empty;
ReadCustomHeader(out sauthorization, "Authorization", context);
if (sauthorization.Length > 0)
{
try
{
FirebaseToken firebaseToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(sauthorization);
/* assigning firebase auth user id to SignalR user */
string uid= firebaseToken.Uid;
}
catch(Exception ex)
{
context.Response.StatusCode = 400; //Bad Request
await context.Response.WriteAsync("Authorization header is missing");
return;
}
Stopwatch sw = Stopwatch.StartNew();
try
{
await _next(context);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
sw.Stop();
logger.LogInformation("Path: {path}; Status: {status}; Time: {time}ms",
context.Request.Path, context.Response.StatusCode, sw.Elapsed.TotalMilliseconds);
return;
}
else
{
context.Response.StatusCode = 400; //Bad Request
await context.Response.WriteAsync("Authorization header is missing");
return;
}
}
}
/// <summary>
/// The actual Cloud Function.
/// </summary>
[FunctionsStartup(typeof(Startup))]
public class Function : IHttpFunction
{
private readonly FirebaseApp _firebaseapp;
//public Function(FirebaseApp database) =>
// _firebaseapp = database;
private readonly ILogger _logger;
public Function(ILogger<Function> logger, FirebaseApp database)
{
_logger = logger;
_firebaseapp = database;
}
public async Task HandleAsync(HttpContext context)
{
try
{
Console.WriteLine("myabc");
FirestoreDb db = FirestoreDb.Create("brindavan-c61b7");
//FirestoreDb db = FirestoreDb.Create();
await context.Response.WriteAsync("Hello, Functions Framework.");
CollectionReference usersRef = db.Collection("USERS");
QuerySnapshot snapshot = await usersRef.GetSnapshotAsync();
foreach (DocumentSnapshot document in snapshot.Documents)
{
Console.WriteLine("User: {0}", document.Id);
Dictionary<string, object> documentDictionary = document.ToDictionary();
Console.WriteLine("First: {0}", documentDictionary["name"]);
Console.WriteLine();
}
await context.Response.WriteAsync("Hello, Functions Framework.");
}
catch(Exception ex)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsync(ex.Message);
}
}
}
}
Please examine the logs in the Functions Console - that should show why it hasn't started properly.
This is what is shown in logs , I am unable to understand , what am i doing wrong, but i will keep on debugging
Right - your function is in a namespace of Google.Cloud.Functions.Examples.Middleware
(oddly - I would suggest changing it; I'd also suggest not using custom middleware until you've got things working to start with).
The entry point you specify has to be the full name of the function type - you've specified digitaloceaninteraction.Function
, which isn't the full name of the function type.
Thanks for your constant help. I am able to fix my errors. Now I can actually test with the Android client. Do you think, I can paste finalfunction here, it might help someone's few hours
Well I won't stop you, but I'm not sure that it's likely to help anyone unless they're trying to do exactly the same as you. I'll close this now as it sounds like it's working, but that doesn't stop you from adding more comments.
Hello, I have been using cloud functions using python. I am trying to do something similar with c#
I want to deploy a cloud function using c# which needs to read and write data from cloud firestore. I also need to validate the request (based on token recvd on header from android client) . Can you please share an example for that.