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
// Copyright 2024 New Vector Ltd.
// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only
// Please see LICENSE in the repository root for full details.

use async_graphql::{Context, Enum, InputObject, Object, ID};
use mas_storage::RepositoryAccess;

use crate::graphql::{
    model::{BrowserSession, NodeType},
    state::ContextExt,
};

#[derive(Default)]
pub struct BrowserSessionMutations {
    _private: (),
}

/// The input of the `endBrowserSession` mutation.
#[derive(InputObject)]
pub struct EndBrowserSessionInput {
    /// The ID of the session to end.
    browser_session_id: ID,
}

/// The payload of the `endBrowserSession` mutation.
pub enum EndBrowserSessionPayload {
    NotFound,
    Ended(Box<mas_data_model::BrowserSession>),
}

/// The status of the `endBrowserSession` mutation.
#[derive(Enum, Copy, Clone, PartialEq, Eq, Debug)]
enum EndBrowserSessionStatus {
    /// The session was ended.
    Ended,

    /// The session was not found.
    NotFound,
}

#[Object]
impl EndBrowserSessionPayload {
    /// The status of the mutation.
    async fn status(&self) -> EndBrowserSessionStatus {
        match self {
            Self::Ended(_) => EndBrowserSessionStatus::Ended,
            Self::NotFound => EndBrowserSessionStatus::NotFound,
        }
    }

    /// Returns the ended session.
    async fn browser_session(&self) -> Option<BrowserSession> {
        match self {
            Self::Ended(session) => Some(BrowserSession(*session.clone())),
            Self::NotFound => None,
        }
    }
}

#[Object]
impl BrowserSessionMutations {
    async fn end_browser_session(
        &self,
        ctx: &Context<'_>,
        input: EndBrowserSessionInput,
    ) -> Result<EndBrowserSessionPayload, async_graphql::Error> {
        let state = ctx.state();
        let browser_session_id =
            NodeType::BrowserSession.extract_ulid(&input.browser_session_id)?;
        let requester = ctx.requester();

        let mut repo = state.repository().await?;
        let clock = state.clock();

        let session = repo.browser_session().lookup(browser_session_id).await?;

        let Some(session) = session else {
            return Ok(EndBrowserSessionPayload::NotFound);
        };

        if !requester.is_owner_or_admin(&session) {
            return Ok(EndBrowserSessionPayload::NotFound);
        }

        let session = repo.browser_session().finish(&clock, session).await?;

        repo.save().await?;

        Ok(EndBrowserSessionPayload::Ended(Box::new(session)))
    }
}