|
1 | 1 | //! Authorization service. |
2 | 2 | use std::sync::Arc; |
3 | 3 |
|
| 4 | +use casbin::prelude::*; |
| 5 | +use serde::{Deserialize, Serialize}; |
| 6 | +use tokio::sync::RwLock; |
| 7 | + |
4 | 8 | use super::user::Repository; |
5 | 9 | use crate::errors::ServiceError; |
6 | 10 | use crate::models::user::{UserCompact, UserId}; |
7 | 11 |
|
| 12 | +#[derive(Debug, Clone, Serialize, Deserialize, Hash)] |
8 | 13 | pub enum ACTION { |
9 | 14 | AddCategory, |
10 | 15 | DeleteCategory, |
11 | 16 | GetSettings, |
12 | 17 | GetSettingsSecret, |
13 | 18 | AddTag, |
14 | 19 | DeleteTag, |
| 20 | + DeleteTorrent, |
| 21 | + BanUser, |
15 | 22 | } |
16 | 23 |
|
17 | 24 | pub struct Service { |
18 | 25 | user_repository: Arc<Box<dyn Repository>>, |
| 26 | + casbin_enforcer: Arc<CasbinEnforcer>, |
19 | 27 | } |
20 | 28 |
|
21 | 29 | impl Service { |
22 | 30 | #[must_use] |
23 | | - pub fn new(user_repository: Arc<Box<dyn Repository>>) -> Self { |
24 | | - Self { user_repository } |
| 31 | + pub fn new(user_repository: Arc<Box<dyn Repository>>, casbin_enforcer: Arc<CasbinEnforcer>) -> Self { |
| 32 | + Self { |
| 33 | + user_repository, |
| 34 | + casbin_enforcer, |
| 35 | + } |
25 | 36 | } |
26 | 37 |
|
| 38 | + /// It returns the compact user. |
| 39 | + /// |
27 | 40 | /// # Errors |
28 | 41 | /// |
29 | | - /// Will return an error if: |
| 42 | + /// It returns an error if there is a database error. |
| 43 | + pub async fn get_user(&self, user_id: UserId) -> std::result::Result<UserCompact, ServiceError> { |
| 44 | + self.user_repository.get_compact(&user_id).await |
| 45 | + } |
| 46 | + |
| 47 | + ///Allows or denies an user to perform an action based on the user's privileges |
30 | 48 | /// |
31 | | - /// - There is not any user with the provided `UserId` (when the user id is some). |
| 49 | + /// # Errors |
| 50 | + /// |
| 51 | + /// Will return an error if: |
| 52 | + /// - There is no user_id found in the request |
| 53 | + /// - The user_id is not found in the database |
32 | 54 | /// - The user is not authorized to perform the action. |
33 | | - pub async fn authorize(&self, action: ACTION, maybe_user_id: Option<UserId>) -> Result<(), ServiceError> { |
34 | | - match action { |
35 | | - ACTION::AddCategory |
36 | | - | ACTION::DeleteCategory |
37 | | - | ACTION::GetSettings |
38 | | - | ACTION::GetSettingsSecret |
39 | | - | ACTION::AddTag |
40 | | - | ACTION::DeleteTag => match maybe_user_id { |
41 | | - Some(user_id) => { |
42 | | - let user = self.get_user(user_id).await?; |
43 | | - |
44 | | - if !user.administrator { |
45 | | - return Err(ServiceError::Unauthorized); |
46 | | - } |
47 | | - |
48 | | - Ok(()) |
| 55 | + pub async fn authorize(&self, action: ACTION, maybe_user_id: Option<UserId>) -> std::result::Result<(), ServiceError> { |
| 56 | + match maybe_user_id { |
| 57 | + Some(user_id) => { |
| 58 | + let user_guard = self.get_user(user_id).await.map_err(|_| ServiceError::UserNotFound); |
| 59 | + // the user that wants to access a resource. |
| 60 | + let role = user_guard.unwrap().administrator; |
| 61 | + |
| 62 | + // the user that wants to access a resource. |
| 63 | + let sub = role.to_string(); |
| 64 | + |
| 65 | + let act = action; // the operation that the user performs on the resource. |
| 66 | + |
| 67 | + let enforcer = self.casbin_enforcer.enforcer.read().await; |
| 68 | + /* let enforcer = self.casbin_enforcer.clone(); |
| 69 | + let enforcer_lock = enforcer.enforcer.read().await; */ |
| 70 | + let authorize = enforcer.enforce((sub, act)).unwrap(); |
| 71 | + match authorize { |
| 72 | + true => Ok(()), |
| 73 | + false => Err(ServiceError::Unauthorized), |
49 | 74 | } |
50 | | - None => Err(ServiceError::Unauthorized), |
51 | | - }, |
| 75 | + } |
| 76 | + None => Err(ServiceError::Unauthorized), |
52 | 77 | } |
53 | 78 | } |
54 | | - |
55 | | - async fn get_user(&self, user_id: UserId) -> Result<UserCompact, ServiceError> { |
56 | | - self.user_repository.get_compact(&user_id).await |
57 | | - } |
58 | 79 | } |
59 | | -#[allow(unused_imports)] |
60 | | -#[cfg(test)] |
61 | | -mod test { |
62 | | - use std::str::FromStr; |
63 | | - use std::sync::Arc; |
64 | 80 |
|
65 | | - use mockall::predicate; |
66 | | - |
67 | | - use crate::databases::database; |
68 | | - use crate::errors::ServiceError; |
69 | | - use crate::models::user::{User, UserCompact}; |
70 | | - use crate::services::authorization::{Service, ACTION}; |
71 | | - use crate::services::user::{MockRepository, Repository}; |
72 | | - use crate::web::api::client::v1::random::string; |
73 | | - |
74 | | - #[tokio::test] |
75 | | - async fn a_guest_user_should_not_be_able_to_add_categories() { |
76 | | - let test_user_id = 1; |
77 | | - |
78 | | - let mut mock_repository = MockRepository::new(); |
79 | | - mock_repository |
80 | | - .expect_get_compact() |
81 | | - .with(predicate::eq(test_user_id)) |
82 | | - .times(1) |
83 | | - .returning(|_| Err(ServiceError::UserNotFound)); |
84 | | - |
85 | | - let service = Service::new(Arc::new(Box::new(mock_repository))); |
86 | | - assert_eq!( |
87 | | - service.authorize(ACTION::AddCategory, Some(test_user_id)).await, |
88 | | - Err(ServiceError::UserNotFound) |
89 | | - ); |
90 | | - } |
91 | | - |
92 | | - #[tokio::test] |
93 | | - async fn a_registered_user_should_not_be_able_to_add_categories() { |
94 | | - let test_user_id = 2; |
95 | | - |
96 | | - let mut mock_repository = MockRepository::new(); |
97 | | - mock_repository |
98 | | - .expect_get_compact() |
99 | | - .with(predicate::eq(test_user_id)) |
100 | | - .times(1) |
101 | | - .returning(move |_| { |
102 | | - Ok(UserCompact { |
103 | | - user_id: test_user_id, |
104 | | - username: "non_admin_user".to_string(), |
105 | | - administrator: false, |
106 | | - }) |
107 | | - }); |
108 | | - |
109 | | - let service = Service::new(Arc::new(Box::new(mock_repository))); |
110 | | - assert_eq!( |
111 | | - service.authorize(ACTION::AddCategory, Some(test_user_id)).await, |
112 | | - Err(ServiceError::Unauthorized) |
113 | | - ); |
114 | | - } |
115 | | - |
116 | | - #[tokio::test] |
117 | | - async fn an_admin_user_should_be_able_to_add_categories() { |
118 | | - let test_user_id = 3; |
119 | | - |
120 | | - let mut mock_repository = MockRepository::new(); |
121 | | - mock_repository |
122 | | - .expect_get_compact() |
123 | | - .with(predicate::eq(test_user_id)) |
124 | | - .times(1) |
125 | | - .returning(move |_| { |
126 | | - Ok(UserCompact { |
127 | | - user_id: test_user_id, |
128 | | - username: "admin_user".to_string(), |
129 | | - administrator: true, |
130 | | - }) |
131 | | - }); |
132 | | - |
133 | | - let service = Service::new(Arc::new(Box::new(mock_repository))); |
134 | | - assert_eq!(service.authorize(ACTION::AddCategory, Some(test_user_id)).await, Ok(())); |
135 | | - } |
136 | | - |
137 | | - #[tokio::test] |
138 | | - async fn a_guest_user_should_not_be_able_to_delete_categories() { |
139 | | - let test_user_id = 4; |
140 | | - |
141 | | - let mut mock_repository = MockRepository::new(); |
142 | | - mock_repository |
143 | | - .expect_get_compact() |
144 | | - .with(predicate::eq(test_user_id)) |
145 | | - .times(1) |
146 | | - .returning(|_| Err(ServiceError::UserNotFound)); |
147 | | - |
148 | | - let service = Service::new(Arc::new(Box::new(mock_repository))); |
149 | | - assert_eq!( |
150 | | - service.authorize(ACTION::DeleteCategory, Some(test_user_id)).await, |
151 | | - Err(ServiceError::UserNotFound) |
152 | | - ); |
153 | | - } |
154 | | - |
155 | | - #[tokio::test] |
156 | | - async fn a_registered_user_should_not_be_able_to_delete_categories() { |
157 | | - let test_user_id = 5; |
158 | | - |
159 | | - let mut mock_repository = MockRepository::new(); |
160 | | - mock_repository |
161 | | - .expect_get_compact() |
162 | | - .with(predicate::eq(test_user_id)) |
163 | | - .times(1) |
164 | | - .returning(move |_| { |
165 | | - Ok(UserCompact { |
166 | | - user_id: test_user_id, |
167 | | - username: "non_admin_user".to_string(), |
168 | | - administrator: false, |
169 | | - }) |
170 | | - }); |
171 | | - |
172 | | - let service = Service::new(Arc::new(Box::new(mock_repository))); |
173 | | - assert_eq!( |
174 | | - service.authorize(ACTION::DeleteCategory, Some(test_user_id)).await, |
175 | | - Err(ServiceError::Unauthorized) |
176 | | - ); |
177 | | - } |
178 | | - |
179 | | - #[tokio::test] |
180 | | - async fn an_admin_user_should_be_able_to_delete_categories() { |
181 | | - let test_user_id = 6; |
182 | | - |
183 | | - let mut mock_repository = MockRepository::new(); |
184 | | - mock_repository |
185 | | - .expect_get_compact() |
186 | | - .with(predicate::eq(test_user_id)) |
187 | | - .times(1) |
188 | | - .returning(move |_| { |
189 | | - Ok(UserCompact { |
190 | | - user_id: test_user_id, |
191 | | - username: "admin_user".to_string(), |
192 | | - administrator: true, |
193 | | - }) |
194 | | - }); |
| 81 | +pub struct CasbinEnforcer { |
| 82 | + enforcer: Arc<RwLock<Enforcer>>, //Arc<tokio::sync::RwLock<casbin::Enforcer>> |
| 83 | +} |
195 | 84 |
|
196 | | - let service = Service::new(Arc::new(Box::new(mock_repository))); |
197 | | - assert_eq!(service.authorize(ACTION::DeleteCategory, Some(test_user_id)).await, Ok(())); |
| 85 | +impl CasbinEnforcer { |
| 86 | + pub async fn new() -> Self { |
| 87 | + let enforcer = Enforcer::new("casbin/model.conf", "casbin/policy.csv").await.unwrap(); |
| 88 | + let enforcer = Arc::new(RwLock::new(enforcer)); |
| 89 | + //casbin_enforcer.enable_log(true); |
| 90 | + Self { enforcer } |
198 | 91 | } |
199 | 92 | } |
0 commit comments