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
Expand Up @@ -255,10 +255,13 @@ fun AuroraTextField(
onImeAction: (() -> Unit)? = null,
visualTransformation: VisualTransformation = VisualTransformation.None,
trailing: (@Composable () -> Unit)? = null,
enabled: Boolean = true,
) {
val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()
val shape = RoundedCornerShape(AuroraControlCorner)
// A disabled field's text dims like a disabled sign-in button's label.
val inkAlpha = if (enabled) 1f else 0.6f

Column(modifier = modifier.fillMaxWidth()) {
AuroraFieldLabel(label)
Expand Down Expand Up @@ -290,17 +293,18 @@ fun AuroraTextField(
Text(
text = placeholder,
fontSize = 17.sp,
color = if (isFocused) AuroraActivePlaceholder else AuroraInkTertiary,
color = (if (isFocused) AuroraActivePlaceholder else AuroraInkTertiary).let { it.copy(alpha = it.alpha * inkAlpha) },
)
}
BasicTextField(
value = value,
onValueChange = onValueChange,
modifier = Modifier.fillMaxWidth(),
enabled = enabled,
singleLine = true,
textStyle = LocalTextStyle.current.merge(
TextStyle(
color = if (isFocused) AuroraActiveInk else AuroraInk,
color = (if (isFocused) AuroraActiveInk else AuroraInk).let { it.copy(alpha = it.alpha * inkAlpha) },
fontSize = 17.sp,
),
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ import org.koin.compose.viewmodel.koinViewModel

/**
* Sign-in. Mirrors silo-apple iOS phone `LoginView` (Aurora): wordmark,
* "Step 02 — Sign in" eyebrow + "Welcome back", then a glass card with a
* "Step 02 — Sign in" eyebrow + "Welcome back", then a glass card with
* "Continue as <owner>" first when the server lists a network provider for
* this device (such as Tailscale: no browser, no password), a
* "Sign in with <provider>" button per external provider the server lists
* (OIDC, run in a Custom Tab), "Use a different account" when the server
* takes `prompt=select_account`, Username + Password fields and the cream
Expand Down Expand Up @@ -154,13 +156,23 @@ fun LoginScreen(
Text(text = "Loading sign-in options…", color = AuroraInkTertiary, fontSize = 14.sp)
}
}
state.networkProvider?.let { provider ->
SignInProviderButton(
provider = provider,
label = continueAsLabel(provider),
supportingText = continueViaLabel(provider),
onClick = viewModel::onNetworkSignIn,
busy = state.networkSignInBusy,
enabled = !state.signInBusy,
)
}
state.providers.forEach { provider ->
SignInProviderButton(
provider = provider,
label = signInWithLabel(provider),
onClick = { viewModel.onProviderClick(provider) },
busy = state.providerBusy == provider.id,
enabled = !state.isLoading && state.providerBusy == null,
enabled = !state.signInBusy,
)
}
if (state.offersAccountChoice) {
Expand All @@ -187,11 +199,11 @@ fun LoginScreen(
AuroraGhostButton(label = "Retry", onClick = viewModel::loadOptions)
}
}
if (state.providers.isNotEmpty() && state.showPasswordForm) {
if ((state.providers.isNotEmpty() || state.networkProvider != null) && state.showPasswordForm) {
OrDivider()
}
if (!state.showPasswordForm) {
if (state.options != null && state.providers.isEmpty()) {
if (state.options != null && state.providers.isEmpty() && state.networkProvider == null) {
// Password sign-in is off and the provider can't run in this app.
AuroraErrorLabel("This server doesn't offer a sign-in this app can use. Sign in on the web, or ask the server's admin.")
}
Expand All @@ -213,6 +225,7 @@ fun LoginScreen(
modifier = Modifier.focusRequester(usernameFocus),
placeholder = "yourname",
imeAction = ImeAction.Next,
enabled = !state.signInBusy,
)
AuroraTextField(
label = "Password",
Expand All @@ -227,8 +240,9 @@ fun LoginScreen(
} else {
PasswordVisualTransformation()
},
enabled = !state.signInBusy,
trailing = {
IconButton(onClick = { showPassword = !showPassword }) {
IconButton(onClick = { showPassword = !showPassword }, enabled = !state.signInBusy) {
Icon(
imageVector = if (showPassword) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = if (showPassword) "Hide password" else "Show password",
Expand All @@ -244,6 +258,8 @@ fun LoginScreen(
label = if (state.isLoading) "Signing in…" else "Sign in",
onClick = viewModel::onLoginClick,
isLoading = state.isLoading,
// Any sign-in under way: the view model takes no password until it ends.
enabled = !state.signInBusy,
modifier = Modifier.fillMaxWidth(),
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import org.siloserver.silo.android.auth.NativeSignInProtocol
import org.siloserver.silo.android.auth.NativeSignInPurpose
import org.siloserver.silo.android.auth.NativeSignInResult
import org.siloserver.silo.android.auth.NativeSignInStart
import org.siloserver.silo.model.auth.NetworkSignInFailure
import org.siloserver.silo.model.auth.PasswordLoginFailure
import org.siloserver.silo.model.auth.SignInOptions
import org.siloserver.silo.model.auth.SignInProvider
Expand Down Expand Up @@ -42,6 +43,12 @@ data class LoginUiState(
val optionsUnavailable: Boolean = false,
/** The provider whose browser sign-in is starting or finishing. */
val providerBusy: String? = null,
/**
* "Continue as …" is waiting for the server: the password form and the
* provider buttons wait too. Its own flag, so reloading the options
* can't free them while the request is still out.
*/
val networkSignInBusy: Boolean = false,
/** A start URL for the screen to open in a Custom Tab, once. */
val browserLaunch: String? = null,
/** "Use a different account" with several providers: which one to sign in with. */
Expand All @@ -50,8 +57,14 @@ data class LoginUiState(
val showPasswordForm: Boolean get() = options?.showPasswordForm == true
val providers: List<SignInProvider> get() = options?.oauthProviders.orEmpty()

/** "Continue as <owner>": the network provider the server listed for this device, above everything else. */
val networkProvider: SignInProvider? get() = options?.networkProvider

/** "Use a different account" under the provider buttons, when the server takes `prompt=select_account`. */
val offersAccountChoice: Boolean get() = options?.selectAccount == true && providers.isNotEmpty()

/** A sign-in on this screen is under way, so no other may start. */
val signInBusy: Boolean get() = isLoading || providerBusy != null || networkSignInBusy
}

class LoginViewModel(
Expand Down Expand Up @@ -125,7 +138,7 @@ class LoginViewModel(
}

fun onLoginClick() {
if (_uiState.value.isLoading) return
if (_uiState.value.signInBusy) return
val current = _uiState.value
if (current.username.isBlank()) {
_uiState.update { it.copy(error = "Username is required") }
Expand All @@ -141,9 +154,7 @@ class LoginViewModel(

when (val result = authRepository.login(current.username, current.password)) {
is ApiResult.Success -> {
screenServerId?.let(nativeSignIn::clearAccountChoice)
// A provider flow left open in the browser no longer speaks for this session.
nativeSignIn.discardPending()
onSignedIn()
_uiState.update { it.copy(isLoading = false, loginSuccess = true) }
}

Expand All @@ -169,6 +180,42 @@ class LoginViewModel(
}
}

/** A sign-in on this screen (password or network identity) saved its session. */
private suspend fun onSignedIn() {
screenServerId?.let(nativeSignIn::clearAccountChoice)
// A provider flow left open in the browser no longer speaks for this session.
nativeSignIn.discardPending()
}

/**
* "Continue as <owner>": sign in as whoever the server's network provider
* (such as Tailscale) says owns this device. No browser and no password:
* one POST to the listed path on the saved server base, and the session
* lands exactly like a password sign-in's.
*/
fun onNetworkSignIn() {
val state = _uiState.value
val provider = state.networkProvider ?: return
val path = provider.networkSignInPath ?: return
if (state.signInBusy) return
_uiState.update { it.copy(networkSignInBusy = true, error = null) }
viewModelScope.launch {
val result = authRepository.signInWith { serverUrl -> externalSignIn.signInWithNetworkIdentity(serverUrl, path) }
when (result) {
is ApiResult.Success -> {
onSignedIn()
_uiState.update { it.copy(networkSignInBusy = false, loginSuccess = true) }
}
is ApiResult.Error -> _uiState.update {
it.copy(networkSignInBusy = false, error = networkSignInMessage(result, provider.displayName))
}
is ApiResult.NetworkError -> _uiState.update {
it.copy(networkSignInBusy = false, error = "Network error. Please check your connection.")
}
}
}
}

/**
* "Sign in with <provider>": record a native flow for the active server
* and hand its start URL to the screen. The redirect must name this
Expand All @@ -179,7 +226,7 @@ class LoginViewModel(
*/
fun onProviderClick(provider: SignInProvider, chooseAccount: Boolean = false) {
val startPath = provider.nativeStartPath ?: return
if (_uiState.value.isLoading || _uiState.value.providerBusy != null) return
if (_uiState.value.signInBusy) return
_uiState.update { it.copy(providerBusy = provider.id, error = null, choosingAccountProvider = false) }
viewModelScope.launch {
val entry = serverRegistry.activeEntry.value
Expand Down Expand Up @@ -223,7 +270,7 @@ class LoginViewModel(
*/
fun onUseDifferentAccount() {
val state = _uiState.value
if (!state.offersAccountChoice || state.isLoading || state.providerBusy != null) return
if (!state.offersAccountChoice || state.signInBusy) return
val only = state.providers.singleOrNull()
if (only != null) onProviderClick(only, chooseAccount = true) else _uiState.update { it.copy(choosingAccountProvider = true) }
}
Expand Down Expand Up @@ -312,6 +359,47 @@ internal fun passwordLoginMessage(
PasswordLoginFailure.Other -> error.message.ifBlank { "Login failed" }
}

/**
* Text for a refused network identity sign-in ("Continue as …") through
* [providerName], such as Tailscale. Refusals other operations share read as
* they do there.
*/
internal fun networkSignInMessage(error: ApiResult.Error, providerName: String): String =
when (NetworkSignInFailure.of(error.code, error.error)) {
NetworkSignInFailure.NetworkIdentityRequired -> ProviderRefusalText.addressRequired(providerName, "sign in this way")
NetworkSignInFailure.NotPermitted -> ProviderRefusalText.notPermitted(providerName)
NetworkSignInFailure.EmailInUse ->
"An account with your email already exists. Sign in with your password, then connect $providerName in Settings → Sign-in."
NetworkSignInFailure.AccountRequired -> NativeSignInMessages.forReason(NativeSignInMessages.ACCOUNT_REQUIRED)
NetworkSignInFailure.AccountDisabled -> NativeSignInMessages.forReason("account_disabled")
NetworkSignInFailure.IdentityLinkedElsewhere -> NativeSignInMessages.forReason("identity_linked_elsewhere", providerName)
NetworkSignInFailure.NotFound -> ProviderRefusalText.providerGone(providerName)
NetworkSignInFailure.ProviderUnavailable -> NativeSignInMessages.forReason("provider_unavailable", providerName)
NetworkSignInFailure.RateLimited -> NativeSignInMessages.forReason(NativeSignInMessages.RATE_LIMITED)
NetworkSignInFailure.Other -> when {
// AuthRepository's code for a sign-in whose account or server changed underneath it.
error.error == "identity_changed" -> NativeSignInMessages.forReason(NativeSignInMessages.ACCOUNT_CHANGED)
error.code == 0 && error.error == NativeSignInMessages.UPDATE_REQUIRED ->
NativeSignInMessages.forReason(NativeSignInMessages.UPDATE_REQUIRED)
else -> NativeSignInMessages.forReason("login_failed", providerName)
}
}

/**
* The phone's copy for provider refusals that sign-in ("Continue as …") and
* "Connect <provider>" in Settings share.
*/
internal object ProviderRefusalText {
/** `network_identity_required`: the app reached the server some other way; [toDo] is what needs that address. */
fun addressRequired(providerName: String, toDo: String) = "Open this server at its $providerName address to $toDo."

/** `not_permitted`: a tagged device, or one the provider's policy leaves out. */
fun notPermitted(providerName: String) = "$providerName doesn't allow this device on this server."

/** The provider is no longer enabled on the server (404). */
fun providerGone(providerName: String) = "$providerName is no longer available on this server."
}

internal fun loginServerHostLabel(serverUrl: String): String? {
val trimmed = serverUrl.trim()
if (trimmed.isBlank()) return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
Expand Down Expand Up @@ -39,6 +40,17 @@ import org.siloserver.silo.model.auth.SignInProvider
/** "Sign in with <provider>". */
fun signInWithLabel(provider: SignInProvider): String = "Sign in with ${provider.displayName}"

/**
* A network provider's button: "Continue as <owner>" when the provider named
* who owns this device, "Continue with <provider>" when it named nobody.
*/
fun continueAsLabel(provider: SignInProvider): String =
provider.networkIdentity?.label?.let { "Continue as $it" } ?: "Continue with ${provider.displayName}"

/** The line under "Continue as <owner>" naming the provider; none when the label already names it. */
fun continueViaLabel(provider: SignInProvider): String? =
provider.networkIdentity?.label?.let { "via ${provider.displayName}" }

/**
* The account-choice link under the provider buttons. It picks another
* account at the provider, not another way into Silo, so it names the
Expand All @@ -49,9 +61,10 @@ fun differentAccountLabel(providers: List<SignInProvider>): String =

/**
* One external sign-in provider's button: its icon (SVG or bitmap from the
* plugin, a generic sign-in glyph when it has none or it can't be drawn) and
* [label]. Glass-outlined so the cream password button stays the primary
* action when both are offered.
* plugin, a generic sign-in glyph when it has none or it can't be drawn),
* [label] and, when given, a smaller [supportingText] line under it.
* Glass-outlined so the cream password button stays the primary action when
* both are offered. The button reads as one element, both lines together.
*/
@Composable
fun SignInProviderButton(
Expand All @@ -61,6 +74,7 @@ fun SignInProviderButton(
modifier: Modifier = Modifier,
busy: Boolean = false,
enabled: Boolean = true,
supportingText: String? = null,
) {
val shape = RoundedCornerShape(14.dp)
val active = enabled && !busy
Expand All @@ -86,12 +100,21 @@ fun SignInProviderButton(
} else {
ProviderIcon(provider)
}
Text(
text = label,
color = AuroraInk.copy(alpha = if (active) 1f else 0.6f),
fontWeight = FontWeight.SemiBold,
fontSize = 17.sp,
)
Column {
Text(
text = label,
color = AuroraInk.copy(alpha = if (active) 1f else 0.6f),
fontWeight = FontWeight.SemiBold,
fontSize = 17.sp,
)
if (supportingText != null) {
Text(
text = supportingText,
color = AuroraInk.copy(alpha = if (active) 0.68f else 0.42f),
fontSize = 13.sp,
)
}
}
}
}
}
Expand Down
Loading
Loading