Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Auth on Kotlin/JS #567

Unanswered
eugenewainaina asked this question in Q&A
Jul 16, 2024 · 2 comments · 3 replies
Discussion options

How do I do auth on Kotlin/JS?

This is what I have but I'm getting errors
Btw I'm using a framework called Kobweb

try {
 val auth = Firebase.auth
 val userCredential = auth.createUserWithEmailAndPassword(
 email = "------@gmail.com",
 password = "Password_123"
 )
 val user = userCredential.user
 if (user != null) {
 ctx.res.setBodyText("Signed in with Email & Password. User: ${user.uid}")
 } else {
 ctx.res.setBodyText("Failed to sign in with Email & Password. User is null.")
 }
} catch (e: Exception) {
 ctx.res.setBodyText("Failed to sign in with Email & Password. Error: ${e.message}")
 // Log the full exception stack trace for debugging
 println("Error signing in with Email & Password: $e")
}
You must be logged in to vote

Replies: 2 comments 3 replies

Comment options

What errors are you getting?

You must be logged in to vote
1 reply
Comment options

So here's the Firebase Initialization

@InitApi
fun initializeFirebase(ctx: InitApiContext) {
val context = Application().applicationContext
FirebasePlatform.initializeFirebasePlatform(object : FirebasePlatform() {
 val storage = mutableMapOf<String, String>()
 override fun store(key: String, value: String) = storage.set(key, value)
 override fun retrieve(key: String) = storage[key]
 override fun clear(key: String) {
 storage.remove(key)
 }
 override fun log(msg: String) = println(msg)
})
val firebaseConfig = FirebaseOptions(
 apiKey = "AIzaSyB_x6qG-gIkUSQSYw4Op5D7lSgjP2xa9G8",
 authDomain = "ticketsystem-66e93.firebaseapp.com",
 projectId = "ticketsystem-66e93",
 storageBucket = "ticketsystem-66e93.appspot.com",
 gcmSenderId = "180179590377",
 applicationId = "1:180179590377:web:ebf237ea60ab9b72132478"
)
val firebaseApp = Firebase.initialize(context = context, options = firebaseConfig)
ctx.data.add(firebaseApp)

}

Here's a test to see if it has connected by querying Firebase Auth

@Api("testFirebaseConnection")
suspend fun testFirebaseConnection(ctx: ApiContext) {
/*try {
 val result = ctx.data.get<FirebaseApp>()
 ctx.res.setBodyText(result.toString())
} catch (e: Exception) {
 ctx.res.setBodyText("error")
}*/
val auth: FirebaseAuth? = try {
 Firebase.auth
} catch (e: Exception) {
 null
}
if (auth != null) {
 ctx.res.setBodyText("Connected to Firebase successfully. $auth")
} else {
 ctx.res.setBodyText("Failed to connect to Firebase.")
}

}

And here's me trying to create a user with Email & Passowrd

@Api("emailPassword")
suspend fun signIn(ctx: ApiContext) {
try {
 val auth = Firebase.auth
 val userCredential = auth.createUserWithEmailAndPassword(
 email = "------@gmail.com",
 password = "Password_123"
 )
 val user = userCredential.user
 if (user != null) {
 ctx.res.setBodyText("Signed in with Email & Password. User: ${user.uid}")
 } else {
 ctx.res.setBodyText("Failed to sign in with Email & Password. User is null.")
 }
} catch (e: Exception) {
 ctx.res.setBodyText("Failed to sign in with Email & Password. Error: ${e.message}")
 // Log the full exception stack trace for debugging
 println("Error signing in with Email & Password: $e")
}

}

The app connects to Firebase but there's a 500 error when I call the createUserWithEmailAndPassword API.

CoroutineExceptionHandlerImpl.kt:7
ResponseException: URL = http://localhost:8080/api/emailPassword, Status = 500, Status Text = Internal Server Error

kotlin.NotImplementedError: An operation is not implemented.
at com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(FirebaseAuth.kt:429)
at dev.gitlive.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(auth.kt:58)
at org.example.ticketv2.api.Firebase_FunctionsKt.signIn(Firebase Functions.kt:93)

propagateExceptionFinalResort @ CoroutineExceptionHandlerImpl.kt:7
handleUncaughtCoroutineException @ CoroutineExceptionHa...erImpl.common.kt:48
handleCoroutineException @ CoroutineExceptionHandler.kt:28
protoOf.handleJobException_9fdet1_k$ @ Builders.common.kt:190
finalizeFinishingState @ JobSupport.kt:228
tryMakeCompletingSlowPath @ JobSupport.kt:907
tryMakeCompleting @ JobSupport.kt:864
protoOf.makeCompletingOnce_b13xy2_k$ @ JobSupport.kt:829
protoOf.resumeWith_dtxwbr_k$ @ AbstractCoroutine.kt:97
protoOf.resumeWith_b9cu3x_k$ @ Continuation.kt:54
protoOf.resumeWith_dtxwbr_k$ @ kotlin-kotlin-stdlib.js:5916
protoOf.run_mvkpxh_k$ @ Continuation.kt:54
eval @ JsMicrotasksDispatcher.kt:11
Promise.then
protoOf.dispatch_qa3n0o_k$ @ JsMicrotasksDispatcher.kt:11
dispatch @ DispatchedTask.kt:157
dispatchResume @ CancellableContinuationImpl.kt:470
resumeImpl @ CancellableContinuationImpl.kt:504
resumeImpl$default @ kotlinx-coroutines-core.js:1113
protoOf.resumeWith_dtxwbr_k$ @ CancellableContinuationImpl.kt:364
protoOf.invoke_py2q9a_k$ @ Continuation.kt:54
protoOf.invoke @ kotlinx-coroutines-core.js:4236
notifyCompletion @ JobSupport.kt:367
completeStateFinalization @ JobSupport.kt:322
finalizeFinishingState @ JobSupport.kt:239
tryMakeCompletingSlowPath @ JobSupport.kt:907
tryMakeCompleting @ JobSupport.kt:864
protoOf.makeCompleting_2ycklh_k$ @ JobSupport.kt:807
protoOf.completeExceptionally_xyzekf_k$ @ CompletableDeferred.kt:89
eval @ Fetch.kt:121
protoOf.doResume_5yljmg_k$ @ Fetch.kt:46
protoOf.resumeWith_b9cu3x_k$ @ Standard.kt:55
protoOf.resumeWith_dtxwbr_k$ @ kotlin-kotlin-stdlib.js:5916
protoOf.run_mvkpxh_k$ @ Continuation.kt:45
protoOf.process_myqcf5_k$ @ JSDispatcher.kt:127
eval @ JSDispatcher.kt:55
Promise.then
protoOf.schedule_o777if_k$ @ JSDispatcher.kt:55
protoOf.enqueue_uiib2n_k$ @ JSDispatcher.kt:118
protoOf.dispatch_qa3n0o_k$ @ JSDispatcher.kt:56
protoOf.resumeWith_dtxwbr_k$ @ DispatchedContinuation.kt:196
protoOf.resumeWith_dtxwbr_k$ @ SafeContinuationJs.kt:34
eval @ Continuation.kt:45
Promise.then
protoOf.doResume_5yljmg_k$ @ Fetch.kt:35
getBodyBytes @ kobweb-frontend-browser-ext.js:921
protoOf.doResume_5yljmg_k$ @ Fetch.kt:46
protoOf.invoke_d9fzmj_k$ @ kobweb-frontend-browser-ext.js:962
l @ kobweb-frontend-browser-ext.js:1011
protoOf.doResume_5yljmg_k$ @ IntrinsicsJs.kt:163
protoOf.resumeWith_b9cu3x_k$ @ Standard.kt:55
protoOf.resumeWith_dtxwbr_k$ @ kotlin-kotlin-stdlib.js:5916
protoOf.run_mvkpxh_k$ @ Continuation.kt:45
protoOf.process_myqcf5_k$ @ JSDispatcher.kt:127
eval @ JSDispatcher.kt:55
Promise.then
protoOf.schedule_o777if_k$ @ JSDispatcher.kt:55
protoOf.enqueue_uiib2n_k$ @ JSDispatcher.kt:118
protoOf.dispatch_qa3n0o_k$ @ JSDispatcher.kt:56
resumeCancellableWith @ DispatchedContinuation.kt:217
startCoroutineCancellable @ Cancellable.kt:26
protoOf.invoke_neaz0o_k$ @ CoroutineStart.kt:88
protoOf.start_rn6v44_k$ @ AbstractCoroutine.kt:123
launch @ Builders.common.kt:52
getBodyBytesAsync @ Fetch.kt:45
eval @ Fetch.kt:120
Promise.then
fetch @ Fetch.kt:115
protoOf.get_89f2h8_k$ @ HttpFetcher.kt:92
protoOf.get_3u5zdv_k$ @ ApiFetcher.kt:81
protoOf.get$default_m5lv9o_k$ @ kobweb-frontend-kobweb-core.js:211
protoOf.doResume_5yljmg_k$ @ Index.kt:84
protoOf.resumeWith_b9cu3x_k$ @ Standard.kt:55
protoOf.resumeWith_dtxwbr_k$ @ kotlin-kotlin-stdlib.js:5916
protoOf.run_mvkpxh_k$ @ Continuation.kt:45
eval @ JsMicrotasksDispatcher.kt:11
Promise.then
protoOf.dispatch_qa3n0o_k$ @ JsMicrotasksDispatcher.kt:11
dispatch @ DispatchedTask.kt:157
dispatchResume @ CancellableContinuationImpl.kt:470
resumeImpl @ CancellableContinuationImpl.kt:504
resumeImpl$default @ kotlinx-coroutines-core.js:1113
protoOf.resumeUndispatched_tyhwz7_k$ @ CancellableContinuationImpl.kt:591
eval @ Standard.kt:71

Comment options

Have you tried on another platform or in pure js? Looks more like a config issue on your end if you are getting a 500 response from the server.

http://localhost:8080/api/emailPassword

You must be logged in to vote
2 replies
Comment options

I've used js
Here's my code

import kotlin.js.Promise
@JsModule("firebase/app")
@JsNonModule
external object FirebaseApp {
 val initializeApp: (config: dynamic) -> dynamic
}
@JsModule("firebase/auth")
@JsNonModule
external object FirebaseAuth {
 val getAuth: () -> dynamic
 val createUserWithEmailAndPassword: (auth: dynamic, email: String, password: String) -> Promise<dynamic>
}
fun createUser(email: String, password: String): Promise<dynamic> {
 val auth = FirebaseAuth.getAuth()
 return FirebaseAuth.createUserWithEmailAndPassword(auth, email, password)
}
fun initFirebase() {
 val firebaseConfig = js(
 """
 {
 apiKey: "-",
 authDomain: "-",
 projectId: "-",
 storageBucket: "--",
 messagingSenderId: "-",
 appId: "-"
 }
 """
 )
 FirebaseApp.initializeApp(firebaseConfig)
}

Then initialize Firebase then create user

 initFirebase()
 createUser("example@gmail.com", "Password_123")
 .then { userCredential: dynamic ->
 val user = userCredential.user
 console.log("User created successfully. User ID: ${user.uid}")
 }
 .catch { error ->
 val errorMessage = error.message
 console.error("Error creating user: $errorMessage")
 }
Comment options

Here, I use the same js way but realise using Java in the server is better.
You can find my detailed explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /