1
+ import { Auth , emulatorHost , Env } from "../src" ;
2
+
3
+ interface Bindings extends Env {
4
+ EMAIL_ADDRESS : string
5
+ PASSWORD : string
6
+ FIREBASE_AUTH_EMULATOR_HOST : string
7
+ PUBLIC_JWK_CACHE_KV : KVNamespace
8
+ PROJECT_ID : string
9
+ PUBLIC_JWK_CACHE_KEY : string
10
+ }
11
+
12
+ const signInPath = "/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=test1234"
13
+
14
+ export async function handleRequest ( req : Request , env : Bindings ) {
15
+ const url = new URL ( req . url )
16
+ const firebaseEmuHost = emulatorHost ( env )
17
+ if ( url . pathname === "/get-jwt" && ! ! firebaseEmuHost ) {
18
+ const firebaseEmulatorSignInUrl = "http://" + firebaseEmuHost + signInPath
19
+ const resp = await fetch ( firebaseEmulatorSignInUrl , {
20
+ method : "POST" ,
21
+ body : JSON . stringify ( {
22
+ email : env . EMAIL_ADDRESS ,
23
+ password : env . PASSWORD ,
24
+ returnSecureToken : true ,
25
+ } ) ,
26
+ headers : {
27
+ "Content-Type" : "application/json"
28
+ }
29
+ } )
30
+ return resp
31
+ }
32
+
33
+ const authorization = req . headers . get ( 'Authorization' )
34
+ if ( authorization === null ) {
35
+ return new Response ( null , {
36
+ status : 400 ,
37
+ } )
38
+ }
39
+ const jwt = authorization . replace ( / B e a r e r \s + / i, "" )
40
+ const auth = Auth . getOrInitialize (
41
+ env . PROJECT_ID ,
42
+ env . PUBLIC_JWK_CACHE_KEY ,
43
+ env . PUBLIC_JWK_CACHE_KV
44
+ )
45
+ const firebaseToken = await auth . verifyIdToken ( jwt , env )
46
+
47
+ return new Response ( JSON . stringify ( firebaseToken ) , {
48
+ headers : {
49
+ "Content-Type" : "application/json"
50
+ }
51
+ } )
52
+ }
53
+
54
+ export default { fetch : handleRequest } ;
0 commit comments