BasicOIDC/src/actors/openid_sessions_actor.rs

103 lines
2.7 KiB
Rust
Raw Normal View History

2022-04-09 10:18:59 +00:00
use actix::{Actor, AsyncContext, Context, Handler};
use actix::Message;
use crate::constants::*;
use crate::data::client::ClientID;
use crate::data::user::UserID;
use crate::utils::time::time;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub struct SessionID(pub String);
#[derive(Clone, Debug)]
pub struct Session {
pub session_id: SessionID,
pub client: ClientID,
pub user: UserID,
pub redirect_uri: String,
pub authorization_code: String,
2022-04-12 18:40:44 +00:00
pub authorization_code_expire_at: u64,
pub authorization_code_used: bool,
2022-04-09 10:18:59 +00:00
2022-04-12 18:40:44 +00:00
pub access_token: String,
pub access_token_expire_at: u64,
pub refresh_token: String,
pub refresh_token_expire_at: u64,
2022-04-09 10:18:59 +00:00
pub nonce: Option<String>,
pub code_challenge: Option<(String, String)>,
}
impl Session {
pub fn is_expired(&self) -> bool {
2022-04-12 18:40:44 +00:00
self.authorization_code_expire_at < time() && self.access_token_expire_at < time()
&& self.refresh_token_expire_at < time()
2022-04-09 10:18:59 +00:00
}
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct PushNewSession(pub Session);
2022-04-12 18:40:44 +00:00
#[derive(Message)]
#[rtype(result = "Option<Session>")]
pub struct FindSessionByAuthorizationCode(pub String);
#[derive(Message)]
#[rtype(result = "()")]
pub struct MarkAuthorizationCodeUsed(pub String);
2022-04-09 10:25:56 +00:00
#[derive(Default)]
2022-04-09 10:18:59 +00:00
pub struct OpenIDSessionsActor {
session: Vec<Session>,
}
impl OpenIDSessionsActor {
pub fn clean_old_sessions(&mut self) {
self.session.retain(|s| !s.is_expired());
}
}
impl Actor for OpenIDSessionsActor {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
// Clean up at a regular interval failed attempts
ctx.run_interval(OPEN_ID_SESSION_CLEANUP_INTERVAL, |act, _ctx| {
log::trace!("Cleaning up old login sessions");
act.clean_old_sessions();
});
}
}
impl Handler<PushNewSession> for OpenIDSessionsActor {
type Result = ();
fn handle(&mut self, msg: PushNewSession, _ctx: &mut Self::Context) -> Self::Result {
self.session.push(msg.0)
}
2022-04-12 18:40:44 +00:00
}
impl Handler<FindSessionByAuthorizationCode> for OpenIDSessionsActor {
type Result = Option<Session>;
fn handle(&mut self, msg: FindSessionByAuthorizationCode, _ctx: &mut Self::Context) -> Self::Result {
self.session
.iter()
.find(|f| f.authorization_code.eq(&msg.0))
.cloned()
}
}
impl Handler<MarkAuthorizationCodeUsed> for OpenIDSessionsActor {
type Result = ();
fn handle(&mut self, msg: MarkAuthorizationCodeUsed, _ctx: &mut Self::Context) -> Self::Result {
if let Some(r) = self.session
.iter_mut()
.find(|f| f.authorization_code.eq(&msg.0)) {
r.authorization_code_used = true;
}
}
2022-04-09 10:18:59 +00:00
}