Skip to main content

qr_login/support/
mod.rs

1//! Shared ephemeral login for the network examples. Never serialize credentials.
2use anyhow::{bail, ensure, Result};
3use std::{
4    io::Write,
5    thread,
6    time::{Duration, Instant},
7};
8use wechat_protocol::{
9    is_retryable_login_poll_error, DeviceProfile, LoginStatus, NativeClient, NativeOptions,
10};
11
12pub fn login() -> Result<NativeClient> {
13    let client = NativeClient::new(NativeOptions::default())?;
14    let device = DeviceProfile::generate("UnifiedPCLinux x86_64".into())?;
15    let qr_directory = wechat_platform::private_tempdir("wechat-protocol-example-")?;
16    let qr_path = qr_directory.path().join("login.png");
17    let mut attempt = client.start_qr_login(device, "Rust protocol example")?;
18    let mut qr = wechat_platform::OpenOptions::new()
19        .write(true)
20        .create_new(true)
21        .mode(0o600)
22        .open(&qr_path)?;
23    qr.write_all(&attempt.qr_png)?;
24    drop(qr);
25    eprintln!("Scan the private QR image: {}", qr_path.display());
26    eprintln!("Approve this example on the test account's phone.");
27    let deadline = Instant::now() + Duration::from_secs(600);
28    loop {
29        ensure!(Instant::now() < deadline, "Login example timed out");
30        match client.poll_login_guarded(&mut attempt, deadline, || false) {
31            Ok(LoginStatus::Approved) => {
32                let state = client.complete_login(&mut attempt)?;
33                eprintln!("Login complete; credentials remain in memory.");
34                return NativeClient::from_account(state, NativeOptions::default());
35            }
36            Ok(LoginStatus::Pending | LoginStatus::Scanned) => {}
37            Ok(status) => bail!("Login stopped: {status:?}"),
38            Err(error) if is_retryable_login_poll_error(&error) => {}
39            Err(error) => return Err(error),
40        }
41        // Only polling an already issued challenge is repeated. QR creation,
42        // credential exchange and sends are never automatically resubmitted.
43        thread::sleep(Duration::from_secs(2));
44    }
45}