authnz_common/types/tokens/
triple.rs1#[cfg(any(feature = "app-server-types", feature = "authnz-server-types"))]
4use impulse_server_kit::salvo;
5#[cfg(any(feature = "app-server-types", feature = "authnz-server-types"))]
6use salvo::oapi::ToSchema;
7use serde::{Deserialize, Serialize};
8
9#[derive(Deserialize, Serialize, PartialEq, Eq, Hash, Clone, Debug)]
10#[cfg_attr(any(feature = "app-server-types", feature = "authnz-server-types"), derive(ToSchema))]
11pub struct TokenBundle {
13 pub(crate) access: String,
14 pub(crate) refresh: String,
15 pub(crate) client: Option<String>,
16}
17
18impl TokenBundle {
19 pub fn new_basic(act: impl ToString, rft: impl ToString) -> Self {
21 Self {
22 access: act.to_string(),
23 refresh: rft.to_string(),
24 client: None,
25 }
26 }
27
28 pub fn new_with_cba(act: impl ToString, rft: impl ToString, cba: impl ToString) -> Self {
30 Self {
31 access: act.to_string(),
32 refresh: rft.to_string(),
33 client: Some(cba.to_string()),
34 }
35 }
36
37 pub fn act(&self) -> &str {
39 self.access.as_str()
40 }
41
42 pub fn rft(&self) -> &str {
44 self.refresh.as_str()
45 }
46
47 pub fn cba(&self) -> Option<&str> {
49 self.client.as_deref()
50 }
51
52 pub fn into_parts(self) -> (String, String, Option<String>) {
54 (self.access, self.refresh, self.client)
55 }
56
57 pub fn pack(&self) -> String {
59 format!(
60 "{}:::{}:::{}",
61 self.access,
62 self.refresh,
63 self.client.as_deref().unwrap_or_default()
64 )
65 }
66
67 pub fn set_act(&mut self, act: impl ToString) {
69 self.access = act.to_string();
70 }
71
72 pub fn set_rft(&mut self, rft: impl ToString) {
74 self.refresh = rft.to_string();
75 }
76
77 pub fn set_cba(&mut self, cba: Option<impl ToString>) {
79 self.client = cba.map(|token| token.to_string());
80 }
81
82 #[allow(clippy::unwrap_used)]
83 pub fn unpack(tokens: impl AsRef<str>) -> Option<Self> {
85 let parts = tokens.as_ref().split(":::").collect::<Vec<_>>();
86 if parts.len() != 3 {
87 return None;
88 }
89
90 let access = parts.first().unwrap().to_string();
91 let refresh = parts.get(1).unwrap().to_string();
92 let client = if let Some(client) = parts.last()
93 && !client.is_empty()
94 {
95 Some(client.to_string())
96 } else {
97 None
98 };
99
100 Some(Self { access, refresh, client })
101 }
102}