Skip to main content

Context

Struct Context 

Source
pub struct Context { /* private fields */ }
Expand description

Holds platform-specific contextual state required to display an authentication prompt.

Implementations§

Source§

impl Context

Source

pub fn new(raw: RawContext) -> Self

Creates a new context from the given “raw” context.

Examples found in repository?
examples/simple_authentication.rs (line 53)
52fn main() {
53    let context = Context::new(());
54    let mut policy = PolicyBuilder::new()
55        // On Linux You need to set action_ids.
56        // See: ./org.robius.authentication.policy file settings and (README: "Usage on Linux").
57        .action_ids([
58            "org.robius.authentication",
59            "org.robius.authentication.settings",
60        ])
61        .biometrics(Some(BiometricStrength::Strong))
62        .password(true)
63        .companion(true)
64        .build()
65        .unwrap();
66
67    if let Err(e) = policy.set_action_id("org.robius.authentication.settings") {
68        eprintln!("Invalid action_id: {:?}", e);
69        return;
70    }
71
72    let (tx, rx) = mpsc::channel();
73
74    // Start authentication. `res` only indicates whether the request was successfully
75    // initiated; the final result is delivered via the callback.
76    let res = context.authenticate(TEXT, &policy, move |result| {
77        let _ = tx.send(result);
78    });
79
80    if let Err(e) = res {
81        eprintln!("Failed to start authentication: {:?}", e);
82        return;
83    }
84
85    // Block until the callback produces a result.
86    match rx.recv() {
87        Ok(Ok(_)) => println!("Authentication successful"),
88        Ok(Err(e)) => println!("Authentication failed: {:?}", e),
89        Err(e) => eprintln!("Failed to receive auth result: {:?}", e),
90    }
91}
Source

pub fn authenticate<F>( &self, message: Text<'_, '_, '_, '_, '_, '_>, policy: &Policy, callback: F, ) -> Result<()>
where F: Fn(Result<()>) + Send + 'static,

Displays an authentication prompt using the provided policy and message.

Note that the returned Result does not indicate whether authentication was successful. This function returns Ok(()) to indicate that the authentication request was successfully initiated (i.e., the prompt was or will be shown), not that the user successfully authenticated. On some platforms (Android, Linux, Windows) the prompt is shown asynchronously after this function has already returned.

For that purpose, the given callback will be called with a Result indicating whether authentication succeeded. If this function returns an error, the callback may never be invoked; if it returns Ok(()), the callback will eventually be invoked with the result of the authentication attempt.

On Linux: message is unused because polkit looks up the prompt text from the action definition in the installed .policy file (its <message>/<description>). The client only supplies an action ID to CheckAuthorization, and there is no stable, cross-agent way to override that UI text at runtime. If you need multiple prompt strings, define multiple actions in the policy file and select the desired one via PolicyBuilder::action_ids and Policy::set_action_id before each authentication.

Thus, authentication failed if this function returns an error OR if the callback is invoked with Err(_).

Examples found in repository?
examples/simple_authentication.rs (lines 76-78)
52fn main() {
53    let context = Context::new(());
54    let mut policy = PolicyBuilder::new()
55        // On Linux You need to set action_ids.
56        // See: ./org.robius.authentication.policy file settings and (README: "Usage on Linux").
57        .action_ids([
58            "org.robius.authentication",
59            "org.robius.authentication.settings",
60        ])
61        .biometrics(Some(BiometricStrength::Strong))
62        .password(true)
63        .companion(true)
64        .build()
65        .unwrap();
66
67    if let Err(e) = policy.set_action_id("org.robius.authentication.settings") {
68        eprintln!("Invalid action_id: {:?}", e);
69        return;
70    }
71
72    let (tx, rx) = mpsc::channel();
73
74    // Start authentication. `res` only indicates whether the request was successfully
75    // initiated; the final result is delivered via the callback.
76    let res = context.authenticate(TEXT, &policy, move |result| {
77        let _ = tx.send(result);
78    });
79
80    if let Err(e) = res {
81        eprintln!("Failed to start authentication: {:?}", e);
82        return;
83    }
84
85    // Block until the callback produces a result.
86    match rx.recv() {
87        Ok(Ok(_)) => println!("Authentication successful"),
88        Ok(Err(e)) => println!("Authentication failed: {:?}", e),
89        Err(e) => eprintln!("Failed to receive auth result: {:?}", e),
90    }
91}

Trait Implementations§

Source§

impl Debug for Context

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more