1use crate::events::WatchEnd;
11use plexus_rpc::core::plexus::{current_reach, AuthContext, PlexusError, Reach, Refusal};
12use plexus_rpc::macros::PlexusRequest;
13
14#[derive(PlexusRequest)]
17pub struct NotesRequest {
18 #[from_auth_context]
20 pub auth: Option<AuthContext>,
21}
22
23#[derive(Clone, Copy, Debug, Default)]
25pub struct Callers;
26
27#[derive(Clone, Debug)]
30pub struct Caller {
31 principal: String,
32 ctx: AuthContext,
33 reach: Reach,
34}
35
36impl Callers {
37 pub async fn verify(&self, ctx: &AuthContext) -> Result<Caller, PlexusError> {
40 if !ctx.is_authenticated() {
41 return Err(PlexusError::Unauthenticated("sign in first".into()));
42 }
43 let principal = ctx.principal().map(|p| p.to_string()).ok_or_else(|| PlexusError::Unauthenticated("this identity names no principal".into()))?;
44 Ok(Caller { principal, ctx: ctx.clone(), reach: current_reach()? })
45 }
46}
47
48impl Caller {
49 pub fn principal(&self) -> &str {
51 &self.principal
52 }
53
54 pub fn name(&self) -> String {
57 ["agent", "name"].iter().find_map(|k| self.ctx.get_metadata_string(k).filter(|n| !n.is_empty())).unwrap_or_else(|| self.principal.clone())
58 }
59
60 pub fn agent(&self) -> bool {
62 self.ctx.get_metadata_string("agent").is_some_and(|a| !a.is_empty())
63 }
64
65 pub fn who(&self) -> crate::presence::Who {
67 crate::presence::Who { principal: self.principal.clone(), name: self.name(), agent: self.agent() }
68 }
69
70 pub fn context(&self) -> &AuthContext {
72 &self.ctx
73 }
74
75 pub fn reach(&self) -> &Reach {
77 &self.reach
78 }
79
80 pub fn expires_at(&self) -> Option<i64> {
82 self.ctx.metadata.get("expires_at").and_then(|v| v.as_i64())
83 }
84
85 pub fn again(&self) -> Result<(), (WatchEnd, String)> {
88 if self.expires_at().is_some_and(|at| at <= crate::store::now()) {
89 return Err((WatchEnd::Expired, "your access changed: your sign-in has expired".into()));
90 }
91 match self.reach.recheck() {
92 Ok(_) => Ok(()),
93 Err(r) => {
94 let reason = match &r {
95 Refusal::Ended { reason } if reason.contains("expired") => WatchEnd::Expired,
96 Refusal::Ended { .. } => WatchEnd::SignedOut,
97 Refusal::MissingGrant { .. } => WatchEnd::Revoked,
98 _ => WatchEnd::Refused,
99 };
100 Err((reason, format!("your access changed: {r}")))
101 }
102 }
103 }
104}