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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//! Trait for types stored in the user's identity cookie.

use crate::api::rcos::users::accounts::lookup::AccountLookup;
use crate::api::rcos::users::UserAccountType;
use crate::error::TelescopeError;
use crate::web::services::auth::oauth2_providers::{
    discord::DiscordIdentity, github::GitHubIdentity,
};
use crate::web::services::auth::rpi_cas::RpiCasIdentity;
use actix_identity::Identity as ActixIdentity;
use actix_web::dev::{Payload, PayloadStream};
use actix_web::{FromRequest, HttpRequest};
use futures::future::{ready, LocalBoxFuture, Ready};
use serde::Serialize;
use uuid::Uuid;

/// The root identity that this user is authenticated with.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum RootIdentity {
    /// Github access token
    GitHub(GitHubIdentity),

    /// Discord access and refresh tokens.
    Discord(DiscordIdentity),

    /// RCS ID.
    RpiCas(RpiCasIdentity),
}

impl RootIdentity {
    /// Refresh this identity token if necessary.
    pub async fn refresh(self) -> Result<Self, TelescopeError> {
        // If this is a discord-based identity, refresh it and construct the refreshed root identity.
        if let RootIdentity::Discord(discord) = self {
            return discord.refresh().await.map(RootIdentity::Discord);
        }
        // Otherwise no-op.
        return Ok(self);
    }

    /// Get the user account variant representing the authenticated platform.
    pub fn get_user_account_type(&self) -> UserAccountType {
        match self {
            RootIdentity::GitHub(_) => UserAccountType::GitHub,
            RootIdentity::Discord(_) => UserAccountType::Discord,
            RootIdentity::RpiCas(_) => UserAccountType::Rpi,
        }
    }

    /// Get the string representing the unique user identifier on this platform.
    pub async fn get_platform_id(&self) -> Result<String, TelescopeError> {
        match self {
            RootIdentity::GitHub(gh) => gh.get_github_id().await,
            RootIdentity::Discord(d) => d.get_discord_id().await,
            RootIdentity::RpiCas(RpiCasIdentity { rcs_id }) => Ok(rcs_id.clone()),
        }
    }

    /// Get the user ID of the RCOS account associated with the account
    /// authenticated with this access token (if one exists).
    pub async fn get_user_id(&self) -> Result<Option<Uuid>, TelescopeError> {
        match self {
            RootIdentity::GitHub(gh) => gh.get_rcos_user_id().await,
            RootIdentity::Discord(d) => d.get_rcos_user_id().await,
            RootIdentity::RpiCas(rpi) => rpi.get_rcos_user_id().await,
        }
    }

    /// Get the user's RCOS user ID. If the user is not found, throw an error.
    pub async fn get_user_id_or_error(&self) -> Result<Uuid, TelescopeError> {
        self.get_user_id()
            .await
            .map(|opt| opt.ok_or(TelescopeError::ise("The authenticated user doesn't exist.")))?
    }

    /// Put this root in a top level identity cookie.
    pub fn make_authenticated_cookie(self) -> AuthenticationCookie {
        AuthenticationCookie {
            root: self,
            github: None,
            discord: None,
        }
    }
}

/// The top level object stored in the identity cookie.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AuthenticationCookie {
    /// The root authenticated identity. This identity must always exist.
    pub root: RootIdentity,

    /// An optional GitHub access token.
    pub github: Option<GitHubIdentity>,

    /// An optional Discord access and refresh token.
    pub discord: Option<DiscordIdentity>,
    // We don't store an optional RCS ID because it can be queried from the
    // database.
}

impl AuthenticationCookie {
    /// If necessary, refresh an identity cookie. This could include getting a
    /// new access token from an OAuth API for example.
    pub async fn refresh(mut self) -> Result<Self, TelescopeError> {
        // Refresh the root identity
        self.root = self.root.refresh().await?;

        // When there is an additional discord identity.
        if let Some(discord_identity) = self.discord {
            // Refresh the discord identity
            let refreshed = discord_identity.refresh().await?;
            // Store back and return self.
            self.discord = Some(refreshed);
            return Ok(self);
        }

        // Otherwise return self
        return Ok(self);
    }

    /// Get the RCOS user ID of an authenticated user. This is the same as just getting the
    /// RCOS user ID of the root identity.
    pub async fn get_user_id(&self) -> Result<Option<Uuid>, TelescopeError> {
        self.root.get_user_id().await
    }

    /// Get the authenticated user's RCOS user ID via the root identity or throw an internal
    /// server error.
    pub async fn get_user_id_or_error(&self) -> Result<Uuid, TelescopeError> {
        self.root.get_user_id_or_error().await
    }

    /// Get discord credentials if authenticated.
    pub fn get_discord(&self) -> Option<&DiscordIdentity> {
        // Check the root identity first
        if let RootIdentity::Discord(discord) = &self.root {
            Some(discord)
        } else {
            // Otherwise return the child field.
            self.discord.as_ref()
        }
    }

    /// Get the github credentials if authenticated.
    pub fn get_github(&self) -> Option<&GitHubIdentity> {
        if let RootIdentity::GitHub(gh) = &self.root {
            Some(gh)
        } else {
            self.github.as_ref()
        }
    }

    /// Get the RCS ID of the authenticated user. Error if there is not an account
    /// associated with this authentication cookie or if there is an issue communicating
    /// with the RCOS API. Return `Ok(None)` if there is an account but RPI CAS is not linked.
    pub async fn get_rcs_id(&self) -> Result<Option<String>, TelescopeError> {
        // Check the base authentication first.
        if let RootIdentity::RpiCas(RpiCasIdentity { rcs_id }) = &self.root {
            return Ok(Some(rcs_id.clone()));
        } else {
            // Otherwise, get the RCS ID from the API.
            let user_id = self.get_user_id_or_error().await?;
            AccountLookup::send(user_id, UserAccountType::Rpi).await
        }
    }

    /// Try to replace the root identity with the secondary GitHub identity.
    /// Return true on success.
    fn replace_root_with_github(&mut self) -> bool {
        // Check if there is a github token to act as the root authentication
        if self.github.is_some() {
            // Swap github to the root position. Use Option::take
            // to extract the value and leave a None in its place.
            let gh: GitHubIdentity = self.github.take().unwrap();
            self.root = RootIdentity::GitHub(gh);
            return true;
        }

        // If we could not replace the root, return false.
        return false;
    }

    /// Try to replace the root identity with the discord token.
    /// Return true on success.
    /// See [`Self::replace_root_with_github`].
    fn replace_root_with_discord(&mut self) -> bool {
        if self.discord.is_some() {
            self.root = RootIdentity::Discord(self.discord.take().unwrap());
            return true;
        }
        return false;
    }

    /// Try to get the user's RCS id from the RCOS database and replace the root
    /// identity with it.
    /// Return true on success.
    async fn replace_root_with_rpi_cas(&mut self) -> Result<bool, TelescopeError> {
        // Lookup the user's ID
        let user_id = self.get_user_id_or_error().await?;
        // Lookup the user's RCS id
        let rcs_id: Option<String> = AccountLookup::send(user_id, UserAccountType::Rpi).await?;
        // If there is an RCS id, replace the root.
        if let Some(rcs_id) = rcs_id {
            self.root = RootIdentity::RpiCas(RpiCasIdentity { rcs_id });
            return Ok(true);
        }

        // Return false if we could not replace the root with the user's RCS id.
        return Ok(false);
    }

    /// Try to remove the root identity from this authentication cookie
    /// and replace it with one of the secondary ones. Return `false` if
    /// there is no secondary cookie to replace the root. This may try to access
    /// the RCOS API to look for an RCS ID to replace the root.
    ///
    /// If the root can successfully be replaced, return `true`.
    async fn remove_root(&mut self) -> Result<bool, TelescopeError> {
        match self.root {
            // When the root identity is an RCS ID.
            RootIdentity::RpiCas(_) => {
                // Try with GitHub, then discord
                Ok(self.replace_root_with_github() || self.replace_root_with_discord())
            }
            // When root identity is GitHub auth
            RootIdentity::GitHub(_) => {
                // Try with discord then RCS id.
                Ok(self.replace_root_with_discord() || self.replace_root_with_rpi_cas().await?)
            }
            // When the root identity is Discord Auth
            RootIdentity::Discord(_) => {
                // Try with GitHub then with RPI CAS
                Ok(self.replace_root_with_github() || self.replace_root_with_rpi_cas().await?)
            }
        }
    }

    /// Try to remove a specific platform's identity and authentication from this cookie.
    /// This is similar to [`Self::remove_root`].
    pub async fn remove_platform(
        &mut self,
        platform: UserAccountType,
    ) -> Result<bool, TelescopeError> {
        // If the account of this type is in the root, simply remove the root.
        if self.root.get_user_account_type() == platform {
            return self.remove_root().await;
        }

        // If it's not in the root, just drop the secondary authentication token
        match platform {
            UserAccountType::GitHub => self.github = None,
            UserAccountType::Discord => self.discord = None,
            // If it isn't held in the authentication cookie this is a no-op
            _ => {}
        }
        // If it wasn't the root, we always succeed to remove a secondary.
        return Ok(true);
    }
}

/// The identity of a user accessing telescope.
#[derive(Clone)]
pub struct Identity {
    /// The actix identity of this request. This handles cookie and
    /// security stuff.
    inner: ActixIdentity,
}

impl FromRequest for Identity {
    type Error = TelescopeError;
    type Future = Ready<Result<Self, Self::Error>>;
    type Config = ();

    fn from_request(req: &HttpRequest, _: &mut Payload<PayloadStream>) -> Self::Future {
        // Extract the actix identity and convert any errors
        ready(
            ActixIdentity::extract(req)
                // Unwrap the ready future
                .into_inner()
                // Normalize the error as an ISE
                .map_err(|e| {
                    TelescopeError::ise(format!(
                        "Could not extract identity \
            object from request. Internal error: {}",
                        e
                    ))
                })
                // Wrap the extracted identity.
                .map(|inner| Self { inner }),
        )
    }
}

impl FromRequest for AuthenticationCookie {
    type Error = TelescopeError;
    type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
    type Config = ();

    fn from_request(req: &HttpRequest, _: &mut Payload<PayloadStream>) -> Self::Future {
        // Clone a reference to the HTTP req, since its behind an Rc pointer.
        let owned_request: HttpRequest = req.clone();
        return Box::pin(async move {
            // Extract the telescope-identity from the request
            Identity::extract(&owned_request)
                // Wait and propagate errors
                .await?
                // Get the cookie if there is one
                .identity()
                // Wait and make error on none
                .await
                .ok_or(TelescopeError::NotAuthenticated)
        });
    }
}

impl Identity {
    /// Forget the user's identity if it exists.
    pub fn forget(&self) {
        self.inner.forget()
    }

    /// Save an identity object to the client's cookies.
    pub fn save(&self, identity: &AuthenticationCookie) {
        // Serialize the cookie to JSON first. This serialization should not fail.
        let cookie: String =
            serde_json::to_string(identity).expect("Could not serialize identity cookie");

        // Remember cookie.
        self.inner.remember(cookie)
    }

    /// Get the user's identity. Refresh it if necessary.
    pub async fn identity(&self) -> Option<AuthenticationCookie> {
        // Get the inner identity as a String.
        let id: String = self.inner.identity()?;
        // try to deserialize it
        match serde_json::from_str::<AuthenticationCookie>(id.as_str()) {
            // On okay, refresh the identity cookie if needed
            Ok(id) => match id.refresh().await {
                // If this succeeds
                Ok(id) => {
                    // Save and return the authenticated identity
                    self.save(&id);
                    return Some(id);
                }

                // If it fails to refresh, we have no identity. Send a warning
                // and return None.
                Err(e) => {
                    warn!("Could not refresh identity token. Error: {}", e);
                    return None;
                }
            },

            // If there is an error deserializing, the identity is malformed.
            // Forget it, and log a warning. Return no identity.
            Err(err) => {
                warn!("Bad identity forgotten. Error: {}", err);
                self.forget();
                return None;
            }
        }
    }

    /// Get the user ID of the authenticated RCOS account (if there is one.)
    pub async fn get_user_id(&self) -> Result<Option<Uuid>, TelescopeError> {
        // If there is an identity cookie
        if let Some(id) = self.identity().await {
            // Use it to get the authenticated RCOS user ID.
            return id.get_user_id().await;
        } else {
            return Ok(None);
        }
    }
}