Skip to content

compat login: support using client-provided device ID #4342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 7, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions crates/handlers/src/compat/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,10 @@ async fn token_login(
.await
.map_err(RouteError::ProvisionDeviceFailed)?;

repo.app_session()
.finish_sessions_to_replace_device(clock, &browser_session.user, &device)
.await?;

let compat_session = repo
.compat_session()
.add(
Expand Down Expand Up @@ -563,6 +567,10 @@ async fn user_password_login(
.await
.map_err(RouteError::ProvisionDeviceFailed)?;

repo.app_session()
.finish_sessions_to_replace_device(clock, &user, &device)
.await?;

let session = repo
.compat_session()
.add(&mut rng, clock, &user, device, None, false)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

55 changes: 53 additions & 2 deletions crates/storage-pg/src/app_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
//! A module containing PostgreSQL implementation of repositories for sessions

use async_trait::async_trait;
use mas_data_model::{CompatSession, CompatSessionState, Device, Session, SessionState, UserAgent};
use mas_data_model::{
CompatSession, CompatSessionState, Device, Session, SessionState, User, UserAgent,
};
use mas_storage::{
Page, Pagination,
Clock, Page, Pagination,
app_session::{AppSession, AppSessionFilter, AppSessionRepository, AppSessionState},
compat::CompatSessionFilter,
oauth2::OAuth2SessionFilter,
Expand All @@ -21,6 +23,7 @@ use sea_query::{
use sea_query_binder::SqlxBinder;
use sqlx::PgConnection;
use ulid::Ulid;
use uuid::Uuid;

use crate::{
DatabaseError, ExecuteExt,
Expand Down Expand Up @@ -457,6 +460,54 @@ impl AppSessionRepository for PgAppSessionRepository<'_> {
.try_into()
.map_err(DatabaseError::to_invalid_operation)
}

#[tracing::instrument(
name = "db.app_session.finish_sessions_to_replace_device",
fields(
db.query.text,
%user.id,
%device_id = device.as_str()
),
skip_all,
err,
)]
async fn finish_sessions_to_replace_device(
&mut self,
clock: &dyn Clock,
user: &User,
device: &Device,
) -> Result<(), Self::Error> {
// TODO need to invoke this from all the oauth2 login sites
// TODO CREATE A SECOND SPAN FOR THE SECOND QUERY
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unfinished

let finished_at = clock.now();
sqlx::query!(
"
UPDATE compat_sessions SET finished_at = $3 WHERE user_id = $1 AND device_id = $2 AND finished_at IS NULL
",
Uuid::from(user.id),
device.as_str(),
finished_at
)
.traced()
.execute(&mut *self.conn)
.await?;

if let Ok(device_as_scope_token) = device.to_scope_token() {
sqlx::query!(
"
UPDATE oauth2_sessions SET finished_at = $3 WHERE user_id = $1 AND $2 = ANY(scope_list) AND finished_at IS NULL
",
Uuid::from(user.id),
device_as_scope_token.as_str(),
finished_at
)
.traced()
.execute(&mut *self.conn)
.await?;
}

Ok(())
}
}

#[cfg(test)]
Expand Down
23 changes: 22 additions & 1 deletion crates/storage/src/app_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use async_trait::async_trait;
use chrono::{DateTime, Utc};
use mas_data_model::{BrowserSession, CompatSession, Device, Session, User};

use crate::{Page, Pagination, repository_impl};
use crate::{Clock, Page, Pagination, repository_impl};

/// The state of a session
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -188,6 +188,20 @@ pub trait AppSessionRepository: Send + Sync {
///
/// Returns [`Self::Error`] if the underlying repository fails
async fn count(&mut self, filter: AppSessionFilter<'_>) -> Result<usize, Self::Error>;

/// Finishes any application sessions that are using the specified device's
/// ID.
///
/// This is intended for logging in using an existing device ID (i.e.
/// replacing a device).
///
/// Should be called *before* creating a new session for the device.
async fn finish_sessions_to_replace_device(
&mut self,
clock: &dyn Clock,
user: &User,
device: &Device,
) -> Result<(), Self::Error>;
}

repository_impl!(AppSessionRepository:
Expand All @@ -198,4 +212,11 @@ repository_impl!(AppSessionRepository:
) -> Result<Page<AppSession>, Self::Error>;

async fn count(&mut self, filter: AppSessionFilter<'_>) -> Result<usize, Self::Error>;

async fn finish_sessions_to_replace_device(
&mut self,
clock: &dyn Clock,
user: &User,
device: &Device,
) -> Result<(), Self::Error>;
);
Loading