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
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use async_graphql::{Context, Object, Union, ID};
use mas_data_model::Device;
use mas_storage::{
    compat::{CompatSessionFilter, CompatSessionRepository},
    oauth2::OAuth2SessionFilter,
    Pagination, RepositoryAccess,
};
use oauth2_types::scope::Scope;

use crate::graphql::{
    model::{CompatSession, NodeType, OAuth2Session},
    state::ContextExt,
    UserId,
};

#[derive(Default)]
pub struct SessionQuery;

/// A client session, either compat or OAuth 2.0
#[derive(Union)]
enum Session {
    CompatSession(Box<CompatSession>),
    OAuth2Session(Box<OAuth2Session>),
}

#[Object]
impl SessionQuery {
    /// Lookup a compat or OAuth 2.0 session
    async fn session(
        &self,
        ctx: &Context<'_>,
        user_id: ID,
        device_id: String,
    ) -> Result<Option<Session>, async_graphql::Error> {
        let user_id = NodeType::User.extract_ulid(&user_id)?;
        let requester = ctx.requester();
        if !requester.is_owner_or_admin(&UserId(user_id)) {
            return Ok(None);
        }

        let Ok(device) = Device::try_from(device_id) else {
            return Ok(None);
        };
        let state = ctx.state();
        let mut repo = state.repository().await?;

        // Lookup the user
        let Some(user) = repo.user().lookup(user_id).await? else {
            return Ok(None);
        };

        // First, try to find a compat session
        let filter = CompatSessionFilter::new()
            .for_user(&user)
            .active_only()
            .for_device(&device);
        // We only want most recent session
        let pagination = Pagination::last(1);
        let compat_sessions = repo.compat_session().list(filter, pagination).await?;

        if compat_sessions.has_previous_page {
            // XXX: should we bail out?
            tracing::warn!(
                "Found more than one active session with device {device} for user {user_id}"
            );
        }

        if let Some((compat_session, sso_login)) = compat_sessions.edges.into_iter().next() {
            repo.cancel().await?;

            return Ok(Some(Session::CompatSession(Box::new(
                CompatSession::new(compat_session).with_loaded_sso_login(sso_login),
            ))));
        }

        // Then, try to find an OAuth 2.0 session. Because we don't have any dedicated
        // device column, we're looking up using the device scope.
        let scope = Scope::from_iter([device.to_scope_token()]);
        let filter = OAuth2SessionFilter::new()
            .for_user(&user)
            .active_only()
            .with_scope(&scope);
        let sessions = repo.oauth2_session().list(filter, pagination).await?;

        // It's possible to have multiple active OAuth 2.0 sessions. For now, we just
        // log it if it is the case
        if sessions.has_previous_page {
            // XXX: should we bail out?
            tracing::warn!(
                "Found more than one active session with device {device} for user {user_id}"
            );
        }

        if let Some(session) = sessions.edges.into_iter().next() {
            repo.cancel().await?;
            return Ok(Some(Session::OAuth2Session(Box::new(OAuth2Session(
                session,
            )))));
        }
        repo.cancel().await?;

        Ok(None)
    }
}