Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.cloudreve.android.api

import kotlinx.serialization.json.JsonElement
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Response
Expand All @@ -18,8 +19,13 @@ import retrofit2.http.Url

interface ApiService {

// With 2FA enabled the server answers code 203 and `data` holds a 2FA session id
// (JSON string) instead of a LoginResponse; finish with [verify2FA].
@POST("api/v4/session/token")
suspend fun login(@Body request: PasswordLoginRequest): Response<ApiResponse<LoginResponse>>
suspend fun login(@Body request: PasswordLoginRequest): Response<ApiResponse<JsonElement>>

@POST("api/v4/session/token/2fa")
suspend fun verify2FA(@Body request: OtpLoginRequest): Response<ApiResponse<LoginResponse>>

// OAuth token exchange returns raw OAuth JSON, not the ApiResponse envelope.
@FormUrlEncoded
Expand Down
10 changes: 10 additions & 0 deletions android/app/src/main/java/org/cloudreve/android/api/Dto.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ data class PasswordLoginRequest(
val password: String,
)

/**
* Second step of a password login when the account has two-factor auth enabled.
* [sessionId] is the value the server returned in `data` alongside code 203.
*/
@Serializable
data class OtpLoginRequest(
val otp: String,
@SerialName("session_id") val sessionId: String,
)

@Serializable
data class RefreshTokenRequest(
@SerialName("refresh_token") val refreshToken: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ fun LoginScreen(viewModel: LoginViewModel, onLoggedIn: () -> Unit) {
) {
Text("Cloudreve", style = MaterialTheme.typography.headlineLarge)
Spacer(Modifier.height(8.dp))

// Password accepted, server is waiting for the authenticator code.
if (state.twoFactorSessionId != null) {
TwoFactorStep(state, viewModel)
return@Column
}

Text(
"Sign in to your server",
style = MaterialTheme.typography.bodyMedium,
Expand Down Expand Up @@ -123,3 +130,52 @@ fun LoginScreen(viewModel: LoginViewModel, onLoggedIn: () -> Unit) {
}
}
}

/**
* Second step of a password login for accounts with two-factor authentication:
* the server has accepted the password and issued a short-lived 2FA session;
* the user types the 6-digit TOTP code to finish.
*/
@Composable
private fun TwoFactorStep(state: LoginUiState, viewModel: LoginViewModel) {
Text(
"Enter the 6-digit code from your authenticator app",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(32.dp))

OutlinedTextField(
value = state.otp,
onValueChange = viewModel::onOtpChange,
label = { Text("Verification code") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
modifier = Modifier.fillMaxWidth(),
)

state.error?.let {
Spacer(Modifier.height(12.dp))
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}

Spacer(Modifier.height(24.dp))
Button(
onClick = viewModel::verify2FA,
enabled = !state.loading && state.otp.length == 6,
modifier = Modifier.fillMaxWidth(),
) {
if (state.loading) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
} else {
Text("Verify")
}
}
Spacer(Modifier.height(12.dp))
androidx.compose.material3.TextButton(
onClick = viewModel::cancelTwoFactor,
enabled = !state.loading,
) {
Text("Back")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
import org.cloudreve.android.api.ApiClient
import org.cloudreve.android.api.LoginResponse
import org.cloudreve.android.api.OtpLoginRequest
import org.cloudreve.android.api.PasswordLoginRequest
import org.cloudreve.android.data.SessionManager
import java.net.URLEncoder
Expand All @@ -19,19 +23,33 @@ data class LoginUiState(
val loading: Boolean = false,
val error: String? = null,
val loggedIn: Boolean = false,
/** Non-null once the server has accepted the password and is waiting for a TOTP code. */
val twoFactorSessionId: String? = null,
val otp: String = "",
)

class LoginViewModel(
private val session: SessionManager,
private val api: ApiClient,
) : ViewModel() {

private companion object {
/** serializer.CodeNotFullySuccess: password accepted, 2FA code still required. */
const val CODE_NOT_FULLY_SUCCESS = 203
/** serializer.CodeNotFound: here, the 2FA session expired. */
const val CODE_NOT_FOUND = 404
}

private val _state = MutableStateFlow(LoginUiState())
val state: StateFlow<LoginUiState> = _state

fun onServerUrlChange(v: String) = _state.value.let { _state.value = it.copy(serverUrl = v, error = null) }
fun onEmailChange(v: String) = _state.value.let { _state.value = it.copy(email = v, error = null) }
fun onPasswordChange(v: String) = _state.value.let { _state.value = it.copy(password = v, error = null) }
fun onOtpChange(v: String) = _state.value.let { _state.value = it.copy(otp = v.filter(Char::isDigit).take(6), error = null) }

/** Abandon the pending 2FA challenge and return to the password form. */
fun cancelTwoFactor() = _state.value.let { _state.value = it.copy(twoFactorSessionId = null, otp = "", error = null) }

fun login() {
val s = _state.value
Expand All @@ -45,24 +63,69 @@ class LoginViewModel(
session.saveServerUrl(s.serverUrl)
val resp = api.service().login(PasswordLoginRequest(s.email, s.password))
val body = resp.body()
if (!resp.isSuccessful || body == null || body.code != 0 || body.data == null) {
if (!resp.isSuccessful || body == null || body.data == null) {
throw Exception(body?.msg ?: "Login failed (HTTP ${resp.code()})")
}
val login = body.data
session.saveSession(
accessToken = login.token.accessToken,
refreshToken = login.token.refreshToken,
accessExpiresAt = ApiClient.parseExpiresAt(login.token.accessExpires),
email = login.user.email,
nick = login.user.nickname,
)
_state.value = _state.value.copy(loading = false, loggedIn = true)
when (body.code) {
// Password accepted; the server wants a TOTP code before issuing tokens.
// `data` is the 2FA session id, valid for ten minutes.
CODE_NOT_FULLY_SUCCESS -> {
val sessionId = (body.data as? JsonPrimitive)?.content
?: throw Exception("Server requested 2FA without a session id")
_state.value = _state.value.copy(loading = false, twoFactorSessionId = sessionId, otp = "")
}
0 -> completeLogin(Json.decodeFromJsonElement(LoginResponse.serializer(), body.data))
else -> throw Exception(body.msg.ifBlank { "Login failed" })
}
} catch (e: Exception) {
_state.value = _state.value.copy(loading = false, error = e.message ?: "Login failed")
}
}
}

/** Second step of a password login: submit the TOTP code for the pending 2FA session. */
fun verify2FA() {
val s = _state.value
val sessionId = s.twoFactorSessionId ?: return
if (s.otp.length != 6) {
_state.value = s.copy(error = "Enter the 6-digit code from your authenticator app")
return
}
_state.value = s.copy(loading = true, error = null)
viewModelScope.launch {
try {
val resp = api.service().verify2FA(OtpLoginRequest(otp = s.otp, sessionId = sessionId))
val body = resp.body()
if (!resp.isSuccessful || body == null || body.code != 0 || body.data == null) {
// A 404 means the ten-minute 2FA session expired: start over.
val expired = body?.code == CODE_NOT_FOUND
_state.value = _state.value.copy(
loading = false,
twoFactorSessionId = if (expired) null else sessionId,
otp = "",
error = if (expired) "Sign-in timed out, please enter your password again"
else body?.msg?.ifBlank { null } ?: "Incorrect code (HTTP ${resp.code()})",
)
return@launch
}
completeLogin(body.data)
} catch (e: Exception) {
_state.value = _state.value.copy(loading = false, otp = "", error = e.message ?: "Verification failed")
}
}
}

private suspend fun completeLogin(login: LoginResponse) {
session.saveSession(
accessToken = login.token.accessToken,
refreshToken = login.token.refreshToken,
accessExpiresAt = ApiClient.parseExpiresAt(login.token.accessExpires),
email = login.user.email,
nick = login.user.nickname,
)
_state.value = _state.value.copy(loading = false, loggedIn = true, twoFactorSessionId = null, otp = "")
}

/**
* Builds the server-side authorize URL for browser sign-in and stashes
* the PKCE verifier + state. The consent page bounces the code to the
Expand Down
33 changes: 31 additions & 2 deletions android/app/src/main/java/org/cloudreve/android/ui/theme/Theme.kt
Original file line number Diff line number Diff line change
@@ -1,28 +1,57 @@
package org.cloudreve.android.ui.theme

import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color

// Every overridden surface sets its matching `on*` colour. Overriding `surface` alone
// leaves Material's defaults for text, which were tuned for a different surface and
// render as low-contrast grey on our near-black; typed text in OutlinedTextField uses
// onSurface and labels use onSurfaceVariant, so both must be set together.
private val LightColors = lightColorScheme(
primary = Color(0xFF4A6FA5),
secondary = Color(0xFF6B8BB8),
background = Color(0xFFFAFBFD),
onBackground = Color(0xFF1A1C1E),
surface = Color(0xFFFAFBFD),
onSurface = Color(0xFF1A1C1E),
surfaceVariant = Color(0xFFE2E6ED),
onSurfaceVariant = Color(0xFF444850),
outline = Color(0xFF757B86),
)

private val DarkColors = darkColorScheme(
primary = Color(0xFF9DB8DC),
secondary = Color(0xFF8AA4CC),
background = Color(0xFF121417),
onBackground = Color(0xFFE3E5E8),
surface = Color(0xFF121417),
onSurface = Color(0xFFE3E5E8),
surfaceVariant = Color(0xFF2A2E34),
onSurfaceVariant = Color(0xFFC2C6CD),
outline = Color(0xFF8B9099),
)

@Composable
fun CloudreveTheme(content: @Composable () -> Unit) {
MaterialTheme(
colorScheme = if (isSystemInDarkTheme()) DarkColors else LightColors,
content = content,
)
) {
// Paint the whole window with the scheme's background. Without this the
// Compose tree inherits the Activity window colour from themes.xml, which does
// not follow the colour scheme: in dark mode the text turned light while the
// window stayed light, leaving the login form light grey on white.
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
contentColor = MaterialTheme.colorScheme.onBackground,
content = content,
)
}
}
5 changes: 5 additions & 0 deletions android/app/src/main/res/values-night/colors.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Matches DarkColors.background in ui/theme/Theme.kt. -->
<color name="window_background">#121417</color>
</resources>
6 changes: 6 additions & 0 deletions android/app/src/main/res/values-night/themes.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Cloudreve" parent="android:Theme.Material.NoActionBar">
<item name="android:windowBackground">@color/window_background</item>
</style>
</resources>
2 changes: 2 additions & 0 deletions android/app/src/main/res/values/colors.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
<!-- Matches LightColors.background in ui/theme/Theme.kt. -->
<color name="window_background">#FAFBFD</color>
</resources>
8 changes: 7 additions & 1 deletion android/app/src/main/res/values/themes.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Cloudreve" parent="android:Theme.Material.Light.NoActionBar" />
<!-- Light variant; values-night/themes.xml overrides this for dark mode so the
window (splash, edge-to-edge insets) follows the system like the Compose
colour scheme does. The two previously disagreed, which made the login form
render light-grey text on a light window in dark mode. -->
<style name="Theme.Cloudreve" parent="android:Theme.Material.Light.NoActionBar">
<item name="android:windowBackground">@color/window_background</item>
</style>
</resources>