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_option::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 result = Map::find_by_id(map_id, &mut conn).await?;
38
39    if result.created_by == user_info.id || user_info.is_admin() {
40        return Ok(());
41    }
42
43    let is_collaborator =
44        MapCollaborator::contains_user_as_collaborator(user_info.id, map_id, &mut conn).await?;
45
46    if is_collaborator {
47        return Ok(());
48    }
49
50    let actual_rights = result.privacy.check_access(&user_info);
51
52    if actual_rights == AccessRights::None {
53        return Err(ServiceError::new(StatusCode::NOT_FOUND, "Map not found"));
54    } else if actual_rights < required_rights {
55        return Err(ServiceError::new(
56            StatusCode::FORBIDDEN,
57            "no permissions to update data",
58        ));
59    }
60    Ok(())
61}
62
63/// This mirrors the the initial behavior of Access Control.
64/// Only Owners are allowed to modify maps.
65///
66/// # Errors
67/// If the user is not the owner of the map and requires writing access.
68#[cfg(not(feature = "access_control"))]
69pub async fn check_permissions(
70    map_id: i32,
71    pool: &SharedPool,
72    user_info: UserInfo,
73    required_rights: AccessRights,
74) -> Result<(), ServiceError> {
75    if user_info.is_admin() {
76        return Ok(());
77    }
78    let mut conn = pool.get().await?;
79    let map = Map::find_by_id(map_id, &mut conn).await?;
80    if required_rights > AccessRights::Read && map.created_by != user_info.id {
81        return Err(ServiceError {
82            status_code: StatusCode::FORBIDDEN,
83            reason: "no permission to update data".to_owned(),
84        });
85    }
86    Ok(())
87}