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.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
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.6")
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
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.WikiArticleDialog // Ny: dialogskalet ligger nu i ui-paketet
|
||||
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.FoundStore
|
||||
import app.klottr.util.FoundStore.LAYER_KLOTTER
|
||||
@@ -154,7 +158,6 @@ import app.klottr.work.OutboxWorker
|
||||
import coil3.ImageLoader
|
||||
import coil3.compose.setSingletonImageLoaderFactory
|
||||
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.location.Priority
|
||||
import com.google.android.gms.maps.CameraUpdateFactory
|
||||
@@ -207,17 +210,25 @@ class MainActivity : ComponentActivity() {
|
||||
// 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
|
||||
signInLauncher =
|
||||
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res ->
|
||||
val task = GoogleSignIn.getSignedInAccountFromIntent(res.data)
|
||||
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()
|
||||
}
|
||||
AuthPlatform.handleSignInActivityResult(this, res)
|
||||
}
|
||||
|
||||
// Starta LocationService direkt om vi redan har FG-platstillstånd
|
||||
@@ -254,10 +265,10 @@ class MainActivity : ComponentActivity() {
|
||||
KlottrAppShell(
|
||||
onRequestPerms = { this@MainActivity.requestAllRuntimePerms() },
|
||||
onLogin = {
|
||||
val client = Auth.signInClient(this)
|
||||
signInLauncher.launch(client.signInIntent)
|
||||
val signInIntent = AuthPlatform.signInIntent(this)
|
||||
signInLauncher.launch(signInIntent)
|
||||
},
|
||||
onLogout = { Auth.clear(this) }
|
||||
onLogout = { AuthPlatform.clear(this) }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -296,8 +307,8 @@ private fun KlottrAppShell(
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
// Inloggning
|
||||
val loggedIn by Auth.loggedIn.collectAsState(initial = false)
|
||||
LaunchedEffect(Unit) { Auth.refreshSilently(context) { } }
|
||||
val loggedIn by AuthShared.loggedIn.collectAsState(initial = false)
|
||||
LaunchedEffect(Unit) { AuthPlatform.refreshSilently(context) { } }
|
||||
|
||||
// DB/Repo
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user