use webgates::accounts::Account;
use webgates::authz::access_hierarchy::AccessHierarchy;
use webgates::codecs::jwt::RegisteredClaims;
#[derive(Debug, Clone)]
pub struct JwtAuthContext<R, G>
where
R: AccessHierarchy + Eq + std::fmt::Display + Clone,
G: Eq + Clone,
{
account: Account<R, G>,
registered_claims: RegisteredClaims,
}
impl<R, G> JwtAuthContext<R, G>
where
R: AccessHierarchy + Eq + std::fmt::Display + Clone,
G: Eq + Clone,
{
pub fn new(account: Account<R, G>, registered_claims: RegisteredClaims) -> Self {
Self {
account,
registered_claims,
}
}
pub fn account(&self) -> &Account<R, G> {
&self.account
}
pub fn registered_claims(&self) -> &RegisteredClaims {
&self.registered_claims
}
}
#[derive(Debug, Clone)]
pub struct OptionalJwtAuthContext<R, G>
where
R: AccessHierarchy + Eq + std::fmt::Display + Clone,
G: Eq + Clone,
{
account: Option<Account<R, G>>,
registered_claims: Option<RegisteredClaims>,
}
impl<R, G> OptionalJwtAuthContext<R, G>
where
R: AccessHierarchy + Eq + std::fmt::Display + Clone,
G: Eq + Clone,
{
pub fn authenticated(account: Account<R, G>, registered_claims: RegisteredClaims) -> Self {
Self {
account: Some(account),
registered_claims: Some(registered_claims),
}
}
pub fn anonymous() -> Self {
Self {
account: None,
registered_claims: None,
}
}
pub fn account(&self) -> Option<&Account<R, G>> {
self.account.as_ref()
}
pub fn registered_claims(&self) -> Option<&RegisteredClaims> {
self.registered_claims.as_ref()
}
pub fn is_authenticated(&self) -> bool {
self.account.is_some()
}
}
#[derive(Debug, Clone, Copy)]
pub struct StaticTokenAuthorized(bool);
impl StaticTokenAuthorized {
pub fn new(authorized: bool) -> Self {
Self(authorized)
}
pub fn is_authorized(&self) -> bool {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use webgates::accounts::Account;
use webgates::codecs::jwt::RegisteredClaims;
use webgates::groups::Group;
use webgates::roles::Role;
#[test]
fn jwt_auth_context_accessors() {
let account = Account::<Role, Group>::new("user");
let claims = RegisteredClaims::new("issuer", 9999);
let ctx = JwtAuthContext::new(account.clone(), claims.clone());
assert_eq!(ctx.account().user_id, account.user_id);
assert_eq!(ctx.registered_claims().issuer, "issuer");
}
#[test]
fn optional_jwt_auth_context_authenticated() {
let account = Account::<Role, Group>::new("user");
let claims = RegisteredClaims::new("issuer", 9999);
let ctx = OptionalJwtAuthContext::authenticated(account, claims);
assert!(ctx.is_authenticated());
assert!(ctx.account().is_some());
assert!(ctx.registered_claims().is_some());
}
#[test]
fn optional_jwt_auth_context_anonymous() {
let ctx = OptionalJwtAuthContext::<Role, Group>::anonymous();
assert!(!ctx.is_authenticated());
assert!(ctx.account().is_none());
assert!(ctx.registered_claims().is_none());
}
#[test]
fn static_token_authorized_true() {
assert!(StaticTokenAuthorized::new(true).is_authorized());
}
#[test]
fn static_token_authorized_false() {
assert!(!StaticTokenAuthorized::new(false).is_authorized());
}
}