feat #14740: link to the euvino admin backend

- Settings section "Backend": backend URL, login status checked live
  (logged in as / until, not logged in, backend unreachable), Anmelden /
  Neu anmelden, Abmelden and the link to the key management page
- login window "backend-login": the backend's own login page in an
  incognito webview without any Tauri capability; after a page load
  behind the login, its cookies create a key (one request, never stored
  or logged), the key goes to the keyring, the window closes; closing it
  cancels; one login at a time, later requests wait for the same result
- call detail: "Transkript hochladen" / "Erneut hochladen" (with a
  confirmation), "wird hochgeladen…", "Hochgeladen am … (ID …)" and
  inline errors; logs in first when there is no usable key
- saving a different backend URL discards the key of the old backend

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-06 14:54:38 +01:00
co-authored by Claude Opus 5.5
parent 58e96a2954
commit f045424e97
10 changed files with 990 additions and 29 deletions
+430
View File
@@ -0,0 +1,430 @@
//! Link to the euvino admin backend: the login window that turns the
//! admin's browser session into an API key, the login status for the
//! settings, and the upload of a call's transcript.
//!
//! The login window shows the backend's own login page, a remote origin: it
//! has no Tauri capability (see `capabilities/default.json`), so the page
//! cannot invoke any command. It runs in incognito mode, so the session
//! never outlives the window. After each page load on the backend the app
//! reads the window's cookies for the backend and uses them for the one
//! request that creates a key. Neither the cookies nor the key are ever
//! logged; the key is stored only in the keyring.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use async_trait::async_trait;
use chrono::{DateTime, Local};
use recorder_core::backend::{self, BackendClient, KeyCheck, Login, LoginStep, NewKey};
use recorder_core::model::CallId;
use serde::Serialize;
use tauri::webview::PageLoadEvent;
use tauri::{
AppHandle, Emitter, Manager, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent,
};
use tauri_plugin_opener::OpenerExt;
use tokio::sync::oneshot;
use crate::processing;
use crate::state::AppState;
/// Label of the login window.
pub const LOGIN_WINDOW: &str = "backend-login";
const CANCELLED: &str = "Anmeldung abgebrochen";
type CmdResult<T> = Result<T, String>;
/// A login's outcome: the new key, or the message why there is none.
type LoginResult = Result<String, String>;
/// Everyone waiting for the login that runs in the login window. Only one
/// login runs at a time; later requests wait for the same result.
#[derive(Default)]
pub struct LoginWaiters {
waiters: Mutex<Vec<oneshot::Sender<LoginResult>>>,
/// Set while a key is being created, so page loads in quick succession
/// do not create several.
creating: AtomicBool,
}
impl LoginWaiters {
/// Waits for the login. `true` if no login was running yet, so the
/// caller has to start one.
fn join(&self) -> (oneshot::Receiver<LoginResult>, bool) {
let (tx, rx) = oneshot::channel();
let mut waiters = lock(&self.waiters);
let first = waiters.is_empty();
waiters.push(tx);
(rx, first)
}
/// Whether anyone waits for a login.
fn waiting(&self) -> bool {
!lock(&self.waiters).is_empty()
}
/// Ends the login with `result` for everyone waiting.
fn finish(&self, result: LoginResult) {
for waiter in lock(&self.waiters).drain(..) {
let _ = waiter.send(result.clone());
}
}
/// Claims the right to create a key; `None` while another page load
/// is already creating one.
fn claim_creating(&self) -> Option<CreatingClaim<'_>> {
(!self.creating.swap(true, Ordering::SeqCst)).then_some(CreatingClaim(&self.creating))
}
}
/// Releases [`LoginWaiters::creating`] when dropped.
struct CreatingClaim<'a>(&'a AtomicBool);
impl Drop for CreatingClaim<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}
/// Answer of `backend_status`.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct BackendStatus {
pub logged_in: bool,
pub username: Option<String>,
pub expires_at: Option<DateTime<Local>>,
/// `false` if the stored key could not be checked; username and expiry
/// are then the stored ones.
pub reachable: bool,
/// Where the admin manages their keys.
pub keys_url: String,
}
/// Payload of `backend-login-error`: creating the key failed, the login
/// window stays open for another try.
#[derive(Serialize, Clone)]
struct LoginError {
message: String,
}
/// Whether a backend key is stored, and whose it is: checked with the
/// backend. A key the backend refuses is discarded.
#[tauri::command]
pub async fn backend_status(app: AppHandle) -> CmdResult<BackendStatus> {
let state = app.state::<AppState>();
let client = state.backend_client();
let stored = blocking(&app, |state| Ok(state.backend_key())).await?;
let mut status = BackendStatus {
logged_in: false,
username: None,
expires_at: None,
reachable: true,
keys_url: client.keys_page_url(),
};
let Some(stored) = stored else {
return Ok(status);
};
match client.check_key(&stored.key).await {
KeyCheck::Valid(info) => {
state.refresh_backend_login(&info)?;
status.logged_in = true;
status.username = Some(info.username);
status.expires_at = Some(info.expires_at);
}
KeyCheck::Invalid => {
log::info!("backend: the stored key was refused, discarding it");
blocking(&app, |state| state.discard_backend_key()).await?;
}
KeyCheck::Unknown(e) => {
log::info!(
"backend: could not check the stored key: {}",
e.user_message()
);
let settings = state.settings();
status.logged_in = true;
status.username = settings.backend_username;
status.expires_at = settings.backend_key_expires_at;
status.reachable = false;
}
}
Ok(status)
}
/// "Anmelden": runs the login in the login window (a new key replaces the
/// stored one).
#[tauri::command]
pub async fn backend_login(app: AppHandle) -> CmdResult<()> {
login(&app).await.map(|_key| ())
}
/// "Abmelden": forgets the key locally (it stays valid on the server until
/// the admin deletes it there or it expires).
#[tauri::command]
pub async fn backend_logout(app: AppHandle) -> CmdResult<()> {
blocking(&app, |state| state.discard_backend_key()).await?;
emit_changed(&app);
Ok(())
}
/// Opens the backend's key management page in the system browser.
#[tauri::command]
pub fn open_backend_keys_page(app: AppHandle) -> CmdResult<()> {
let url = app.state::<AppState>().backend_client().keys_page_url();
app.opener()
.open_url(url, None::<&str>)
.map_err(|e| format!("Browser konnte nicht geöffnet werden: {e}"))
}
/// "Transkript hochladen": uploads the call's transcript as the user sees
/// it, logging in first if needed, and records the CRM's id on the call.
#[tauri::command]
pub async fn upload_transcript(app: AppHandle, id: CallId) -> CmdResult<()> {
let state = app.state::<AppState>();
let detail = state.call_detail(id)?;
if detail.call.transcribed_at.is_none() {
return Err("Das Gespräch ist noch nicht transkribiert".to_string());
}
let text = detail.upload_text()?;
let client = state.backend_client();
let stored = blocking(&app, |state| Ok(state.backend_key())).await?;
let login = AppLogin { app: app.clone() };
let crm_id = backend::upload_with_login(&client, &login, stored, Local::now(), &text)
.await
.inspect_err(|e| log::warn!("call {id}: upload failed: {e}"))?;
log::info!("call {id}: transcript uploaded (CRM id {crm_id})");
state.mark_uploaded(id, &crm_id)?;
processing::emit_updated(&app, id);
Ok(())
}
/// [`Login`] through the login window, for the upload.
struct AppLogin {
app: AppHandle,
}
#[async_trait]
impl Login for AppLogin {
async fn login(&self) -> Result<String, String> {
login(&self.app).await
}
async fn discard_key(&self) {
log::info!("backend: the key was refused, discarding it");
if let Err(e) = blocking(&self.app, |state| state.discard_backend_key()).await {
log::error!("backend: {e}");
}
emit_changed(&self.app);
}
}
/// Runs the login in the login window, or waits for the one already
/// running (and brings its window to the front). Returns the new key,
/// already stored.
pub async fn login(app: &AppHandle) -> LoginResult {
let waiters = app.state::<LoginWaiters>();
let (result, first) = waiters.join();
match app.get_webview_window(LOGIN_WINDOW) {
Some(window) => {
let _ = window.unminimize();
let _ = window.set_focus();
}
None if first => {
if let Err(e) = open_login_window(app) {
log::error!("backend: could not open the login window: {e}");
waiters.finish(Err(format!(
"Anmeldefenster konnte nicht geöffnet werden: {e}"
)));
}
}
None => {}
}
result.await.unwrap_or_else(|_| Err(CANCELLED.to_string()))
}
fn open_login_window(app: &AppHandle) -> tauri::Result<()> {
let client = app.state::<AppState>().backend_client();
let url = Url::parse(&client.login_url()).map_err(tauri::Error::InvalidUrl)?;
let window = WebviewWindowBuilder::new(app, LOGIN_WINDOW, WebviewUrl::External(url))
.title("Anmeldung euvino Admin")
.inner_size(1000.0, 760.0)
.incognito(true)
.on_page_load(move |window, payload| {
if payload.event() == PageLoadEvent::Finished
&& client.is_logged_in_page(payload.url().as_str())
{
create_key(window, client.clone());
}
})
.build()?;
let app = app.clone();
window.on_window_event(move |event| {
if let WindowEvent::Destroyed = event {
// Closed by the user: the login is cancelled. After a
// finished login nobody waits any more.
app.state::<LoginWaiters>()
.finish(Err(CANCELLED.to_string()));
}
});
Ok(())
}
/// The login window shows a backend page behind the login: creates a key
/// with the window's session, in the background. `client` is the backend
/// the window was opened for.
fn create_key(window: WebviewWindow, client: BackendClient) {
tauri::async_runtime::spawn(async move {
let app = window.app_handle().clone();
let waiters = app.state::<LoginWaiters>();
if !waiters.waiting() {
return;
}
let Some(_claim) = waiters.claim_creating() else {
return;
};
match try_create_key(&client, &window).await {
LoginStep::Done(key) => {
let result = store_key(&app, &client, &key).await.map(|()| key.key);
waiters.finish(result);
emit_changed(&app);
let _ = window.destroy();
}
LoginStep::Wait => {}
LoginStep::Fail(message) => {
log::warn!("backend: the login cannot create a key: {message}");
waiters.finish(Err(message));
let _ = window.destroy();
}
LoginStep::Retry(message) => {
log::warn!("backend: creating the key failed: {message}");
let _ = app.emit_to("main", "backend-login-error", LoginError { message });
}
}
});
}
/// Creates a key with the cookies the login window holds for the backend.
/// The cookies are used for this one request and dropped.
async fn try_create_key(client: &BackendClient, window: &WebviewWindow) -> LoginStep {
let Ok(url) = Url::parse(&client.keys_page_url()) else {
return LoginStep::Wait;
};
// Off the async runtime: on Windows reading cookies blocks until the
// main thread answers.
let reader = window.clone();
let cookies = tauri::async_runtime::spawn_blocking(move || reader.cookies_for_url(url)).await;
let cookies = match cookies {
Ok(Ok(cookies)) => cookies,
Ok(Err(e)) => return LoginStep::Retry(format!("Anmeldedaten nicht lesbar: {e}")),
Err(e) => return LoginStep::Retry(format!("Anmeldedaten nicht lesbar: {e}")),
};
if cookies.is_empty() {
return LoginStep::Wait;
}
let cookie_header = cookies
.iter()
.map(|cookie| format!("{}={}", cookie.name(), cookie.value()))
.collect::<Vec<_>>()
.join("; ");
let label = backend::key_label(hostname().as_deref());
LoginStep::of(client.create_key(&cookie_header, &label).await)
}
/// Stores a new key with whose it is (asked from the backend; left empty if
/// that fails) and its expiry.
async fn store_key(app: &AppHandle, client: &BackendClient, key: &NewKey) -> Result<(), String> {
let username = match client.key_info(&key.key).await {
Ok(info) => Some(info.username),
Err(e) => {
log::warn!(
"backend: could not ask whose the new key is: {}",
e.user_message()
);
None
}
};
let key = key.clone();
blocking(app, move |state| state.store_backend_key(&key, username)).await?;
log::info!("backend: logged in, key stored");
Ok(())
}
/// The computer's name, for the key's label.
fn hostname() -> Option<String> {
std::env::var("COMPUTERNAME")
.ok()
.or_else(|| std::fs::read_to_string("/etc/hostname").ok())
.or_else(|| std::env::var("HOSTNAME").ok())
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty())
}
/// Tells the settings that the login changed (`backend-changed`).
fn emit_changed(app: &AppHandle) {
if let Err(e) = app.emit_to("main", "backend-changed", ()) {
log::error!("could not emit backend-changed: {e}");
}
}
/// Runs `f` with the app state on the blocking pool (keyring access).
async fn blocking<T, F>(app: &AppHandle, f: F) -> CmdResult<T>
where
T: Send + 'static,
F: FnOnce(&AppState) -> CmdResult<T> + Send + 'static,
{
let app = app.clone();
tauri::async_runtime::spawn_blocking(move || f(&app.state::<AppState>()))
.await
.map_err(|e| e.to_string())?
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn everyone_waiting_gets_the_one_login_result() {
let waiters = LoginWaiters::default();
assert!(!waiters.waiting());
let (first, starts) = waiters.join();
let (second, starts_again) = waiters.join();
assert!(starts);
assert!(!starts_again);
assert!(waiters.waiting());
waiters.finish(Ok("euv_k".into()));
assert_eq!(first.blocking_recv().unwrap(), Ok("euv_k".to_string()));
assert_eq!(second.blocking_recv().unwrap(), Ok("euv_k".to_string()));
assert!(!waiters.waiting());
}
#[test]
fn a_finished_login_leaves_the_next_one_to_start_anew() {
let waiters = LoginWaiters::default();
let (first, _) = waiters.join();
waiters.finish(Err(CANCELLED.into()));
// A late "window destroyed" reaches nobody.
waiters.finish(Err("ignored".into()));
assert_eq!(first.blocking_recv().unwrap(), Err(CANCELLED.to_string()));
let (next, starts) = waiters.join();
assert!(starts);
waiters.finish(Ok("euv_new".into()));
assert_eq!(next.blocking_recv().unwrap(), Ok("euv_new".to_string()));
}
#[test]
fn only_one_key_is_created_at_a_time() {
let waiters = LoginWaiters::default();
let claim = waiters.claim_creating();
assert!(claim.is_some());
assert!(waiters.claim_creating().is_none());
drop(claim);
assert!(waiters.claim_creating().is_some());
}
}
+16 -9
View File
@@ -37,16 +37,23 @@ pub fn get_settings(state: State<'_, AppState>) -> Settings {
state.settings()
}
/// Saves the settings. A changed backend URL ends the backend login
/// (`backend-changed`). May delete from the keyring, so it runs on the
/// blocking pool.
#[tauri::command]
pub fn save_settings(
app: AppHandle,
state: State<'_, AppState>,
settings: Settings,
) -> CmdResult<()> {
let autostart = settings.autostart;
state.save_settings(settings)?;
apply_autostart(&app, autostart);
Ok(())
pub async fn save_settings(app: AppHandle, settings: Settings) -> CmdResult<()> {
blocking(app, move |app| {
let autostart = settings.autostart;
let backend_changed = app.state::<AppState>().save_settings(settings)?;
apply_autostart(app, autostart);
if backend_changed {
if let Err(e) = app.emit_to("main", "backend-changed", ()) {
log::error!("could not emit backend-changed: {e}");
}
}
Ok(())
})
.await
}
/// Stores `key` in the keyring; an empty key deletes the entry.
+16 -3
View File
@@ -1,3 +1,4 @@
mod backend;
mod commands;
mod detection;
mod processing;
@@ -34,6 +35,9 @@ pub fn run() {
))
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_updater::Builder::new().build())
// Only for `open_backend_keys_page`: no capability grants the UI
// the plugin's commands.
.plugin(tauri_plugin_opener::init())
.setup(|app| {
// Release builds log to a file in the app log directory (on
// Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug
@@ -89,6 +93,7 @@ pub fn run() {
processing::clear_upload_dir(app.handle());
app.manage(state);
app.manage(PendingUpdate::default());
app.manage(backend::LoginWaiters::default());
// Windows are created here (`create: false` in tauri.conf.json)
// instead of by Tauri before `setup` runs: their webviews load
// immediately and invoke commands (list_calls, get_recording_state,
@@ -110,10 +115,13 @@ pub fn run() {
})
.on_window_event(|window, event| {
// Closing a window only hides it; the app keeps running in the
// tray (for call detection) until "Beenden".
// tray (for call detection) until "Beenden". The login window
// really closes: that cancels the login.
if let WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
if window.label() != backend::LOGIN_WINDOW {
api.prevent_close();
let _ = window.hide();
}
}
})
.invoke_handler(tauri::generate_handler![
@@ -139,6 +147,11 @@ pub fn run() {
commands::merge_speakers,
commands::unmerge_speaker,
commands::rename_call,
backend::backend_status,
backend::backend_login,
backend::backend_logout,
backend::open_backend_keys_page,
backend::upload_transcript,
updater::get_update,
updater::install_update,
])
+218 -11
View File
@@ -17,13 +17,14 @@ use std::time::{Duration, Instant};
use chrono::{DateTime, Local};
use recorder_audio::RenderSession;
use recorder_core::backend::{BackendClient, KeyInfo, NewKey, StoredKey};
use recorder_core::call_view::{self, CallDetail, CallListItem};
use recorder_core::capture::{CaptureSource, OutputTarget};
use recorder_core::detect::{CallDetector, DetectorEvent, MicSession};
use recorder_core::http::{HttpTransport, ReqwestTransport};
use recorder_core::model::{Call, CallId, CallStatus, Speaker};
use recorder_core::recorder::Recorder;
use recorder_core::secrets::SecretStore;
use recorder_core::secrets::{SecretStore, Service};
use recorder_core::settings::Settings;
use recorder_core::store::Store;
use serde::Serialize;
@@ -195,15 +196,85 @@ impl AppState {
lock(&self.settings).clone()
}
/// Validates, saves and applies the settings; the detector picks up the
/// new allowlist and delays immediately.
pub fn save_settings(&self, settings: Settings) -> Result<(), String> {
settings.validate()?;
settings
.save(&self.settings_path)
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))?;
/// Validates, saves and applies the settings the user edited; the
/// detector picks up the new allowlist and delays immediately. The
/// backend login is kept, unless the backend URL changed: then its key
/// is discarded (it belongs to the old backend) and `true` returned.
/// Deletes from the keyring, so call it off the UI thread.
pub fn save_settings(&self, edited: Settings) -> Result<bool, String> {
let mut current = lock(&self.settings);
let (settings, backend_changed) = current.edited(edited)?;
if backend_changed {
self.secrets
.delete(Service::Backend)
.map_err(|e| format!("Backend-Schlüssel konnte nicht entfernt werden: {e}"))?;
}
save(&settings, &self.settings_path)?;
lock(&self.detector).set_config(detector_config(&settings));
*lock(&self.settings) = settings;
*current = settings;
Ok(backend_changed)
}
/// Client of the configured backend.
pub fn backend_client(&self) -> BackendClient {
BackendClient::new(self.transport.clone(), &self.settings().backend_url)
}
/// The stored backend key with its expiry. Reads the keyring, so call
/// it off the UI thread.
pub fn backend_key(&self) -> Option<StoredKey> {
let key = self
.secrets
.get(Service::Backend)
.filter(|key| !key.trim().is_empty())?;
Some(StoredKey {
key,
expires_at: self.settings().backend_key_expires_at,
})
}
/// Stores a key the login created (in the keyring) and whose it is and
/// when it expires (in the settings).
pub fn store_backend_key(&self, key: &NewKey, username: Option<String>) -> Result<(), String> {
self.secrets
.set(Service::Backend, &key.key)
.map_err(|e| format!("Backend-Schlüssel konnte nicht gespeichert werden: {e}"))?;
self.update_settings(|s| {
s.backend_username = username;
s.backend_key_expires_at = Some(key.expires_at);
})
}
/// Takes over whose the stored key is and when it expires, as the
/// backend reports it.
pub fn refresh_backend_login(&self, info: &KeyInfo) -> Result<(), String> {
self.update_settings(|s| {
s.backend_username = Some(info.username.clone());
s.backend_key_expires_at = Some(info.expires_at);
})
}
/// Forgets the backend key (keyring) and its login (settings).
pub fn discard_backend_key(&self) -> Result<(), String> {
self.secrets
.delete(Service::Backend)
.map_err(|e| format!("Backend-Schlüssel konnte nicht entfernt werden: {e}"))?;
self.update_settings(|s| {
s.backend_username = None;
s.backend_key_expires_at = None;
})
}
/// Changes and saves settings the app manages itself; saves only if
/// something changed.
fn update_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), String> {
let mut current = lock(&self.settings);
let mut settings = current.clone();
change(&mut settings);
if settings != *current {
save(&settings, &self.settings_path)?;
*current = settings;
}
Ok(())
}
@@ -495,6 +566,15 @@ impl AppState {
self.store.set_title(id, title).map_err(|e| e.to_string())
}
/// Records that call `id`'s transcript was just uploaded and the CRM
/// gave it `crm_transcript_id`.
pub fn mark_uploaded(&self, id: CallId, crm_transcript_id: &str) -> Result<(), String> {
self.find_call(id)?;
self.store
.set_uploaded(id, crm_transcript_id, Local::now())
.map_err(|e| format!("Upload konnte nicht vermerkt werden: {e}"))
}
fn find_call(&self, id: CallId) -> Result<Call, String> {
self.store
.get_call(id)
@@ -696,6 +776,12 @@ fn detected_output_target(
}
}
fn save(settings: &Settings, path: &Path) -> Result<(), String> {
settings
.save(path)
.map_err(|e| format!("Einstellungen konnten nicht gespeichert werden: {e}"))
}
fn output_target(settings: &Settings) -> OutputTarget {
match &settings.output_device {
Some(id) => OutputTarget::Device(id.clone()),
@@ -713,8 +799,9 @@ fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use recorder_core::backend::{KeyInfo, NewKey, StoredKey};
use recorder_core::model::{Segment, Speaker};
use recorder_core::secrets::MemorySecrets;
use recorder_core::secrets::{MemorySecrets, Service};
use super::*;
@@ -1250,10 +1337,130 @@ mod tests {
end_after_secs: 30,
..Settings::default()
};
assert_eq!(f.state.save_settings(valid.clone()), Ok(()));
assert_eq!(f.state.save_settings(valid.clone()), Ok(false));
assert_eq!(f.state.settings(), valid);
}
fn new_key(key: &str) -> NewKey {
NewKey {
key: key.into(),
expires_at: Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap(),
}
}
#[test]
fn a_stored_backend_key_comes_with_its_login() {
let f = fixture();
assert_eq!(f.state.backend_key(), None);
f.state
.store_backend_key(&new_key("euv_k"), Some("hinrichs".into()))
.unwrap();
let expires_at = Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap();
assert_eq!(
f.state.backend_key(),
Some(StoredKey {
key: "euv_k".into(),
expires_at: Some(expires_at),
})
);
let saved = Settings::load(&f.dir.path().join("settings.json"));
assert_eq!(saved.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(saved.backend_key_expires_at, Some(expires_at));
assert!(!fs::read_to_string(f.dir.path().join("settings.json"))
.unwrap()
.contains("euv_k"));
assert_eq!(f.state.settings(), saved);
}
#[test]
fn the_backend_login_is_refreshed_from_the_key_info() {
let f = fixture();
f.state.store_backend_key(&new_key("euv_k"), None).unwrap();
let later = Local.with_ymd_and_hms(2028, 1, 1, 0, 0, 0).unwrap();
f.state
.refresh_backend_login(&KeyInfo {
label: "l".into(),
hint: "h".into(),
username: "hinrichs".into(),
created_at: later,
expires_at: later,
})
.unwrap();
let settings = f.state.settings();
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(settings.backend_key_expires_at, Some(later));
}
#[test]
fn a_discarded_backend_key_is_gone_with_its_login() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), Some("hinrichs".into()))
.unwrap();
f.state.discard_backend_key().unwrap();
assert_eq!(f.state.backend_key(), None);
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_expires_at, None);
}
#[test]
fn saving_settings_keeps_the_backend_login_unless_the_url_changes() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), Some("hinrichs".into()))
.unwrap();
// The settings page sends what it loaded, maybe before the login.
let edited = Settings {
retention_days: 14,
..Settings::default()
};
assert_eq!(f.state.save_settings(edited.clone()), Ok(false));
assert!(f.state.backend_key().is_some());
assert_eq!(
f.state.settings().backend_username.as_deref(),
Some("hinrichs")
);
assert_eq!(f.state.settings().retention_days, 14);
let other_backend = Settings {
backend_url: "https://other.example/".into(),
..edited
};
assert_eq!(f.state.save_settings(other_backend), Ok(true));
assert_eq!(f.state.backend_key(), None);
assert_eq!(f.state.settings().backend_url, "https://other.example");
assert_eq!(f.state.settings().backend_username, None);
assert_eq!(
f.state.backend_client().login_url(),
"https://other.example/euvadm"
);
}
#[test]
fn an_upload_is_recorded_on_the_call() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.mark_uploaded(id, "4711").unwrap();
let call = f.state.store.get_call(id).unwrap().unwrap();
assert_eq!(call.crm_transcript_id.as_deref(), Some("4711"));
assert!(call.uploaded_at.is_some());
assert_eq!(
f.state.mark_uploaded(id + 1, "1"),
Err("Gespräch nicht gefunden".to_string())
);
}
fn render_session(exe: &str, root_pid: u32, device: &str) -> RenderSession {
RenderSession {
exe: exe.to_string(),