Skip to main content

orca/models/
auth_only.rs

1use crate::model::{self, ActorModel, Transition, TransitionAction, TransitionResult};
2
3use crate::{error::Error, run::EventRecord, state::*};
4use kanidm_client::KanidmClient;
5
6use async_trait::async_trait;
7
8use std::time::Duration;
9
10enum State {
11    Unauthenticated,
12    Authenticated,
13}
14
15pub struct ActorAuthOnly {
16    state: State,
17}
18
19impl ActorAuthOnly {
20    pub fn new() -> Self {
21        ActorAuthOnly {
22            state: State::Unauthenticated,
23        }
24    }
25}
26
27#[async_trait]
28impl ActorModel for ActorAuthOnly {
29    async fn transition(
30        &mut self,
31        client: &KanidmClient,
32        person: &Person,
33    ) -> Result<Vec<EventRecord>, Error> {
34        let transition = self.next_transition();
35
36        if let Some(delay) = transition.delay {
37            tokio::time::sleep(delay).await;
38        }
39
40        // Once we get to here, we want the transition to go ahead.
41        let (result, event) = match transition.action {
42            TransitionAction::Login => model::login(client, person).await,
43            TransitionAction::Logout => model::logout(client, person).await,
44            _ => Err(Error::InvalidState),
45        }?;
46
47        self.next_state(transition.action, result);
48
49        Ok(event)
50    }
51}
52
53impl ActorAuthOnly {
54    fn next_transition(&mut self) -> Transition {
55        match self.state {
56            State::Unauthenticated => Transition {
57                delay: None,
58                action: TransitionAction::Login,
59            },
60            State::Authenticated => Transition {
61                delay: Some(Duration::from_millis(100)),
62                action: TransitionAction::Logout,
63            },
64        }
65    }
66
67    fn next_state(&mut self, action: TransitionAction, result: TransitionResult) {
68        match (&self.state, action, result) {
69            (State::Unauthenticated, TransitionAction::Login, TransitionResult::Ok) => {
70                self.state = State::Authenticated;
71            }
72            (State::Authenticated, TransitionAction::Logout, TransitionResult::Ok) => {
73                self.state = State::Unauthenticated;
74            }
75            // Shouldn't be reachable?
76            #[allow(clippy::unreachable)]
77            (_, _, TransitionResult::Ok) => {
78                unreachable!();
79            }
80            (_, _, TransitionResult::Error) => {
81                self.state = State::Unauthenticated;
82            }
83        }
84    }
85}