use crate::events::WatchEnd;
use plexus_rpc::core::plexus::{current_reach, AuthContext, PlexusError, Reach, Refusal};
use plexus_rpc::macros::PlexusRequest;
#[derive(PlexusRequest)]
pub struct NotesRequest {
#[from_auth_context]
pub auth: Option<AuthContext>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Callers;
#[derive(Clone, Debug)]
pub struct Caller {
principal: String,
ctx: AuthContext,
reach: Reach,
}
impl Callers {
pub async fn verify(&self, ctx: &AuthContext) -> Result<Caller, PlexusError> {
if !ctx.is_authenticated() {
return Err(PlexusError::Unauthenticated("sign in first".into()));
}
let principal = ctx.principal().map(|p| p.to_string()).ok_or_else(|| PlexusError::Unauthenticated("this identity names no principal".into()))?;
Ok(Caller { principal, ctx: ctx.clone(), reach: current_reach()? })
}
}
impl Caller {
pub fn principal(&self) -> &str {
&self.principal
}
pub fn name(&self) -> String {
["agent", "name"].iter().find_map(|k| self.ctx.get_metadata_string(k).filter(|n| !n.is_empty())).unwrap_or_else(|| self.principal.clone())
}
pub fn agent(&self) -> bool {
self.ctx.get_metadata_string("agent").is_some_and(|a| !a.is_empty())
}
pub fn who(&self) -> crate::presence::Who {
crate::presence::Who { principal: self.principal.clone(), name: self.name(), agent: self.agent() }
}
pub fn context(&self) -> &AuthContext {
&self.ctx
}
pub fn reach(&self) -> &Reach {
&self.reach
}
pub fn expires_at(&self) -> Option<i64> {
self.ctx.metadata.get("expires_at").and_then(|v| v.as_i64())
}
pub fn again(&self) -> Result<(), (WatchEnd, String)> {
if self.expires_at().is_some_and(|at| at <= crate::store::now()) {
return Err((WatchEnd::Expired, "your access changed: your sign-in has expired".into()));
}
match self.reach.recheck() {
Ok(_) => Ok(()),
Err(r) => {
let reason = match &r {
Refusal::Ended { reason } if reason.contains("expired") => WatchEnd::Expired,
Refusal::Ended { .. } => WatchEnd::SignedOut,
Refusal::MissingGrant { .. } => WatchEnd::Revoked,
_ => WatchEnd::Refused,
};
Err((reason, format!("your access changed: {r}")))
}
}
}
}