backend/service/
map_access_control.rs

1use actix_http::StatusCode;
2
3use crate::model::entity::Map;
4#[cfg(feature = "access_control")]
5use crate::model::entity::MapCollaborator;
6#[cfg(feature = "access_control")]
7use crate::model::r#enum::privacy_access_control::AccessControl;
8use crate::{
9    config::{auth::user_info::UserInfo, data::SharedPool},
10    error::ServiceError,
11};
12
13/// Order of the variants is important for comparison.
14#[derive(Debug, PartialEq, PartialOrd, Eq, Ord)]
15pub enum AccessRights {
16    /// The user has no rights.
17    None,
18    /// The user has read rights to a map.
19    Read,
20    /// The user has read/write rights to a map.
21    Write,
22}
23
24/// Check if the current user has the correct permissions to view or perform an action on a map.
25///
26/// # Errors
27/// If the connection to the database could not be established.
28/// If the user does not have the required rights for performing an action on a map.
29#[cfg(feature = "access_control")]
30pub async fn check_permissions(
31    map_id: i32,
32    pool: &SharedPool,
33    user_info: UserInfo,
34    required_rights: AccessRights,
35) -> Result<(), ServiceError> {
36    let mut conn = pool.get().await?;
37    let map_id_i64 = i64::from(map_id);
38    let result = Map::find_by_id(map_id_i64, &mut conn).await?;
39
40    if result.created_by == user_info.id || user_info.is_admin() {
41        return Ok(());
42    }
43
44    let is_collaborator =
45        MapCollaborator::contains_user_as_collaborator(user_info.id, map_id_i64, &mut conn).await?;
46
47    if is_collaborator {
48        return Ok(());
49    }
50
51    let actual_rights = result.privacy.check_access(&user_info);
52
53    if actual_rights == AccessRights::None {
54        return Err(ServiceError::new(StatusCode::NOT_FOUND, "Map not found"));
55    } else if actual_rights < required_rights {
56        return Err(ServiceError::new(
57            StatusCode::FORBIDDEN,
58            "no permissions to update data",
59        ));
60    }
61    Ok(())
62}
63
64/// This mirrors the the initial behavior of Access Control.
65/// Only Owners are allowed to modify maps.
66///
67/// # Errors
68/// If the user is not the owner of the map and requires writing access.
69#[cfg(not(feature = "access_control"))]
70pub async fn check_permissions(
71    map_id: i32,
72    pool: &SharedPool,
73    user_info: UserInfo,
74    required_rights: AccessRights,
75) -> Result<(), ServiceError> {
76    if user_info.is_admin() {
77        return Ok(());
78    }
79    let mut conn = pool.get().await?;
80    let map = Map::find_by_id(map_id, &mut conn).await?;
81    if required_rights > AccessRights::Read && map.created_by != user_info.id {
82        return Err(ServiceError {
83            status_code: StatusCode::FORBIDDEN,
84            reason: "no permission to update data".to_owned(),
85        });
86    }
87    Ok(())
88}