feat: appairage par code d'appareil depuis l'écran de connexion (2.16.0)
- Bouton « Se connecter avec mon compte Dracodev » à l'écran de connexion (voie principale pour une instance Dracodev) : demande de code à POST /api/pairing/device, écran d'attente (code en grand, verification_uri, bouton navigateur, compte à rebours, annulation), interrogation de POST /api/pairing/token en respectant interval et slow_down (+5 s), états d'échec propres (access_denied, expired_token). - Secret d'appareil shd_… stocké via TokenManager (EncryptedSharedPreferences) avec drapeau d'origine appairé/manuel et nom du compte ; JwtGenerator et AuthInterceptor inchangés. Vérification immédiate par GET /api/v1/info, secret effacé en cas d'échec. - Le champ « secret manuel » reste (client Shaarli générique). - Désappairage dans les Paramètres : effacement local + message clair (aucun endpoint de révocation self-service côté serveur ; la révocation se fait depuis les Réglages web, section Appareils appairés). - 401 persistant : SessionManager dépose un message explicite que l'écran de connexion affiche au retour. - Étiquette d'appareil : modèle + version de l'app, aucune empreinte. - Écran de connexion traduit en français ; version 2.16.0 (code 47). Contrat consommé : celui d'APP-2 (ShaarIt 0.8.0, PR shaarit#20). Rejeu boîte noire contre le serveur 0.8.0 compilé depuis la branche appairage-shaarit-serveur : 32/32 + chemin du refus (voir la PR).
This commit is contained in:
@@ -12,7 +12,8 @@
|
|||||||
## 📱 Fonctionnalités
|
## 📱 Fonctionnalités
|
||||||
|
|
||||||
### 🔐 Authentification
|
### 🔐 Authentification
|
||||||
- Connexion sécurisée à votre instance Shaarli auto-hébergée (API v1)
|
- **Appairage par code d'appareil (2.16.0)** : sur une instance Dracodev (serveur ShaarIt 0.8.0+), le bouton « Se connecter avec mon compte Dracodev » de l'écran de connexion demande un code au serveur, l'affiche en grand, et l'approbation se fait dans un navigateur connecté au compte de la suite — l'app reçoit un secret propre à l'appareil (`shd_…`), stocké chiffré avec un drapeau d'origine, révocable depuis les Réglages web du serveur. Désappairage depuis les Paramètres de l'app (effacement local ; la révocation reste un geste web).
|
||||||
|
- Connexion sécurisée à votre instance Shaarli auto-hébergée (API v1) — le champ « secret API » manuel reste disponible pour les instances tierces et en secours
|
||||||
- Stockage chiffré des tokens JWT et secrets API via `EncryptedSharedPreferences`
|
- Stockage chiffré des tokens JWT et secrets API via `EncryptedSharedPreferences`
|
||||||
- Génération automatique de tokens JWT avec algorithme HS512
|
- Génération automatique de tokens JWT avec algorithme HS512
|
||||||
- Vérification automatique du token au démarrage (skip login si valide)
|
- Vérification automatique du token au démarrage (skip login si valide)
|
||||||
|
|||||||
@@ -69,4 +69,10 @@ object NetworkModule {
|
|||||||
fun provideShaarliApi(retrofit: Retrofit): ShaarliApi {
|
fun provideShaarliApi(retrofit: Retrofit): ShaarliApi {
|
||||||
return retrofit.create(ShaarliApi::class.java)
|
return retrofit.create(ShaarliApi::class.java)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun providePairingApi(retrofit: Retrofit): com.shaarit.data.api.PairingApi {
|
||||||
|
return retrofit.create(com.shaarit.data.api.PairingApi::class.java)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ abstract class RepositoryModule {
|
|||||||
|
|
||||||
@Binds @Singleton abstract fun bindAuthRepository(impl: AuthRepositoryImpl): AuthRepository
|
@Binds @Singleton abstract fun bindAuthRepository(impl: AuthRepositoryImpl): AuthRepository
|
||||||
|
|
||||||
|
@Binds
|
||||||
|
@Singleton
|
||||||
|
abstract fun bindPairingRepository(
|
||||||
|
impl: com.shaarit.data.repository.PairingRepositoryImpl
|
||||||
|
): com.shaarit.domain.repository.PairingRepository
|
||||||
|
|
||||||
@Binds @Singleton abstract fun bindLinkRepository(impl: LinkRepositoryImpl): LinkRepository
|
@Binds @Singleton abstract fun bindLinkRepository(impl: LinkRepositoryImpl): LinkRepository
|
||||||
|
|
||||||
@Binds @Singleton abstract fun bindGeminiRepository(impl: GeminiRepositoryImpl): GeminiRepository
|
@Binds @Singleton abstract fun bindGeminiRepository(impl: GeminiRepositoryImpl): GeminiRepository
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package com.shaarit.core.network
|
package com.shaarit.core.network
|
||||||
|
|
||||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharedFlow
|
import kotlinx.coroutines.flow.SharedFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asSharedFlow
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@@ -19,7 +22,24 @@ class SessionManager @Inject constructor() {
|
|||||||
private val _unauthorized = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
|
private val _unauthorized = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
|
||||||
val unauthorized: SharedFlow<Unit> = _unauthorized.asSharedFlow()
|
val unauthorized: SharedFlow<Unit> = _unauthorized.asSharedFlow()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Message explicite destiné à l'écran de connexion après un 401
|
||||||
|
* persistant (appareil révoqué côté web, secret régénéré…). Conservé
|
||||||
|
* dans un [StateFlow] pour survivre à la navigation : l'écran de
|
||||||
|
* connexion le lit à son arrivée puis le consomme, plutôt que de
|
||||||
|
* laisser l'utilisateur revenir sans explication.
|
||||||
|
*/
|
||||||
|
private val _expiredMessage = MutableStateFlow<String?>(null)
|
||||||
|
val expiredMessage: StateFlow<String?> = _expiredMessage.asStateFlow()
|
||||||
|
|
||||||
fun onUnauthorized() {
|
fun onUnauthorized() {
|
||||||
|
_expiredMessage.value =
|
||||||
|
"Cet appareil a été désappairé ou le secret a été révoqué côté " +
|
||||||
|
"serveur. Reconnectez-vous pour continuer."
|
||||||
_unauthorized.tryEmit(Unit)
|
_unauthorized.tryEmit(Unit)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun consumeExpiredMessage() {
|
||||||
|
_expiredMessage.value = null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,19 @@ import dagger.hilt.android.qualifiers.ApplicationContext
|
|||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Origine du secret API stocké : saisi à la main par l'utilisateur (secret
|
||||||
|
* d'instance Shaarli, instances tierces incluses) ou reçu par appairage
|
||||||
|
* (secret d'appareil `shd_…` émis par une instance Dracodev, conception
|
||||||
|
* DRACODEV-APPAIRAGE-ANDROID §3.2). Le drapeau sert à l'affichage dans les
|
||||||
|
* réglages et au désappairage ; il ne change rien à la signature des JWT,
|
||||||
|
* qui utilise toujours « le secret stocké », quelle que soit son origine.
|
||||||
|
*/
|
||||||
|
enum class SecretOrigin {
|
||||||
|
MANUAL,
|
||||||
|
PAIRED
|
||||||
|
}
|
||||||
|
|
||||||
interface TokenManager {
|
interface TokenManager {
|
||||||
fun saveToken(token: String)
|
fun saveToken(token: String)
|
||||||
fun getToken(): String?
|
fun getToken(): String?
|
||||||
@@ -19,6 +32,11 @@ interface TokenManager {
|
|||||||
fun getApiSecret(): String?
|
fun getApiSecret(): String?
|
||||||
fun clearApiSecret()
|
fun clearApiSecret()
|
||||||
|
|
||||||
|
/** Enregistre un secret reçu par appairage, avec le nom du compte approuvant. */
|
||||||
|
fun savePairedApiSecret(secret: String, accountName: String?)
|
||||||
|
fun getSecretOrigin(): SecretOrigin
|
||||||
|
fun getPairedAccountName(): String?
|
||||||
|
|
||||||
fun setCollectionsConfigDirty(isDirty: Boolean)
|
fun setCollectionsConfigDirty(isDirty: Boolean)
|
||||||
fun isCollectionsConfigDirty(): Boolean
|
fun isCollectionsConfigDirty(): Boolean
|
||||||
fun saveCollectionsConfigBookmarkId(id: Int)
|
fun saveCollectionsConfigBookmarkId(id: Int)
|
||||||
@@ -84,7 +102,14 @@ class TokenManagerImpl @Inject constructor(@ApplicationContext private val conte
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun saveApiSecret(secret: String) {
|
override fun saveApiSecret(secret: String) {
|
||||||
sharedPreferences.edit().putString(KEY_API_SECRET, secret).apply()
|
// Tous les appelants historiques de saveApiSecret sont des saisies
|
||||||
|
// manuelles (écran de connexion, réglages) : l'origine suit.
|
||||||
|
sharedPreferences
|
||||||
|
.edit()
|
||||||
|
.putString(KEY_API_SECRET, secret)
|
||||||
|
.putString(KEY_SECRET_ORIGIN, SecretOrigin.MANUAL.name)
|
||||||
|
.remove(KEY_PAIRED_ACCOUNT_NAME)
|
||||||
|
.apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getApiSecret(): String? {
|
override fun getApiSecret(): String? {
|
||||||
@@ -92,7 +117,33 @@ class TokenManagerImpl @Inject constructor(@ApplicationContext private val conte
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun clearApiSecret() {
|
override fun clearApiSecret() {
|
||||||
sharedPreferences.edit().remove(KEY_API_SECRET).apply()
|
sharedPreferences
|
||||||
|
.edit()
|
||||||
|
.remove(KEY_API_SECRET)
|
||||||
|
.remove(KEY_SECRET_ORIGIN)
|
||||||
|
.remove(KEY_PAIRED_ACCOUNT_NAME)
|
||||||
|
.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun savePairedApiSecret(secret: String, accountName: String?) {
|
||||||
|
val editor = sharedPreferences.edit()
|
||||||
|
editor.putString(KEY_API_SECRET, secret)
|
||||||
|
editor.putString(KEY_SECRET_ORIGIN, SecretOrigin.PAIRED.name)
|
||||||
|
if (accountName.isNullOrBlank()) {
|
||||||
|
editor.remove(KEY_PAIRED_ACCOUNT_NAME)
|
||||||
|
} else {
|
||||||
|
editor.putString(KEY_PAIRED_ACCOUNT_NAME, accountName)
|
||||||
|
}
|
||||||
|
editor.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getSecretOrigin(): SecretOrigin {
|
||||||
|
val raw = sharedPreferences.getString(KEY_SECRET_ORIGIN, null)
|
||||||
|
return runCatching { SecretOrigin.valueOf(raw ?: "") }.getOrDefault(SecretOrigin.MANUAL)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getPairedAccountName(): String? {
|
||||||
|
return sharedPreferences.getString(KEY_PAIRED_ACCOUNT_NAME, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun setCollectionsConfigDirty(isDirty: Boolean) {
|
override fun setCollectionsConfigDirty(isDirty: Boolean) {
|
||||||
@@ -143,6 +194,8 @@ class TokenManagerImpl @Inject constructor(@ApplicationContext private val conte
|
|||||||
private const val KEY_TOKEN = "jwt_token"
|
private const val KEY_TOKEN = "jwt_token"
|
||||||
private const val KEY_BASE_URL = "base_url"
|
private const val KEY_BASE_URL = "base_url"
|
||||||
private const val KEY_API_SECRET = "api_secret"
|
private const val KEY_API_SECRET = "api_secret"
|
||||||
|
private const val KEY_SECRET_ORIGIN = "api_secret_origin"
|
||||||
|
private const val KEY_PAIRED_ACCOUNT_NAME = "paired_account_name"
|
||||||
|
|
||||||
private const val KEY_COLLECTIONS_DIRTY = "collections_config_dirty"
|
private const val KEY_COLLECTIONS_DIRTY = "collections_config_dirty"
|
||||||
private const val KEY_COLLECTIONS_BOOKMARK_ID = "collections_config_bookmark_id"
|
private const val KEY_COLLECTIONS_BOOKMARK_ID = "collections_config_bookmark_id"
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.shaarit.data.api
|
||||||
|
|
||||||
|
import com.shaarit.data.dto.PairingDeviceRequestDto
|
||||||
|
import com.shaarit.data.dto.PairingDeviceResponseDto
|
||||||
|
import com.shaarit.data.dto.PairingTokenRequestDto
|
||||||
|
import com.shaarit.data.dto.PairingTokenResponseDto
|
||||||
|
import retrofit2.Response
|
||||||
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.POST
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Endpoints d'appairage (code d'appareil, RFC 8628 adapté). Ils sont servis
|
||||||
|
* par le serveur d'application choisi par l'utilisateur, à sa racine — le
|
||||||
|
* [com.shaarit.core.network.HostSelectionInterceptor] réécrit l'hôte depuis
|
||||||
|
* l'URL enregistrée, comme pour l'API v1.
|
||||||
|
*
|
||||||
|
* Les réponses sont lues en [Response] plutôt qu'en exception : les statuts
|
||||||
|
* 428 (en attente), 429 (ralentir) et 400 (refusé / expiré) font partie du
|
||||||
|
* flux normal de l'interrogation, pas des erreurs.
|
||||||
|
*/
|
||||||
|
interface PairingApi {
|
||||||
|
|
||||||
|
/** Demande un couple (code d'appareil secret, code utilisateur court). */
|
||||||
|
@POST("/api/pairing/device")
|
||||||
|
suspend fun requestDeviceCode(
|
||||||
|
@Body body: PairingDeviceRequestDto
|
||||||
|
): Response<PairingDeviceResponseDto>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interroge l'état de la demande. Succès (200) = le secret d'appareil
|
||||||
|
* `shd_…`, délivré une seule fois.
|
||||||
|
*/
|
||||||
|
@POST("/api/pairing/token")
|
||||||
|
suspend fun pollToken(@Body body: PairingTokenRequestDto): Response<PairingTokenResponseDto>
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.shaarit.data.dto
|
||||||
|
|
||||||
|
import com.squareup.moshi.Json
|
||||||
|
import com.squareup.moshi.JsonClass
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrat d'appairage consommé par l'application (conception
|
||||||
|
* DRACODEV-APPAIRAGE-ANDROID §4.2, implémenté côté serveur par APP-2 /
|
||||||
|
* ShaarIt 0.8.0). Ces routes vivent à la racine du serveur choisi par
|
||||||
|
* l'utilisateur, HORS de `/api/v1` : le contrat Shaarli n'est pas touché.
|
||||||
|
* Les erreurs sont des objets JSON `{"error": …}` au vocabulaire RFC 8628.
|
||||||
|
*/
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class PairingDeviceRequestDto(
|
||||||
|
@Json(name = "app") val app: String,
|
||||||
|
@Json(name = "device_label") val deviceLabel: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class PairingDeviceResponseDto(
|
||||||
|
@Json(name = "device_code") val deviceCode: String,
|
||||||
|
@Json(name = "user_code") val userCode: String,
|
||||||
|
@Json(name = "verification_uri") val verificationUri: String,
|
||||||
|
@Json(name = "verification_uri_complete") val verificationUriComplete: String,
|
||||||
|
@Json(name = "expires_in") val expiresInSeconds: Long,
|
||||||
|
@Json(name = "interval") val intervalSeconds: Long
|
||||||
|
)
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class PairingTokenRequestDto(@Json(name = "device_code") val deviceCode: String)
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class PairingTokenResponseDto(
|
||||||
|
@Json(name = "api_secret") val apiSecret: String,
|
||||||
|
@Json(name = "account_name") val accountName: String?
|
||||||
|
)
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class PairingErrorDto(@Json(name = "error") val error: String?)
|
||||||
@@ -70,6 +70,54 @@ constructor(private val api: ShaarliApi, private val tokenManager: TokenManager)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun completePairing(
|
||||||
|
serverUrl: String,
|
||||||
|
deviceSecret: String,
|
||||||
|
accountName: String?
|
||||||
|
): Result<String?> {
|
||||||
|
// 1. URL d'abord (routage), 2. secret d'appareil avec son origine.
|
||||||
|
tokenManager.saveBaseUrl(serverUrl)
|
||||||
|
tokenManager.savePairedApiSecret(deviceSecret, accountName)
|
||||||
|
|
||||||
|
// 3. Vérification immédiate par un appel réel, comme la connexion
|
||||||
|
// manuelle. Échec = secret effacé, retour à l'écran de connexion.
|
||||||
|
return try {
|
||||||
|
api.getInfo()
|
||||||
|
Result.success(accountName)
|
||||||
|
} catch (e: HttpException) {
|
||||||
|
tokenManager.clearApiSecret()
|
||||||
|
e.printStackTrace()
|
||||||
|
Result.failure(
|
||||||
|
Exception(
|
||||||
|
"Le secret d'appareil reçu a été refusé par le serveur " +
|
||||||
|
"(HTTP ${e.code()}). L'appairage n'a pas abouti ; " +
|
||||||
|
"réessayez ou utilisez le secret API."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
tokenManager.clearApiSecret()
|
||||||
|
e.printStackTrace()
|
||||||
|
Result.failure(
|
||||||
|
Exception(
|
||||||
|
"Serveur injoignable pendant la vérification de l'appairage " +
|
||||||
|
"(${e.message}). Le secret reçu n'a pas été conservé."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
tokenManager.clearApiSecret()
|
||||||
|
e.printStackTrace()
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getSecretOrigin(): com.shaarit.core.storage.SecretOrigin {
|
||||||
|
return tokenManager.getSecretOrigin()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getPairedAccountName(): String? {
|
||||||
|
return tokenManager.getPairedAccountName()
|
||||||
|
}
|
||||||
|
|
||||||
override fun isLoggedIn(): Boolean {
|
override fun isLoggedIn(): Boolean {
|
||||||
// We're logged in if we have both base URL and API secret
|
// We're logged in if we have both base URL and API secret
|
||||||
return !tokenManager.getApiSecret().isNullOrBlank() &&
|
return !tokenManager.getApiSecret().isNullOrBlank() &&
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package com.shaarit.data.repository
|
||||||
|
|
||||||
|
import com.shaarit.core.storage.TokenManager
|
||||||
|
import com.shaarit.data.api.PairingApi
|
||||||
|
import com.shaarit.data.dto.PairingDeviceRequestDto
|
||||||
|
import com.shaarit.data.dto.PairingErrorDto
|
||||||
|
import com.shaarit.data.dto.PairingTokenRequestDto
|
||||||
|
import com.shaarit.domain.repository.PairingPollResult
|
||||||
|
import com.shaarit.domain.repository.PairingRepository
|
||||||
|
import com.shaarit.domain.repository.PairingSession
|
||||||
|
import com.squareup.moshi.Moshi
|
||||||
|
import java.io.IOException
|
||||||
|
import javax.inject.Inject
|
||||||
|
import retrofit2.Response
|
||||||
|
|
||||||
|
class PairingRepositoryImpl
|
||||||
|
@Inject
|
||||||
|
constructor(
|
||||||
|
private val api: PairingApi,
|
||||||
|
private val tokenManager: TokenManager,
|
||||||
|
private val moshi: Moshi
|
||||||
|
) : PairingRepository {
|
||||||
|
|
||||||
|
override suspend fun requestDeviceCode(
|
||||||
|
serverUrl: String,
|
||||||
|
deviceLabel: String
|
||||||
|
): Result<PairingSession> {
|
||||||
|
// Même patron que la connexion manuelle : l'URL est enregistrée
|
||||||
|
// d'abord, l'intercepteur de sélection d'hôte route ensuite tous
|
||||||
|
// les appels (appairage puis API v1) vers ce serveur-là.
|
||||||
|
tokenManager.saveBaseUrl(serverUrl.trim())
|
||||||
|
|
||||||
|
return try {
|
||||||
|
val response =
|
||||||
|
api.requestDeviceCode(
|
||||||
|
PairingDeviceRequestDto(app = APP_ID, deviceLabel = deviceLabel)
|
||||||
|
)
|
||||||
|
val body = response.body()
|
||||||
|
when {
|
||||||
|
response.isSuccessful && body != null ->
|
||||||
|
Result.success(
|
||||||
|
PairingSession(
|
||||||
|
deviceCode = body.deviceCode,
|
||||||
|
userCode = body.userCode,
|
||||||
|
verificationUri = body.verificationUri,
|
||||||
|
verificationUriComplete = body.verificationUriComplete,
|
||||||
|
expiresInSeconds = body.expiresInSeconds,
|
||||||
|
intervalSeconds = body.intervalSeconds
|
||||||
|
)
|
||||||
|
)
|
||||||
|
response.code() == 404 ->
|
||||||
|
Result.failure(
|
||||||
|
Exception(
|
||||||
|
"Ce serveur ne propose pas l'appairage (instance " +
|
||||||
|
"Shaarli classique ou serveur trop ancien). " +
|
||||||
|
"Utilisez le secret API ci-dessous."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
response.code() == 429 ->
|
||||||
|
Result.failure(
|
||||||
|
Exception(
|
||||||
|
"Trop de demandes d'appairage depuis ce réseau. " +
|
||||||
|
"Réessayez dans quelques minutes."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else ->
|
||||||
|
Result.failure(
|
||||||
|
Exception(
|
||||||
|
"Le serveur a refusé la demande d'appairage " +
|
||||||
|
"(HTTP ${response.code()})."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
Result.failure(
|
||||||
|
Exception(
|
||||||
|
"Serveur injoignable (${e.message}). Vérifiez l'URL et la " +
|
||||||
|
"connexion réseau."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun pollOnce(deviceCode: String): PairingPollResult {
|
||||||
|
val response: Response<com.shaarit.data.dto.PairingTokenResponseDto>
|
||||||
|
try {
|
||||||
|
response = api.pollToken(PairingTokenRequestDto(deviceCode = deviceCode))
|
||||||
|
} catch (e: IOException) {
|
||||||
|
return PairingPollResult.Failure(
|
||||||
|
"Serveur injoignable (${e.message}). Vérifiez la connexion réseau."
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
return PairingPollResult.Failure(e.message ?: "Erreur inattendue pendant l'appairage.")
|
||||||
|
}
|
||||||
|
|
||||||
|
val body = response.body()
|
||||||
|
if (response.isSuccessful && body != null) {
|
||||||
|
return PairingPollResult.Approved(
|
||||||
|
apiSecret = body.apiSecret,
|
||||||
|
accountName = body.accountName
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return when (response.code()) {
|
||||||
|
428 -> PairingPollResult.Pending
|
||||||
|
429 -> PairingPollResult.SlowDown
|
||||||
|
400 ->
|
||||||
|
when (parseError(response)) {
|
||||||
|
"access_denied" -> PairingPollResult.Denied
|
||||||
|
"expired_token" -> PairingPollResult.Expired
|
||||||
|
else ->
|
||||||
|
PairingPollResult.Failure(
|
||||||
|
"Le serveur a mis fin à la demande d'appairage " +
|
||||||
|
"(HTTP 400)."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
else ->
|
||||||
|
PairingPollResult.Failure(
|
||||||
|
"Réponse inattendue du serveur (HTTP ${response.code()}) " +
|
||||||
|
"pendant l'appairage."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseError(response: Response<*>): String? {
|
||||||
|
val raw = runCatching { response.errorBody()?.string() }.getOrNull() ?: return null
|
||||||
|
return runCatching {
|
||||||
|
moshi.adapter(PairingErrorDto::class.java).fromJson(raw)?.error
|
||||||
|
}
|
||||||
|
.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** Identité déclarée de l'application, montrée sur la page d'approbation. */
|
||||||
|
const val APP_ID = "shaarit-android"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,27 @@
|
|||||||
package com.shaarit.domain.repository
|
package com.shaarit.domain.repository
|
||||||
|
|
||||||
|
import com.shaarit.core.storage.SecretOrigin
|
||||||
import com.shaarit.domain.model.Credentials
|
import com.shaarit.domain.model.Credentials
|
||||||
|
|
||||||
interface AuthRepository {
|
interface AuthRepository {
|
||||||
suspend fun login(credentials: Credentials, serverUrl: String): Result<Boolean>
|
suspend fun login(credentials: Credentials, serverUrl: String): Result<Boolean>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Termine un appairage : enregistre le secret d'appareil reçu (avec son
|
||||||
|
* drapeau d'origine), puis le vérifie immédiatement par l'appel réel
|
||||||
|
* `GET /api/v1/info` — le même que la connexion manuelle. En cas d'échec,
|
||||||
|
* le secret est effacé et l'utilisateur revient à l'écran de connexion.
|
||||||
|
* Retourne le nom du compte approuvant quand la vérification réussit.
|
||||||
|
*/
|
||||||
|
suspend fun completePairing(
|
||||||
|
serverUrl: String,
|
||||||
|
deviceSecret: String,
|
||||||
|
accountName: String?
|
||||||
|
): Result<String?>
|
||||||
|
|
||||||
fun isLoggedIn(): Boolean
|
fun isLoggedIn(): Boolean
|
||||||
fun logout()
|
fun logout()
|
||||||
fun getBaseUrl(): String?
|
fun getBaseUrl(): String?
|
||||||
|
fun getSecretOrigin(): SecretOrigin
|
||||||
|
fun getPairedAccountName(): String?
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.shaarit.domain.repository
|
||||||
|
|
||||||
|
/** Une demande d'appairage émise par le serveur, en attente d'approbation. */
|
||||||
|
data class PairingSession(
|
||||||
|
val deviceCode: String,
|
||||||
|
val userCode: String,
|
||||||
|
val verificationUri: String,
|
||||||
|
val verificationUriComplete: String,
|
||||||
|
val expiresInSeconds: Long,
|
||||||
|
val intervalSeconds: Long
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Résultat d'une interrogation de `/api/pairing/token` (vocabulaire RFC 8628). */
|
||||||
|
sealed class PairingPollResult {
|
||||||
|
/** 428 — l'utilisateur n'a pas encore approuvé : continuer d'attendre. */
|
||||||
|
object Pending : PairingPollResult()
|
||||||
|
|
||||||
|
/** 429 — interrogation trop rapide : allonger l'intervalle et continuer. */
|
||||||
|
object SlowDown : PairingPollResult()
|
||||||
|
|
||||||
|
/** 400 `access_denied` — l'utilisateur a refusé (ou plafond d'appareils atteint). */
|
||||||
|
object Denied : PairingPollResult()
|
||||||
|
|
||||||
|
/** 400 `expired_token` — demande expirée, consommée ou inconnue. */
|
||||||
|
object Expired : PairingPollResult()
|
||||||
|
|
||||||
|
/** 200 — approuvée : le secret d'appareil, délivré une seule fois. */
|
||||||
|
data class Approved(val apiSecret: String, val accountName: String?) : PairingPollResult()
|
||||||
|
|
||||||
|
/** Échec technique (réseau, statut inattendu) : le message est affichable. */
|
||||||
|
data class Failure(val message: String) : PairingPollResult()
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PairingRepository {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enregistre d'abord l'URL du serveur (pour que l'intercepteur de
|
||||||
|
* sélection d'hôte route les appels), puis demande un code d'appareil
|
||||||
|
* au serveur choisi. [deviceLabel] = modèle + version de l'app, jamais
|
||||||
|
* une empreinte matérielle.
|
||||||
|
*/
|
||||||
|
suspend fun requestDeviceCode(serverUrl: String, deviceLabel: String): Result<PairingSession>
|
||||||
|
|
||||||
|
/** Une seule interrogation ; la boucle et le rythme vivent dans l'écran. */
|
||||||
|
suspend fun pollOnce(deviceCode: String): PairingPollResult
|
||||||
|
}
|
||||||
@@ -24,6 +24,7 @@ import com.shaarit.ui.theme.Typography
|
|||||||
@Composable
|
@Composable
|
||||||
fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltViewModel()) {
|
fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltViewModel()) {
|
||||||
val uiState by viewModel.uiState.collectAsState()
|
val uiState by viewModel.uiState.collectAsState()
|
||||||
|
val pairingState by viewModel.pairingState.collectAsState()
|
||||||
val snackbarHostState = remember { SnackbarHostState() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
|
|
||||||
var url by remember { mutableStateOf(viewModel.getInitialUrl()) }
|
var url by remember { mutableStateOf(viewModel.getInitialUrl()) }
|
||||||
@@ -114,13 +115,20 @@ fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltView
|
|||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Your personal bookmark manager",
|
text = "Votre gestionnaire de favoris personnel",
|
||||||
style = MaterialTheme.typography.bodyLarge,
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
textAlign = TextAlign.Center
|
textAlign = TextAlign.Center
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (pairingState !is PairingUiState.Inactif) {
|
||||||
|
// Écran d'appairage : code, page d'approbation, attente.
|
||||||
|
PairingContent(
|
||||||
|
state = pairingState,
|
||||||
|
onCancel = { viewModel.cancelPairing() }
|
||||||
|
)
|
||||||
|
} else {
|
||||||
// Login Card
|
// Login Card
|
||||||
GlassCard(modifier = Modifier.fillMaxWidth()) {
|
GlassCard(modifier = Modifier.fillMaxWidth()) {
|
||||||
Column(
|
Column(
|
||||||
@@ -128,7 +136,7 @@ fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltView
|
|||||||
verticalArrangement = Arrangement.spacedBy(20.dp)
|
verticalArrangement = Arrangement.spacedBy(20.dp)
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = "Connect to Shaarli",
|
text = "Connexion à Shaarli",
|
||||||
style = MaterialTheme.typography.titleLarge,
|
style = MaterialTheme.typography.titleLarge,
|
||||||
fontWeight = FontWeight.SemiBold,
|
fontWeight = FontWeight.SemiBold,
|
||||||
color = MaterialTheme.colorScheme.onBackground
|
color = MaterialTheme.colorScheme.onBackground
|
||||||
@@ -138,16 +146,40 @@ fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltView
|
|||||||
value = url,
|
value = url,
|
||||||
onValueChange = { url = it },
|
onValueChange = { url = it },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
label = "Server URL",
|
label = "URL du serveur",
|
||||||
placeholder = "https://your-shaarli.com"
|
placeholder = "https://votre-shaarli.com"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Voie principale sur une instance Dracodev :
|
||||||
|
// l'appairage par code d'appareil, aucun secret
|
||||||
|
// à copier-coller.
|
||||||
|
GradientButton(
|
||||||
|
text = "Se connecter avec mon compte Dracodev",
|
||||||
|
onClick = { viewModel.startPairing(url) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
enabled = url.isNotBlank() && uiState !is LoginUiState.Loading
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||||
|
) {
|
||||||
|
Divider(modifier = Modifier.weight(1f))
|
||||||
|
Text(
|
||||||
|
text = "ou, avec le secret de l'instance",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.outline
|
||||||
|
)
|
||||||
|
Divider(modifier = Modifier.weight(1f))
|
||||||
|
}
|
||||||
|
|
||||||
PremiumTextField(
|
PremiumTextField(
|
||||||
value = secret,
|
value = secret,
|
||||||
onValueChange = { secret = it },
|
onValueChange = { secret = it },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
label = "API Secret",
|
label = "Secret API",
|
||||||
placeholder = "Enter your API secret",
|
placeholder = "Saisissez le secret API de l'instance",
|
||||||
isPassword = true,
|
isPassword = true,
|
||||||
passwordVisible = showSecret,
|
passwordVisible = showSecret,
|
||||||
leadingIcon = {
|
leadingIcon = {
|
||||||
@@ -160,7 +192,7 @@ fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltView
|
|||||||
trailingIcon = {
|
trailingIcon = {
|
||||||
TextButton(onClick = { showSecret = !showSecret }) {
|
TextButton(onClick = { showSecret = !showSecret }) {
|
||||||
Text(
|
Text(
|
||||||
if (showSecret) "Hide" else "Show",
|
if (showSecret) "Masquer" else "Afficher",
|
||||||
style = MaterialTheme.typography.labelSmall,
|
style = MaterialTheme.typography.labelSmall,
|
||||||
color = MaterialTheme.colorScheme.outline
|
color = MaterialTheme.colorScheme.outline
|
||||||
)
|
)
|
||||||
@@ -168,20 +200,19 @@ fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltView
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(8.dp))
|
|
||||||
|
|
||||||
if (uiState is LoginUiState.Loading) {
|
if (uiState is LoginUiState.Loading) {
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center
|
||||||
) { CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) }
|
) { CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) }
|
||||||
} else {
|
} else {
|
||||||
GradientButton(
|
OutlinedButton(
|
||||||
text = "Connect",
|
|
||||||
onClick = { viewModel.login(url, secret) },
|
onClick = { viewModel.login(url, secret) },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
enabled = url.isNotBlank() && secret.isNotBlank()
|
enabled = url.isNotBlank() && secret.isNotBlank()
|
||||||
)
|
) {
|
||||||
|
Text(text = "Se connecter avec le secret API")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -190,7 +221,10 @@ fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltView
|
|||||||
Spacer(modifier = Modifier.height(24.dp))
|
Spacer(modifier = Modifier.height(24.dp))
|
||||||
Text(
|
Text(
|
||||||
text =
|
text =
|
||||||
"Find your API secret in Shaarli's\n\"Configuration\" → \"Security\" — it is not\nyour login password",
|
"Instance Dracodev : utilisez l'appairage, aucun secret\n" +
|
||||||
|
"à copier. Sinon, le secret API se trouve dans\n" +
|
||||||
|
"Shaarli, « Configuration » → « Sécurité » —\n" +
|
||||||
|
"ce n'est pas votre mot de passe de connexion.",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.outline,
|
color = MaterialTheme.colorScheme.outline,
|
||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
@@ -199,4 +233,5 @@ fun LoginScreen(onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltView
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,23 @@
|
|||||||
package com.shaarit.presentation.auth
|
package com.shaarit.presentation.auth
|
||||||
|
|
||||||
|
import android.os.Build
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.shaarit.BuildConfig
|
||||||
|
import com.shaarit.core.network.SessionManager
|
||||||
import com.shaarit.data.sync.SyncManager
|
import com.shaarit.data.sync.SyncManager
|
||||||
import com.shaarit.domain.repository.AuthRepository
|
import com.shaarit.domain.repository.AuthRepository
|
||||||
|
import com.shaarit.domain.repository.PairingPollResult
|
||||||
|
import com.shaarit.domain.repository.PairingRepository
|
||||||
|
import com.shaarit.domain.repository.PairingSession
|
||||||
import com.shaarit.domain.usecase.LoginUseCase
|
import com.shaarit.domain.usecase.LoginUseCase
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
@@ -17,14 +26,22 @@ class LoginViewModel
|
|||||||
constructor(
|
constructor(
|
||||||
private val loginUseCase: LoginUseCase,
|
private val loginUseCase: LoginUseCase,
|
||||||
private val authRepository: AuthRepository, // To check login state
|
private val authRepository: AuthRepository, // To check login state
|
||||||
|
private val pairingRepository: PairingRepository,
|
||||||
|
private val sessionManager: SessionManager,
|
||||||
private val syncManager: SyncManager
|
private val syncManager: SyncManager
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.Idle)
|
private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.Idle)
|
||||||
val uiState = _uiState.asStateFlow()
|
val uiState = _uiState.asStateFlow()
|
||||||
|
|
||||||
|
private val _pairingState = MutableStateFlow<PairingUiState>(PairingUiState.Inactif)
|
||||||
|
val pairingState = _pairingState.asStateFlow()
|
||||||
|
|
||||||
|
private var pairingJob: Job? = null
|
||||||
|
|
||||||
init {
|
init {
|
||||||
checkLoginStatus()
|
checkLoginStatus()
|
||||||
|
observeSessionExpired()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun checkLoginStatus() {
|
private fun checkLoginStatus() {
|
||||||
@@ -40,6 +57,22 @@ constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Après un 401 persistant en vie courante (appareil révoqué côté web…),
|
||||||
|
* l'utilisateur revient ici : afficher le message explicite déposé par
|
||||||
|
* [SessionManager] plutôt qu'un écran de connexion muet.
|
||||||
|
*/
|
||||||
|
private fun observeSessionExpired() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
sessionManager.expiredMessage.collect { message ->
|
||||||
|
if (message != null && _uiState.value !is LoginUiState.Success) {
|
||||||
|
_uiState.value = LoginUiState.Error(message)
|
||||||
|
sessionManager.consumeExpiredMessage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun login(url: String, secret: String) {
|
fun login(url: String, secret: String) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_uiState.value = LoginUiState.Loading
|
_uiState.value = LoginUiState.Loading
|
||||||
@@ -50,12 +83,159 @@ constructor(
|
|||||||
_uiState.value = LoginUiState.Success
|
_uiState.value = LoginUiState.Success
|
||||||
},
|
},
|
||||||
onFailure = {
|
onFailure = {
|
||||||
_uiState.value = LoginUiState.Error(it.message ?: "Unknown Error")
|
_uiState.value = LoginUiState.Error(it.message ?: "Erreur inconnue")
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lance l'appairage par code d'appareil (conception §2.2) vers le
|
||||||
|
* serveur saisi : demande du code, affichage, puis interrogation de
|
||||||
|
* `/api/pairing/token` au rythme annoncé par le serveur (`interval`,
|
||||||
|
* allongé de 5 s à chaque `slow_down`) jusqu'à approbation, refus,
|
||||||
|
* expiration ou annulation.
|
||||||
|
*/
|
||||||
|
fun startPairing(url: String) {
|
||||||
|
val cleanUrl = url.trim()
|
||||||
|
if (cleanUrl.isBlank()) {
|
||||||
|
_uiState.value = LoginUiState.Error("Saisissez d'abord l'URL du serveur.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cancelPairing()
|
||||||
|
pairingJob =
|
||||||
|
viewModelScope.launch {
|
||||||
|
_pairingState.value = PairingUiState.DemandeEnCours
|
||||||
|
|
||||||
|
val sessionResult = pairingRepository.requestDeviceCode(cleanUrl, deviceLabel())
|
||||||
|
val session =
|
||||||
|
sessionResult.getOrElse { error ->
|
||||||
|
_pairingState.value = PairingUiState.Inactif
|
||||||
|
_uiState.value =
|
||||||
|
LoginUiState.Error(error.message ?: "Appairage impossible.")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
_pairingState.value =
|
||||||
|
PairingUiState.Attente(session, session.expiresInSeconds.toInt())
|
||||||
|
|
||||||
|
var intervalSeconds = session.intervalSeconds.coerceAtLeast(1)
|
||||||
|
val deadlineMs =
|
||||||
|
System.currentTimeMillis() + session.expiresInSeconds * 1000
|
||||||
|
var consecutiveFailures = 0
|
||||||
|
|
||||||
|
while (isActive) {
|
||||||
|
val remainingMs = deadlineMs - System.currentTimeMillis()
|
||||||
|
if (remainingMs <= 0) break
|
||||||
|
delay(minOf(intervalSeconds, remainingMs / 1000 + 1) * 1000)
|
||||||
|
if (!isActive) return@launch
|
||||||
|
|
||||||
|
_pairingState.value =
|
||||||
|
PairingUiState.Attente(
|
||||||
|
session,
|
||||||
|
((deadlineMs - System.currentTimeMillis()) / 1000)
|
||||||
|
.toInt()
|
||||||
|
.coerceAtLeast(0)
|
||||||
|
)
|
||||||
|
|
||||||
|
val poll = pairingRepository.pollOnce(session.deviceCode)
|
||||||
|
// Annulation pendant l'appel réseau : ne rien traiter.
|
||||||
|
if (!isActive) return@launch
|
||||||
|
|
||||||
|
when (poll) {
|
||||||
|
is PairingPollResult.Pending -> consecutiveFailures = 0
|
||||||
|
is PairingPollResult.SlowDown -> {
|
||||||
|
consecutiveFailures = 0
|
||||||
|
intervalSeconds += 5
|
||||||
|
}
|
||||||
|
is PairingPollResult.Approved -> {
|
||||||
|
_pairingState.value = PairingUiState.Verification
|
||||||
|
val verified =
|
||||||
|
authRepository.completePairing(
|
||||||
|
cleanUrl,
|
||||||
|
poll.apiSecret,
|
||||||
|
poll.accountName
|
||||||
|
)
|
||||||
|
verified.fold(
|
||||||
|
onSuccess = {
|
||||||
|
_pairingState.value = PairingUiState.Inactif
|
||||||
|
syncManager.syncNow()
|
||||||
|
_uiState.value = LoginUiState.Success
|
||||||
|
},
|
||||||
|
onFailure = { error ->
|
||||||
|
_pairingState.value = PairingUiState.Inactif
|
||||||
|
_uiState.value =
|
||||||
|
LoginUiState.Error(
|
||||||
|
error.message
|
||||||
|
?: "Vérification de l'appairage impossible."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
is PairingPollResult.Denied -> {
|
||||||
|
_pairingState.value = PairingUiState.Inactif
|
||||||
|
_uiState.value =
|
||||||
|
LoginUiState.Error(
|
||||||
|
"Appairage refusé. La demande a été refusée " +
|
||||||
|
"dans le navigateur, ou le plafond " +
|
||||||
|
"d'appareils de l'instance est atteint."
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
is PairingPollResult.Expired -> {
|
||||||
|
_pairingState.value = PairingUiState.Inactif
|
||||||
|
_uiState.value =
|
||||||
|
LoginUiState.Error(
|
||||||
|
"Le code d'appairage a expiré. Relancez " +
|
||||||
|
"l'appairage pour obtenir un nouveau code."
|
||||||
|
)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
is PairingPollResult.Failure -> {
|
||||||
|
consecutiveFailures++
|
||||||
|
if (consecutiveFailures >= 3) {
|
||||||
|
_pairingState.value = PairingUiState.Inactif
|
||||||
|
_uiState.value = LoginUiState.Error(poll.message)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isActive) {
|
||||||
|
_pairingState.value = PairingUiState.Inactif
|
||||||
|
_uiState.value =
|
||||||
|
LoginUiState.Error(
|
||||||
|
"Le code d'appairage a expiré sans approbation. " +
|
||||||
|
"Relancez l'appairage pour obtenir un nouveau code."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Annule l'attente : la demande côté serveur expirera seule (10 minutes). */
|
||||||
|
fun cancelPairing() {
|
||||||
|
pairingJob?.cancel()
|
||||||
|
pairingJob = null
|
||||||
|
if (_pairingState.value !is PairingUiState.Inactif) {
|
||||||
|
_pairingState.value = PairingUiState.Inactif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Étiquette déclarée au serveur, montrée sur la page d'approbation :
|
||||||
|
* modèle de l'appareil + version de l'app (ex. « Pixel 8 · ShaarIt
|
||||||
|
* Android 2.16.0 »). Jamais d'empreinte matérielle (conception §2.2).
|
||||||
|
*/
|
||||||
|
private fun deviceLabel(): String {
|
||||||
|
val model = Build.MODEL?.trim().orEmpty()
|
||||||
|
return if (model.isNotBlank()) {
|
||||||
|
"$model · ShaarIt Android ${BuildConfig.VERSION_NAME}"
|
||||||
|
} else {
|
||||||
|
"ShaarIt Android ${BuildConfig.VERSION_NAME}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun getInitialUrl(): String {
|
fun getInitialUrl(): String {
|
||||||
return authRepository.getBaseUrl() ?: "https://bm.dracodev.net"
|
return authRepository.getBaseUrl() ?: "https://bm.dracodev.net"
|
||||||
}
|
}
|
||||||
@@ -67,3 +247,18 @@ sealed class LoginUiState {
|
|||||||
object Success : LoginUiState()
|
object Success : LoginUiState()
|
||||||
data class Error(val message: String) : LoginUiState()
|
data class Error(val message: String) : LoginUiState()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** États de l'écran d'appairage, affichés à la place du formulaire. */
|
||||||
|
sealed class PairingUiState {
|
||||||
|
object Inactif : PairingUiState()
|
||||||
|
|
||||||
|
/** La demande de code est en vol vers le serveur. */
|
||||||
|
object DemandeEnCours : PairingUiState()
|
||||||
|
|
||||||
|
/** Code émis : attente de l'approbation dans le navigateur. */
|
||||||
|
data class Attente(val session: PairingSession, val secondesRestantes: Int) :
|
||||||
|
PairingUiState()
|
||||||
|
|
||||||
|
/** Secret reçu : vérification en cours par l'appel réel `/api/v1/info`. */
|
||||||
|
object Verification : PairingUiState()
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package com.shaarit.presentation.auth
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.shaarit.ui.components.GlassCard
|
||||||
|
import com.shaarit.ui.components.GradientButton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Écran d'attente de l'appairage (conception §2.2, étapes 3 et 6) : le code
|
||||||
|
* utilisateur en grand, l'adresse de la page d'approbation, le bouton pour
|
||||||
|
* ouvrir le navigateur, et l'annulation. L'interrogation du serveur est
|
||||||
|
* menée par [LoginViewModel] ; cet écran ne fait que refléter son état.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun PairingContent(
|
||||||
|
state: PairingUiState,
|
||||||
|
onCancel: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
GlassCard(modifier = modifier.fillMaxWidth()) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(8.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Appairage en cours",
|
||||||
|
style = MaterialTheme.typography.titleLarge,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground
|
||||||
|
)
|
||||||
|
|
||||||
|
when (state) {
|
||||||
|
is PairingUiState.DemandeEnCours -> {
|
||||||
|
CircularProgressIndicator(color = MaterialTheme.colorScheme.primary)
|
||||||
|
Text(
|
||||||
|
text = "Demande du code au serveur…",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
}
|
||||||
|
is PairingUiState.Attente -> {
|
||||||
|
val session = state.session
|
||||||
|
Text(
|
||||||
|
text =
|
||||||
|
"Ouvrez la page d'approbation dans un navigateur " +
|
||||||
|
"connecté à votre compte Dracodev, vérifiez que " +
|
||||||
|
"le code correspond, puis approuvez l'appairage " +
|
||||||
|
"de cet appareil.",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = session.userCode,
|
||||||
|
fontSize = 40.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
letterSpacing = 4.sp,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = session.verificationUri,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
|
||||||
|
GradientButton(
|
||||||
|
text = "Ouvrir le navigateur",
|
||||||
|
onClick = {
|
||||||
|
val intent =
|
||||||
|
Intent(
|
||||||
|
Intent.ACTION_VIEW,
|
||||||
|
Uri.parse(session.verificationUriComplete)
|
||||||
|
)
|
||||||
|
context.startActivity(intent)
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||||
|
) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
strokeWidth = 2.dp
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "En attente d'approbation…",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val minutes = state.secondesRestantes / 60
|
||||||
|
val secondes = state.secondesRestantes % 60
|
||||||
|
Text(
|
||||||
|
text =
|
||||||
|
"Code valable encore %d:%02d".format(minutes, secondes),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.outline,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
}
|
||||||
|
is PairingUiState.Verification -> {
|
||||||
|
CircularProgressIndicator(color = MaterialTheme.colorScheme.primary)
|
||||||
|
Text(
|
||||||
|
text = "Secret d'appareil reçu, vérification auprès du serveur…",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
}
|
||||||
|
is PairingUiState.Inactif -> Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
TextButton(onClick = onCancel) {
|
||||||
|
Text(
|
||||||
|
text = "Annuler l'appairage",
|
||||||
|
color = MaterialTheme.colorScheme.error
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -137,12 +137,18 @@ fun SettingsScreen(
|
|||||||
apiSecret = viewModel.shaarliSecret.collectAsState().value,
|
apiSecret = viewModel.shaarliSecret.collectAsState().value,
|
||||||
isConfigured = viewModel.isShaarliAccountConfigured(),
|
isConfigured = viewModel.isShaarliAccountConfigured(),
|
||||||
isSaving = viewModel.isSavingCredentials.collectAsState().value,
|
isSaving = viewModel.isSavingCredentials.collectAsState().value,
|
||||||
|
secretOrigin = viewModel.getSecretOrigin(),
|
||||||
|
pairedAccountName = viewModel.getPairedAccountName(),
|
||||||
onUrlChange = { viewModel.updateShaarliUrl(it) },
|
onUrlChange = { viewModel.updateShaarliUrl(it) },
|
||||||
onSecretChange = { viewModel.updateShaarliSecret(it) },
|
onSecretChange = { viewModel.updateShaarliSecret(it) },
|
||||||
onSave = { viewModel.saveShaarliCredentials() },
|
onSave = { viewModel.saveShaarliCredentials() },
|
||||||
onLogout = {
|
onLogout = {
|
||||||
viewModel.logoutShaarli()
|
viewModel.logoutShaarli()
|
||||||
onNavigateToLogin()
|
onNavigateToLogin()
|
||||||
|
},
|
||||||
|
onUnpair = {
|
||||||
|
viewModel.unpairDevice()
|
||||||
|
onNavigateToLogin()
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -410,14 +416,20 @@ private fun ShaarliAccountItem(
|
|||||||
apiSecret: String,
|
apiSecret: String,
|
||||||
isConfigured: Boolean,
|
isConfigured: Boolean,
|
||||||
isSaving: Boolean,
|
isSaving: Boolean,
|
||||||
|
secretOrigin: com.shaarit.core.storage.SecretOrigin,
|
||||||
|
pairedAccountName: String?,
|
||||||
onUrlChange: (String) -> Unit,
|
onUrlChange: (String) -> Unit,
|
||||||
onSecretChange: (String) -> Unit,
|
onSecretChange: (String) -> Unit,
|
||||||
onSave: () -> Unit,
|
onSave: () -> Unit,
|
||||||
onLogout: () -> Unit
|
onLogout: () -> Unit,
|
||||||
|
onUnpair: () -> Unit
|
||||||
) {
|
) {
|
||||||
var isExpanded by remember { mutableStateOf(false) }
|
var isExpanded by remember { mutableStateOf(false) }
|
||||||
var showSecret by remember { mutableStateOf(false) }
|
var showSecret by remember { mutableStateOf(false) }
|
||||||
var showLogoutDialog by remember { mutableStateOf(false) }
|
var showLogoutDialog by remember { mutableStateOf(false) }
|
||||||
|
var showUnpairDialog by remember { mutableStateOf(false) }
|
||||||
|
val isPaired =
|
||||||
|
isConfigured && secretOrigin == com.shaarit.core.storage.SecretOrigin.PAIRED
|
||||||
|
|
||||||
Card(
|
Card(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -445,7 +457,7 @@ private fun ShaarliAccountItem(
|
|||||||
style = MaterialTheme.typography.bodyLarge
|
style = MaterialTheme.typography.bodyLarge
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = if (isConfigured) "\u2713 Connect\u00e9" else "Non connect\u00e9",
|
text = when { isPaired -> "\u2713 Connect\u00e9 par appairage"; isConfigured -> "\u2713 Connect\u00e9"; else -> "Non connect\u00e9" },
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = if (isConfigured) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
color = if (isConfigured) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
)
|
)
|
||||||
@@ -540,6 +552,32 @@ private fun ShaarliAccountItem(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isPaired) {
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Cet appareil est appair\u00e9" +
|
||||||
|
(if (pairedAccountName != null) " au compte \u00ab $pairedAccountName \u00bb" else "") +
|
||||||
|
" : il utilise un secret propre \u00e0 cet appareil, r\u00e9vocable " +
|
||||||
|
"depuis les R\u00e9glages web du serveur (section \u00ab Appareils appair\u00e9s \u00bb).",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
|
TextButton(onClick = { showUnpairDialog = true }) {
|
||||||
|
Icon(
|
||||||
|
Icons.Outlined.LinkOff,
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
tint = MaterialTheme.colorScheme.error
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text("D\u00e9sappairer cet appareil", color = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -564,6 +602,35 @@ private fun ShaarliAccountItem(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (showUnpairDialog) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { showUnpairDialog = false },
|
||||||
|
title = { Text("D\u00e9sappairer cet appareil ?") },
|
||||||
|
text = {
|
||||||
|
Text(
|
||||||
|
"Le secret d'appareil sera effac\u00e9 de ce t\u00e9l\u00e9phone et vous " +
|
||||||
|
"reviendrez \u00e0 l'\u00e9cran de connexion. Le secret reste actif " +
|
||||||
|
"c\u00f4t\u00e9 serveur tant qu'il n'est pas r\u00e9voqu\u00e9 depuis les " +
|
||||||
|
"R\u00e9glages web de ShaarIt (section \u00ab Appareils appair\u00e9s \u00bb) : " +
|
||||||
|
"pensez \u00e0 le r\u00e9voquer si ce t\u00e9l\u00e9phone n'est plus entre vos mains."
|
||||||
|
)
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
showUnpairDialog = false
|
||||||
|
onUnpair()
|
||||||
|
}) {
|
||||||
|
Text("D\u00e9sappairer", color = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showUnpairDialog = false }) {
|
||||||
|
Text("Annuler")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
|
|||||||
@@ -340,6 +340,36 @@ class SettingsViewModel @Inject constructor(
|
|||||||
_shaarliSecret.value = ""
|
_shaarliSecret.value = ""
|
||||||
_uiState.value = _uiState.value.copy(message = "D\u00e9connect\u00e9")
|
_uiState.value = _uiState.value.copy(message = "D\u00e9connect\u00e9")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Origine du secret stocké (appairé / manuel), pour l'affichage des réglages. */
|
||||||
|
fun getSecretOrigin(): com.shaarit.core.storage.SecretOrigin {
|
||||||
|
return authRepository.getSecretOrigin()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getPairedAccountName(): String? {
|
||||||
|
return authRepository.getPairedAccountName()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Désappairage : effacement local du secret d'appareil. Le serveur
|
||||||
|
* n'expose à l'application aucun endpoint de révocation de son propre
|
||||||
|
* secret (la révocation se fait depuis les Réglages web de ShaarIt,
|
||||||
|
* section « Appareils appairés », avec effet immédiat) : le message
|
||||||
|
* affiché le dit clairement plutôt que de promettre une révocation
|
||||||
|
* qui n'a pas eu lieu.
|
||||||
|
*/
|
||||||
|
fun unpairDevice() {
|
||||||
|
authRepository.logout()
|
||||||
|
_shaarliSecret.value = ""
|
||||||
|
_uiState.value =
|
||||||
|
_uiState.value.copy(
|
||||||
|
message =
|
||||||
|
"Appareil désappairé : le secret d'appareil a été effacé " +
|
||||||
|
"de ce téléphone. Il reste actif côté serveur tant " +
|
||||||
|
"qu'il n'est pas révoqué depuis les Réglages web de " +
|
||||||
|
"ShaarIt (section « Appareils appairés »)."
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
data class SettingsUiState(
|
data class SettingsUiState(
|
||||||
|
|||||||
+2
-2
@@ -1,3 +1,3 @@
|
|||||||
#Wed Nov 04 09:00:00 2026
|
#Wed Nov 04 09:00:00 2026
|
||||||
VERSION_NAME=2.15.1
|
VERSION_NAME=2.16.0
|
||||||
VERSION_CODE=46
|
VERSION_CODE=47
|
||||||
Reference in New Issue
Block a user