forked from Txio-labs/txio-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_service.rs
More file actions
133 lines (114 loc) · 4.18 KB
/
Copy pathadmin_service.rs
File metadata and controls
133 lines (114 loc) · 4.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use crate::dtos::admin_dtos::{AdminLogEntry, AdminStatsResponse};
use crate::model::user::User;
use crate::repositories::rpc_repository::RpcRepository;
use crate::repositories::session_repository::SessionRepository;
use crate::repositories::user_repository::UserRepository;
use crate::utils::auth_jwt::Claims;
use crate::utils::error::AppError;
use mongodb::bson::oid::ObjectId;
#[derive(Clone)]
pub struct AdminService {
user_repo: UserRepository,
rpc_repo: RpcRepository,
session_repo: SessionRepository,
}
impl AdminService {
pub fn new(
user_repo: UserRepository,
rpc_repo: RpcRepository,
session_repo: SessionRepository,
) -> Self {
Self {
user_repo,
rpc_repo,
session_repo,
}
}
/// Admin access is granted solely by the durable `User.is_admin` flag.
/// Email allowlist matching against JWT claims is intentionally not used.
pub(crate) fn ensure_admin_flag(user: &User) -> Result<(), AppError> {
if user.is_admin {
Ok(())
} else {
Err(AppError::Forbidden("Admin access required".into()))
}
}
async fn require_admin(&self, claims: &Claims) -> Result<(), AppError> {
let oid = ObjectId::parse_str(&claims.sub)
.map_err(|_| AppError::Unauthorized("Invalid token subject".into()))?;
let user = self.user_repo.find_by_id(&oid).await?;
Self::ensure_admin_flag(&user)
}
pub async fn list_user_emails(&self, claims: &Claims) -> Result<Vec<String>, AppError> {
self.require_admin(claims).await?;
self.user_repo.list_all_emails().await
}
pub async fn delete_user(&self, claims: &Claims, email: &str) -> Result<String, AppError> {
self.require_admin(claims).await?;
let user = self.user_repo.find_by_email(email).await?;
let user_id = user
.id
.map(|id| id.to_hex())
.ok_or_else(|| AppError::InternalError("User ID missing".into()))?;
// Clean up all sessions before deleting the account, matching the
// ordering and fail-closed error propagation in AuthService::delete_user_by_email.
let oid = ObjectId::parse_str(&user_id)
.map_err(|_| AppError::InternalError("Invalid user ID".into()))?;
self.session_repo.delete_all_by_user_id(&oid).await?;
let deleted = self.user_repo.delete_by_id(&user_id).await?;
Ok(deleted.email)
}
pub async fn stats(&self, claims: &Claims) -> Result<AdminStatsResponse, AppError> {
self.require_admin(claims).await?;
let user_count = self.user_repo.count_documents().await?;
let rpc_log_count = self.rpc_repo.count_all().await?;
Ok(AdminStatsResponse {
user_count,
rpc_log_count,
})
}
pub async fn list_logs(
&self,
claims: &Claims,
limit: i64,
) -> Result<Vec<AdminLogEntry>, AppError> {
self.require_admin(claims).await?;
let logs = self.rpc_repo.find_recent(limit).await?;
Ok(logs
.into_iter()
.map(|log| AdminLogEntry {
method: log.method,
success: log.success,
error: log.error,
timestamp: log.timestamp.to_rfc3339(),
})
.collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::user::User;
fn sample_user(is_admin: bool) -> User {
let mut user = User::new("admin@example.com".into(), "hash".into());
user.is_admin = is_admin;
user
}
#[test]
fn ensure_admin_flag_accepts_admin_user() {
assert!(AdminService::ensure_admin_flag(&sample_user(true)).is_ok());
}
#[test]
fn ensure_admin_flag_rejects_non_admin_user() {
assert!(matches!(
AdminService::ensure_admin_flag(&sample_user(false)),
Err(AppError::Forbidden(_))
));
}
#[test]
fn ensure_admin_flag_ignores_email_string() {
// Even with an "admin-looking" email, privilege requires the flag.
let user = User::new("admin@txio.io".into(), "hash".into());
assert!(AdminService::ensure_admin_flag(&user).is_err());
}
}