Refactored and cleaned up Auth integration
This commit is contained in:
@@ -100,9 +100,6 @@ dependencies {
|
|||||||
implementation("com.google.maps.android:maps-compose:4.4.1")
|
implementation("com.google.maps.android:maps-compose:4.4.1")
|
||||||
// implementation("com.google.android.gms:play-services-maps:18.2.0") // This is now included in :shared
|
// implementation("com.google.android.gms:play-services-maps:18.2.0") // This is now included in :shared
|
||||||
|
|
||||||
// Google Sign-In
|
|
||||||
implementation("com.google.android.gms:play-services-auth:21.2.0")
|
|
||||||
|
|
||||||
// Lifecycle
|
// Lifecycle
|
||||||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.6")
|
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.6")
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import android.widget.Toast
|
|||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.result.ActivityResult
|
||||||
import androidx.activity.result.ActivityResultLauncher
|
import androidx.activity.result.ActivityResultLauncher
|
||||||
import androidx.activity.result.PickVisualMediaRequest
|
import androidx.activity.result.PickVisualMediaRequest
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
@@ -136,7 +137,10 @@ import app.klottr.ui.SettingsContent // Delad material-fri UI för inställninga
|
|||||||
import app.klottr.ui.UsernameDialog
|
import app.klottr.ui.UsernameDialog
|
||||||
import app.klottr.ui.WikiArticleDialog // Ny: dialogskalet ligger nu i ui-paketet
|
import app.klottr.ui.WikiArticleDialog // Ny: dialogskalet ligger nu i ui-paketet
|
||||||
import app.klottr.ui.WriteDocContent // Använd delad, material-fri formulär-UI
|
import app.klottr.ui.WriteDocContent // Använd delad, material-fri formulär-UI
|
||||||
import app.klottr.util.Auth
|
import app.klottr.auth.AuthPlatform
|
||||||
|
import app.klottr.util.AuthShared
|
||||||
|
import app.klottr.util.PlatformAuthStorage
|
||||||
|
import app.klottr.util.AuthStorageDelegate
|
||||||
import app.klottr.util.Config
|
import app.klottr.util.Config
|
||||||
import app.klottr.util.FoundStore
|
import app.klottr.util.FoundStore
|
||||||
import app.klottr.util.FoundStore.LAYER_KLOTTER
|
import app.klottr.util.FoundStore.LAYER_KLOTTER
|
||||||
@@ -154,7 +158,6 @@ import app.klottr.work.OutboxWorker
|
|||||||
import coil3.ImageLoader
|
import coil3.ImageLoader
|
||||||
import coil3.compose.setSingletonImageLoaderFactory
|
import coil3.compose.setSingletonImageLoaderFactory
|
||||||
import coil3.toBitmap
|
import coil3.toBitmap
|
||||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
|
||||||
import com.google.android.gms.common.api.ApiException
|
import com.google.android.gms.common.api.ApiException
|
||||||
import com.google.android.gms.location.Priority
|
import com.google.android.gms.location.Priority
|
||||||
import com.google.android.gms.maps.CameraUpdateFactory
|
import com.google.android.gms.maps.CameraUpdateFactory
|
||||||
@@ -207,17 +210,25 @@ class MainActivity : ComponentActivity() {
|
|||||||
// no-op
|
// no-op
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Install platform storage delegate for shared Auth (Android uses SharedPreferences)
|
||||||
|
PlatformAuthStorage.install(object : AuthStorageDelegate {
|
||||||
|
private val sp by lazy { getSharedPreferences("klottr_auth", Context.MODE_PRIVATE) }
|
||||||
|
override fun get(key: String): String? = sp.getString(key, null)
|
||||||
|
override fun set(key: String, value: String?) {
|
||||||
|
sp.edit().apply {
|
||||||
|
if (value == null) remove(key) else putString(key, value)
|
||||||
|
apply()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun clear() { sp.edit().clear().apply() }
|
||||||
|
})
|
||||||
|
// Seed in-memory state from persisted storage (works on both platforms)
|
||||||
|
AuthShared.loadFromStorage()
|
||||||
|
|
||||||
// Google inloggning
|
// Google inloggning
|
||||||
signInLauncher =
|
signInLauncher =
|
||||||
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res ->
|
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res ->
|
||||||
val task = GoogleSignIn.getSignedInAccountFromIntent(res.data)
|
AuthPlatform.handleSignInActivityResult(this, res)
|
||||||
try {
|
|
||||||
val account = task.getResult(ApiException::class.java)
|
|
||||||
Auth.save(this, account)
|
|
||||||
Toast.makeText(this, "Inloggad som ${account.email ?: "okänd"}", Toast.LENGTH_SHORT).show()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Toast.makeText(this, "Inloggning misslyckades: ${e.message}", Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Starta LocationService direkt om vi redan har FG-platstillstånd
|
// Starta LocationService direkt om vi redan har FG-platstillstånd
|
||||||
@@ -254,10 +265,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
KlottrAppShell(
|
KlottrAppShell(
|
||||||
onRequestPerms = { this@MainActivity.requestAllRuntimePerms() },
|
onRequestPerms = { this@MainActivity.requestAllRuntimePerms() },
|
||||||
onLogin = {
|
onLogin = {
|
||||||
val client = Auth.signInClient(this)
|
val signInIntent = AuthPlatform.signInIntent(this)
|
||||||
signInLauncher.launch(client.signInIntent)
|
signInLauncher.launch(signInIntent)
|
||||||
},
|
},
|
||||||
onLogout = { Auth.clear(this) }
|
onLogout = { AuthPlatform.clear(this) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -296,8 +307,8 @@ private fun KlottrAppShell(
|
|||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
// Inloggning
|
// Inloggning
|
||||||
val loggedIn by Auth.loggedIn.collectAsState(initial = false)
|
val loggedIn by AuthShared.loggedIn.collectAsState(initial = false)
|
||||||
LaunchedEffect(Unit) { Auth.refreshSilently(context) { } }
|
LaunchedEffect(Unit) { AuthPlatform.refreshSilently(context) { } }
|
||||||
|
|
||||||
// DB/Repo
|
// DB/Repo
|
||||||
val db = remember { AppDatabase.Companion.getInstance(context) }
|
val db = remember { AppDatabase.Companion.getInstance(context) }
|
||||||
|
|||||||
@@ -1,117 +0,0 @@
|
|||||||
package app.klottr.util
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
|
||||||
import app.klottr.BuildConfig
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
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
|
|
||||||
|
|
||||||
object Auth {
|
|
||||||
|
|
||||||
private val WEB_CLIENT_ID: String
|
|
||||||
get() = BuildConfig.WEB_CLIENT_ID
|
|
||||||
private const val PREFS = "klottr_auth"
|
|
||||||
private const val KEY_IDTOKEN = "id_token"
|
|
||||||
private const val KEY_SUB = "sub"
|
|
||||||
private const val KEY_EMAIL = "email"
|
|
||||||
|
|
||||||
@Volatile var idToken: String? = null
|
|
||||||
private set
|
|
||||||
@Volatile var userId: String? = null // Google "sub"
|
|
||||||
private set
|
|
||||||
@Volatile var email: String? = null
|
|
||||||
private set
|
|
||||||
|
|
||||||
// Reaktivt UI-state (läs i UI med collectAsState())
|
|
||||||
private val _loggedIn = MutableStateFlow(false)
|
|
||||||
val loggedIn: StateFlow<Boolean> = _loggedIn
|
|
||||||
|
|
||||||
private val _email = MutableStateFlow<String?>(null)
|
|
||||||
val emailFlow: StateFlow<String?> = _email
|
|
||||||
|
|
||||||
/** Skapar klient som kan hämta ID-token (JWT) för serververifiering. */
|
|
||||||
fun signInClient(ctx: Context): GoogleSignInClient {
|
|
||||||
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
|
||||||
.requestEmail()
|
|
||||||
.requestIdToken(BuildConfig.WEB_CLIENT_ID)
|
|
||||||
.build()
|
|
||||||
return GoogleSignIn.getClient(ctx, gso)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Läs ev. sparad token/ID från SharedPreferences och uppdatera flöden. */
|
|
||||||
fun loadFromPrefs(ctx: Context) {
|
|
||||||
val sp = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
idToken = sp.getString(KEY_IDTOKEN, null)
|
|
||||||
userId = sp.getString(KEY_SUB, null)
|
|
||||||
email = sp.getString(KEY_EMAIL, null)
|
|
||||||
_loggedIn.value = idToken != null
|
|
||||||
_email.value = email
|
|
||||||
// Keep shared KMP state in sync (for iOS/Compose common UI)
|
|
||||||
AuthShared.applyLogin(idToken, userId, email)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Spara kontoinfo efter lyckad inloggning och uppdatera flöden. */
|
|
||||||
fun save(ctx: Context, acct: GoogleSignInAccount) {
|
|
||||||
val token = acct.idToken
|
|
||||||
val sub = acct.id
|
|
||||||
val mail = acct.email
|
|
||||||
idToken = token
|
|
||||||
userId = sub
|
|
||||||
email = mail
|
|
||||||
ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().apply {
|
|
||||||
putString(KEY_IDTOKEN, token)
|
|
||||||
putString(KEY_SUB, sub)
|
|
||||||
putString(KEY_EMAIL, mail)
|
|
||||||
apply()
|
|
||||||
}
|
|
||||||
_loggedIn.value = token != null
|
|
||||||
_email.value = mail
|
|
||||||
// Sync shared KMP state
|
|
||||||
AuthShared.applyLogin(token, sub, mail)
|
|
||||||
if (token == null) {
|
|
||||||
Log.w("Klottr/Auth", "ID‑token är null efter sign‑in. Kontrollera WEB_CLIENT_ID i Auth.kt och på servern.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Logga ut och nollställ lokalt state. */
|
|
||||||
fun clear(ctx: Context) {
|
|
||||||
idToken = null
|
|
||||||
userId = null
|
|
||||||
email = null
|
|
||||||
ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().clear().apply()
|
|
||||||
signInClient(ctx).signOut()
|
|
||||||
_loggedIn.value = false
|
|
||||||
_email.value = null
|
|
||||||
// Clear shared KMP state too
|
|
||||||
AuthShared.clearAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Försök uppdatera auth-status tyst (silent sign-in).
|
|
||||||
* Anropa i onCreate() och vid appstart för att återställa login.
|
|
||||||
*/
|
|
||||||
fun refreshSilently(ctx: Context, onDone: (Boolean) -> Unit) {
|
|
||||||
val last = GoogleSignIn.getLastSignedInAccount(ctx)
|
|
||||||
if (last != null) {
|
|
||||||
// Försök få färsk token tyst
|
|
||||||
signInClient(ctx).silentSignIn()
|
|
||||||
.addOnSuccessListener { acc ->
|
|
||||||
save(ctx, acc)
|
|
||||||
onDone(true)
|
|
||||||
}
|
|
||||||
.addOnFailureListener {
|
|
||||||
// Fall tillbaka till ev. sparat läge
|
|
||||||
loadFromPrefs(ctx)
|
|
||||||
onDone(idToken != null)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
loadFromPrefs(ctx)
|
|
||||||
onDone(idToken != null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -158,6 +158,8 @@ kotlin {
|
|||||||
implementation("com.google.android.gms:play-services-location:21.3.0") // FusedLocation
|
implementation("com.google.android.gms:play-services-location:21.3.0") // FusedLocation
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.9.0") // await() på Tasks
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.9.0") // await() på Tasks
|
||||||
implementation("com.google.maps.android:maps-compose:6.10.0") // Sep 9, 2025
|
implementation("com.google.maps.android:maps-compose:6.10.0") // Sep 9, 2025
|
||||||
|
// Google Sign-In
|
||||||
|
implementation("com.google.android.gms:play-services-auth:21.4.0")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
// shared/src/androidMain/kotlin/app/klottr/util/PlatformAuthStorage.android.kt
|
// shared/src/androidMain/kotlin/app/klottr/util/PlatformAuthStorage.android.kt
|
||||||
package app.klottr.util
|
package app.klottr.util
|
||||||
|
|
||||||
/** In-memory stub; Android keeps its own SharedPreferences today. */
|
|
||||||
actual object PlatformAuthStorage {
|
actual object PlatformAuthStorage {
|
||||||
private val mem = mutableMapOf<String, String>()
|
private var delegate: AuthStorageDelegate? = null
|
||||||
actual fun get(key: String) = mem[key]
|
|
||||||
actual fun set(key: String, value: String?) {
|
|
||||||
if (value == null) mem.remove(key) else mem[key] = value
|
|
||||||
}
|
|
||||||
actual fun clear() = mem.clear()
|
|
||||||
|
|
||||||
actual fun install(delegate: AuthStorageDelegate) { /* no-op on Android */ }
|
actual fun install(delegate: AuthStorageDelegate) {
|
||||||
|
this.delegate = delegate
|
||||||
|
}
|
||||||
|
|
||||||
|
actual fun get(key: String): String? = delegate?.get(key)
|
||||||
|
actual fun set(key: String, value: String?) { delegate?.set(key, value) }
|
||||||
|
actual fun clear() { delegate?.clear() }
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user