Files
Klottr/shared/src/androidMain/kotlin/app/klottr/auth/AuthPlatform.android.kt
2025-09-23 14:50:47 +02:00

91 lines
3.3 KiB
Kotlin

package app.klottr.auth
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResult
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import app.klottr.util.AuthShared
import app.klottr.util.PlatformAuthStorage
import app.klottr.BuildKonfig
import com.google.android.gms.common.api.ApiException
/**
* Android-only bridge that performs Google Sign-In and updates shared auth state.
* No UI or Compose code here; UI observes AuthShared in commonMain.
*/
object AuthPlatform {
/** Client that can fetch an ID token for server verification. */
fun signInIntent(ctx: Context): Intent {
return signInClient(ctx).signInIntent
}
fun handleSignInActivityResult(ctx: Context, res: ActivityResult) {
val task = GoogleSignIn.getSignedInAccountFromIntent(res.data)
try {
val account = task.getResult(ApiException::class.java)
applySignInResult(account)
Toast.makeText(ctx, "Inloggad som ${account.email ?: "okänd"}", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Toast.makeText(ctx, "Inloggning misslyckades: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
/** Clear (sign out) */
fun clear(ctx: Context) {
// Clears Google session and shared state
signInClient(ctx).signOut()
AuthShared.clearAll()
}
/**
* Try restoring / refreshing silently.
* - If Google knows the last account, try silentSignIn.
* - Otherwise fall back to whatever is persisted in PlatformAuthStorage.
*/
fun refreshSilently(ctx: Context, onDone: (Boolean) -> Unit) {
val last = GoogleSignIn.getLastSignedInAccount(ctx)
if (last != null) {
signInClient(ctx).silentSignIn()
.addOnSuccessListener { acc ->
applySignInResult(acc)
onDone(true)
}
.addOnFailureListener {
AuthShared.loadFromStorage()
onDone(AuthShared.idToken != null)
}
} else {
AuthShared.loadFromStorage()
onDone(AuthShared.idToken != null)
}
}
/** Save returned account -> shared state + shared persistence */
private fun applySignInResult(acct: GoogleSignInAccount) {
val token = acct.idToken
val sub = acct.id
val mail = acct.email
// Update shared in-memory state
AuthShared.applyLogin(token, sub, mail)
// Persist through PlatformAuthStorage (delegate provided in MainActivity)
if (token == null) {
Log.w("Klottr/Auth", "ID token is null after sign-in. Check WEB_CLIENT_ID/server config.")
}
}
private fun signInClient(ctx: Context): GoogleSignInClient
{
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(BuildKonfig.WEB_CLIENT_ID)
.build()
return GoogleSignIn.getClient(ctx, gso)
}
}