You've already forked authentication-service
mirror of
https://github.com/matrix-org/matrix-authentication-service.git
synced 2025-07-29 22:01:14 +03:00
storage: user and user email repository
This commit is contained in:
@ -21,8 +21,8 @@ use mas_storage::{
|
||||
add_compat_access_token, add_compat_refresh_token, get_compat_sso_login_by_token,
|
||||
mark_compat_sso_login_as_exchanged, start_compat_session,
|
||||
},
|
||||
user::{add_user_password, lookup_user_by_username, lookup_user_password},
|
||||
Clock,
|
||||
user::{add_user_password, lookup_user_password, UserRepository},
|
||||
Clock, Repository,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_with::{serde_as, skip_serializing_none, DurationMilliSeconds};
|
||||
@ -314,7 +314,9 @@ async fn user_password_login(
|
||||
let (clock, mut rng) = crate::clock_and_rng();
|
||||
|
||||
// Find the user
|
||||
let user = lookup_user_by_username(&mut *txn, &username)
|
||||
let user = txn
|
||||
.user()
|
||||
.find_by_username(&username)
|
||||
.await?
|
||||
.ok_or(RouteError::UserNotFound)?;
|
||||
|
||||
|
@ -80,14 +80,8 @@ pub async fn get(
|
||||
return Ok((cookie_jar, url).into_response());
|
||||
};
|
||||
|
||||
// TODO: make that more generic
|
||||
if session
|
||||
.user
|
||||
.primary_email
|
||||
.as_ref()
|
||||
.and_then(|e| e.confirmed_at)
|
||||
.is_none()
|
||||
{
|
||||
// TODO: make that more generic, check that the email has been confirmed
|
||||
if session.user.primary_user_email_id.is_none() {
|
||||
let destination = mas_router::AccountAddEmail::default()
|
||||
.and_then(PostAuthAction::continue_compat_sso_login(id));
|
||||
return Ok((cookie_jar, destination.go()).into_response());
|
||||
@ -149,13 +143,7 @@ pub async fn post(
|
||||
};
|
||||
|
||||
// TODO: make that more generic
|
||||
if session
|
||||
.user
|
||||
.primary_email
|
||||
.as_ref()
|
||||
.and_then(|e| e.confirmed_at)
|
||||
.is_none()
|
||||
{
|
||||
if session.user.primary_user_email_id.is_none() {
|
||||
let destination = mas_router::AccountAddEmail::default()
|
||||
.and_then(PostAuthAction::continue_compat_sso_login(id));
|
||||
return Ok((cookie_jar, destination.go()).into_response());
|
||||
|
@ -28,6 +28,7 @@ use mas_jose::{
|
||||
};
|
||||
use mas_keystore::Keystore;
|
||||
use mas_router::UrlBuilder;
|
||||
use mas_storage::{user::UserEmailRepository, Repository};
|
||||
use oauth2_types::scope;
|
||||
use serde::Serialize;
|
||||
use serde_with::skip_serializing_none;
|
||||
@ -66,6 +67,7 @@ pub enum RouteError {
|
||||
}
|
||||
|
||||
impl_from_error_for_route!(sqlx::Error);
|
||||
impl_from_error_for_route!(mas_storage::DatabaseError);
|
||||
impl_from_error_for_route!(mas_keystore::WrongAlgorithmError);
|
||||
impl_from_error_for_route!(mas_jose::jwt::JwtSignatureError);
|
||||
|
||||
@ -92,19 +94,19 @@ pub async fn get(
|
||||
let session = user_authorization.protected(&mut conn).await?;
|
||||
|
||||
let user = session.browser_session.user;
|
||||
let mut user_info = UserInfo {
|
||||
sub: user.sub,
|
||||
username: user.username,
|
||||
email: None,
|
||||
email_verified: None,
|
||||
|
||||
let user_email = if session.scope.contains(&scope::EMAIL) {
|
||||
conn.user_email().get_primary(&user).await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if session.scope.contains(&scope::EMAIL) {
|
||||
if let Some(email) = user.primary_email {
|
||||
user_info.email_verified = Some(email.confirmed_at.is_some());
|
||||
user_info.email = Some(email.email);
|
||||
}
|
||||
}
|
||||
let user_info = UserInfo {
|
||||
sub: user.sub.clone(),
|
||||
username: user.username.clone(),
|
||||
email_verified: user_email.as_ref().map(|u| u.confirmed_at.is_some()),
|
||||
email: user_email.map(|u| u.email),
|
||||
};
|
||||
|
||||
if let Some(alg) = session.client.userinfo_signed_response_alg {
|
||||
let key = key_store
|
||||
|
@ -26,7 +26,7 @@ use mas_axum_utils::{
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_storage::{
|
||||
upstream_oauth2::UpstreamOAuthSessionRepository,
|
||||
user::{add_user, authenticate_session_with_upstream, lookup_user, start_session},
|
||||
user::{authenticate_session_with_upstream, start_session, UserRepository},
|
||||
Repository, UpstreamOAuthLinkRepository,
|
||||
};
|
||||
use mas_templates::{
|
||||
@ -51,6 +51,10 @@ pub(crate) enum RouteError {
|
||||
#[error("Session not found")]
|
||||
SessionNotFound,
|
||||
|
||||
/// Couldn't find the user
|
||||
#[error("User not found")]
|
||||
UserNotFound,
|
||||
|
||||
/// Session was already consumed
|
||||
#[error("Session already consumed")]
|
||||
SessionConsumed,
|
||||
@ -157,7 +161,11 @@ pub(crate) async fn get(
|
||||
// Session already linked, but link doesn't match the currently
|
||||
// logged user. Suggest logging out of the current user
|
||||
// and logging in with the new one
|
||||
let user = lookup_user(&mut txn, user_id).await?;
|
||||
let user = txn
|
||||
.user()
|
||||
.lookup(user_id)
|
||||
.await?
|
||||
.ok_or(RouteError::UserNotFound)?;
|
||||
|
||||
let ctx = UpstreamExistingLinkContext::new(user)
|
||||
.with_session(user_session)
|
||||
@ -177,7 +185,11 @@ pub(crate) async fn get(
|
||||
|
||||
(None, Some(user_id)) => {
|
||||
// Session linked, but user not logged in: do the login
|
||||
let user = lookup_user(&mut txn, user_id).await?;
|
||||
let user = txn
|
||||
.user()
|
||||
.lookup(user_id)
|
||||
.await?
|
||||
.ok_or(RouteError::UserNotFound)?;
|
||||
|
||||
let ctx = UpstreamExistingLinkContext::new(user).with_csrf(csrf_token.form_value());
|
||||
|
||||
@ -250,12 +262,17 @@ pub(crate) async fn post(
|
||||
}
|
||||
|
||||
(None, Some(user_id), FormData::Login) => {
|
||||
let user = lookup_user(&mut txn, user_id).await?;
|
||||
let user = txn
|
||||
.user()
|
||||
.lookup(user_id)
|
||||
.await?
|
||||
.ok_or(RouteError::UserNotFound)?;
|
||||
|
||||
start_session(&mut txn, &mut rng, &clock, user).await?
|
||||
}
|
||||
|
||||
(None, None, FormData::Register { username }) => {
|
||||
let user = add_user(&mut txn, &mut rng, &clock, &username).await?;
|
||||
let user = txn.user().add(&mut rng, &clock, username).await?;
|
||||
txn.upstream_oauth_link()
|
||||
.associate_to_user(&link, &user)
|
||||
.await?;
|
||||
|
@ -24,7 +24,7 @@ use mas_axum_utils::{
|
||||
use mas_email::Mailer;
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_router::Route;
|
||||
use mas_storage::user::add_user_email;
|
||||
use mas_storage::{user::UserEmailRepository, Repository};
|
||||
use mas_templates::{EmailAddContext, TemplateContext, Templates};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
@ -88,7 +88,11 @@ pub(crate) async fn post(
|
||||
return Ok((cookie_jar, login.go()).into_response());
|
||||
};
|
||||
|
||||
let user_email = add_user_email(&mut txn, &mut rng, &clock, &session.user, form.email).await?;
|
||||
let user_email = txn
|
||||
.user_email()
|
||||
.add(&mut rng, &clock, &session.user, form.email)
|
||||
.await?;
|
||||
|
||||
let next = mas_router::AccountVerifyEmail::new(user_email.id);
|
||||
let next = if let Some(action) = query.post_auth_action {
|
||||
next.and_then(action)
|
||||
|
@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use axum::{
|
||||
extract::{Form, State},
|
||||
response::{Html, IntoResponse, Response},
|
||||
@ -27,17 +28,11 @@ use mas_data_model::{BrowserSession, User, UserEmail};
|
||||
use mas_email::Mailer;
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_router::Route;
|
||||
use mas_storage::{
|
||||
user::{
|
||||
add_user_email, add_user_email_verification_code, get_user_email, get_user_emails,
|
||||
remove_user_email, set_user_email_as_primary,
|
||||
},
|
||||
Clock,
|
||||
};
|
||||
use mas_storage::{user::UserEmailRepository, Clock, Repository};
|
||||
use mas_templates::{AccountEmailsContext, EmailVerificationContext, TemplateContext, Templates};
|
||||
use rand::{distributions::Uniform, Rng};
|
||||
use serde::Deserialize;
|
||||
use sqlx::{PgExecutor, PgPool};
|
||||
use sqlx::{PgConnection, PgPool};
|
||||
use tracing::info;
|
||||
|
||||
pub mod add;
|
||||
@ -79,11 +74,11 @@ async fn render(
|
||||
templates: Templates,
|
||||
session: BrowserSession,
|
||||
cookie_jar: PrivateCookieJar<Encrypter>,
|
||||
executor: impl PgExecutor<'_>,
|
||||
conn: &mut PgConnection,
|
||||
) -> Result<Response, FancyError> {
|
||||
let (csrf_token, cookie_jar) = cookie_jar.csrf_token(clock.now(), rng);
|
||||
|
||||
let emails = get_user_emails(executor, &session.user).await?;
|
||||
let emails = conn.user_email().all(&session.user).await?;
|
||||
|
||||
let ctx = AccountEmailsContext::new(emails)
|
||||
.with_session(session)
|
||||
@ -96,7 +91,7 @@ async fn render(
|
||||
|
||||
async fn start_email_verification(
|
||||
mailer: &Mailer,
|
||||
executor: impl PgExecutor<'_>,
|
||||
conn: &mut PgConnection,
|
||||
mut rng: impl Rng + Send,
|
||||
clock: &Clock,
|
||||
user: &User,
|
||||
@ -108,15 +103,10 @@ async fn start_email_verification(
|
||||
|
||||
let address: Address = user_email.email.parse()?;
|
||||
|
||||
let verification = add_user_email_verification_code(
|
||||
executor,
|
||||
&mut rng,
|
||||
clock,
|
||||
user_email,
|
||||
Duration::hours(8),
|
||||
code,
|
||||
)
|
||||
.await?;
|
||||
let verification = conn
|
||||
.user_email()
|
||||
.add_verification_code(&mut rng, clock, &user_email, Duration::hours(8), code)
|
||||
.await?;
|
||||
|
||||
// And send the verification email
|
||||
let mailbox = Mailbox::new(Some(user.username.clone()), address);
|
||||
@ -126,7 +116,7 @@ async fn start_email_verification(
|
||||
mailer.send_verification_email(mailbox, &context).await?;
|
||||
|
||||
info!(
|
||||
email.id = %verification.email.id,
|
||||
email.id = %user_email.id,
|
||||
"Verification email sent"
|
||||
);
|
||||
Ok(())
|
||||
@ -157,49 +147,65 @@ pub(crate) async fn post(
|
||||
|
||||
match form {
|
||||
ManagementForm::Add { email } => {
|
||||
let user_email =
|
||||
add_user_email(&mut txn, &mut rng, &clock, &session.user, email).await?;
|
||||
let next = mas_router::AccountVerifyEmail::new(user_email.id);
|
||||
start_email_verification(
|
||||
&mailer,
|
||||
&mut txn,
|
||||
&mut rng,
|
||||
&clock,
|
||||
&session.user,
|
||||
user_email,
|
||||
)
|
||||
.await?;
|
||||
let email = txn
|
||||
.user_email()
|
||||
.add(&mut rng, &clock, &session.user, email)
|
||||
.await?;
|
||||
|
||||
let next = mas_router::AccountVerifyEmail::new(email.id);
|
||||
start_email_verification(&mailer, &mut txn, &mut rng, &clock, &session.user, email)
|
||||
.await?;
|
||||
txn.commit().await?;
|
||||
return Ok((cookie_jar, next.go()).into_response());
|
||||
}
|
||||
ManagementForm::ResendConfirmation { id } => {
|
||||
let id = id.parse()?;
|
||||
|
||||
let user_email = get_user_email(&mut txn, &session.user, id).await?;
|
||||
let next = mas_router::AccountVerifyEmail::new(user_email.id);
|
||||
start_email_verification(
|
||||
&mailer,
|
||||
&mut txn,
|
||||
&mut rng,
|
||||
&clock,
|
||||
&session.user,
|
||||
user_email,
|
||||
)
|
||||
.await?;
|
||||
let email = txn
|
||||
.user_email()
|
||||
.lookup(id)
|
||||
.await?
|
||||
.context("Email not found")?;
|
||||
|
||||
if email.user_id != session.user.id {
|
||||
return Err(anyhow!("Email not found").into());
|
||||
}
|
||||
|
||||
let next = mas_router::AccountVerifyEmail::new(email.id);
|
||||
start_email_verification(&mailer, &mut txn, &mut rng, &clock, &session.user, email)
|
||||
.await?;
|
||||
txn.commit().await?;
|
||||
return Ok((cookie_jar, next.go()).into_response());
|
||||
}
|
||||
ManagementForm::Remove { id } => {
|
||||
let id = id.parse()?;
|
||||
|
||||
let email = get_user_email(&mut txn, &session.user, id).await?;
|
||||
remove_user_email(&mut txn, email).await?;
|
||||
let email = txn
|
||||
.user_email()
|
||||
.lookup(id)
|
||||
.await?
|
||||
.context("Email not found")?;
|
||||
|
||||
if email.user_id != session.user.id {
|
||||
return Err(anyhow!("Email not found").into());
|
||||
}
|
||||
|
||||
txn.user_email().remove(email).await?;
|
||||
}
|
||||
ManagementForm::SetPrimary { id } => {
|
||||
let id = id.parse()?;
|
||||
let email = get_user_email(&mut txn, &session.user, id).await?;
|
||||
set_user_email_as_primary(&mut txn, &email).await?;
|
||||
session.user.primary_email = Some(email);
|
||||
let email = txn
|
||||
.user_email()
|
||||
.lookup(id)
|
||||
.await?
|
||||
.context("Email not found")?;
|
||||
|
||||
if email.user_id != session.user.id {
|
||||
return Err(anyhow!("Email not found").into());
|
||||
}
|
||||
|
||||
txn.user_email().set_as_primary(&email).await?;
|
||||
session.user.primary_user_email_id = Some(email.id);
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -24,13 +24,7 @@ use mas_axum_utils::{
|
||||
};
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_router::Route;
|
||||
use mas_storage::{
|
||||
user::{
|
||||
consume_email_verification, lookup_user_email_by_id, lookup_user_email_verification_code,
|
||||
mark_user_email_as_verified, set_user_email_as_primary,
|
||||
},
|
||||
Clock,
|
||||
};
|
||||
use mas_storage::{user::UserEmailRepository, Clock, Repository};
|
||||
use mas_templates::{EmailVerificationPageContext, TemplateContext, Templates};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
@ -65,8 +59,11 @@ pub(crate) async fn get(
|
||||
return Ok((cookie_jar, login.go()).into_response());
|
||||
};
|
||||
|
||||
let user_email = lookup_user_email_by_id(&mut conn, &session.user, id)
|
||||
let user_email = conn
|
||||
.user_email()
|
||||
.lookup(id)
|
||||
.await?
|
||||
.filter(|u| u.user_id == session.user.id)
|
||||
.context("Could not find user email")?;
|
||||
|
||||
if user_email.confirmed_at.is_some() {
|
||||
@ -106,23 +103,31 @@ pub(crate) async fn post(
|
||||
return Ok((cookie_jar, login.go()).into_response());
|
||||
};
|
||||
|
||||
let email = lookup_user_email_by_id(&mut txn, &session.user, id)
|
||||
let user_email = txn
|
||||
.user_email()
|
||||
.lookup(id)
|
||||
.await?
|
||||
.filter(|u| u.user_id == session.user.id)
|
||||
.context("Could not find user email")?;
|
||||
|
||||
if session.user.primary_email.is_none() {
|
||||
set_user_email_as_primary(&mut txn, &email).await?;
|
||||
}
|
||||
|
||||
// TODO: make those 8 hours configurable
|
||||
let verification = lookup_user_email_verification_code(&mut txn, &clock, email, &form.code)
|
||||
let verification = txn
|
||||
.user_email()
|
||||
.find_verification_code(&clock, &user_email, &form.code)
|
||||
.await?
|
||||
.context("Invalid code")?;
|
||||
|
||||
// TODO: display nice errors if the code was already consumed or expired
|
||||
let verification = consume_email_verification(&mut txn, &clock, verification).await?;
|
||||
txn.user_email()
|
||||
.consume_verification_code(&clock, verification)
|
||||
.await?;
|
||||
|
||||
let _email = mark_user_email_as_verified(&mut txn, &clock, verification.email).await?;
|
||||
if session.user.primary_user_email_id.is_none() {
|
||||
txn.user_email().set_as_primary(&user_email).await?;
|
||||
}
|
||||
|
||||
txn.user_email()
|
||||
.mark_as_verified(&clock, user_email)
|
||||
.await?;
|
||||
|
||||
txn.commit().await?;
|
||||
|
||||
|
@ -23,7 +23,10 @@ use axum_extra::extract::PrivateCookieJar;
|
||||
use mas_axum_utils::{csrf::CsrfExt, FancyError, SessionInfoExt};
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_router::Route;
|
||||
use mas_storage::user::{count_active_sessions, get_user_emails};
|
||||
use mas_storage::{
|
||||
user::{count_active_sessions, UserEmailRepository},
|
||||
Repository,
|
||||
};
|
||||
use mas_templates::{AccountContext, TemplateContext, Templates};
|
||||
use sqlx::PgPool;
|
||||
|
||||
@ -49,7 +52,7 @@ pub(crate) async fn get(
|
||||
|
||||
let active_sessions = count_active_sessions(&mut conn, &session.user).await?;
|
||||
|
||||
let emails = get_user_emails(&mut conn, &session.user).await?;
|
||||
let emails = conn.user_email().all(&session.user).await?;
|
||||
|
||||
let ctx = AccountContext::new(active_sessions, emails)
|
||||
.with_session(session)
|
||||
|
@ -26,8 +26,8 @@ use mas_keystore::Encrypter;
|
||||
use mas_storage::{
|
||||
upstream_oauth2::UpstreamOAuthProviderRepository,
|
||||
user::{
|
||||
add_user_password, authenticate_session_with_password, lookup_user_by_username,
|
||||
lookup_user_password, start_session,
|
||||
add_user_password, authenticate_session_with_password, lookup_user_password, start_session,
|
||||
UserRepository,
|
||||
},
|
||||
Clock, Repository,
|
||||
};
|
||||
@ -130,8 +130,6 @@ pub(crate) async fn post(
|
||||
return Ok((cookie_jar, Html(content)).into_response());
|
||||
}
|
||||
|
||||
lookup_user_by_username(&mut conn, &form.username).await?;
|
||||
|
||||
match login(
|
||||
password_manager,
|
||||
&mut conn,
|
||||
@ -175,7 +173,9 @@ async fn login(
|
||||
) -> Result<BrowserSession, FormError> {
|
||||
// XXX: we're loosing the error context here
|
||||
// First, lookup the user
|
||||
let user = lookup_user_by_username(&mut *conn, username)
|
||||
let user = conn
|
||||
.user()
|
||||
.find_by_username(username)
|
||||
.await
|
||||
.map_err(|_e| FormError::Internal)?
|
||||
.ok_or(FormError::InvalidCredentials)?;
|
||||
|
@ -31,9 +31,12 @@ use mas_email::Mailer;
|
||||
use mas_keystore::Encrypter;
|
||||
use mas_policy::PolicyFactory;
|
||||
use mas_router::Route;
|
||||
use mas_storage::user::{
|
||||
add_user, add_user_email, add_user_email_verification_code, add_user_password,
|
||||
authenticate_session_with_password, start_session, username_exists,
|
||||
use mas_storage::{
|
||||
user::{
|
||||
add_user_password, authenticate_session_with_password, start_session, UserEmailRepository,
|
||||
UserRepository,
|
||||
},
|
||||
Repository,
|
||||
};
|
||||
use mas_templates::{
|
||||
EmailVerificationContext, FieldError, FormError, RegisterContext, RegisterFormField,
|
||||
@ -114,7 +117,7 @@ pub(crate) async fn post(
|
||||
|
||||
if form.username.is_empty() {
|
||||
state.add_error_on_field(RegisterFormField::Username, FieldError::Required);
|
||||
} else if username_exists(&mut txn, &form.username).await? {
|
||||
} else if txn.user().exists(&form.username).await? {
|
||||
state.add_error_on_field(RegisterFormField::Username, FieldError::Exists);
|
||||
}
|
||||
|
||||
@ -185,7 +188,7 @@ pub(crate) async fn post(
|
||||
return Ok((cookie_jar, Html(content)).into_response());
|
||||
}
|
||||
|
||||
let user = add_user(&mut txn, &mut rng, &clock, &form.username).await?;
|
||||
let user = txn.user().add(&mut rng, &clock, form.username).await?;
|
||||
let password = Zeroizing::new(form.password.into_bytes());
|
||||
let (version, hashed_password) = password_manager.hash(&mut rng, password).await?;
|
||||
let user_password = add_user_password(
|
||||
@ -199,7 +202,10 @@ pub(crate) async fn post(
|
||||
)
|
||||
.await?;
|
||||
|
||||
let user_email = add_user_email(&mut txn, &mut rng, &clock, &user, form.email).await?;
|
||||
let user_email = txn
|
||||
.user_email()
|
||||
.add(&mut rng, &clock, &user, form.email)
|
||||
.await?;
|
||||
|
||||
// First, generate a code
|
||||
let range = Uniform::<u32>::from(0..1_000_000);
|
||||
@ -208,15 +214,10 @@ pub(crate) async fn post(
|
||||
|
||||
let address: Address = user_email.email.parse()?;
|
||||
|
||||
let verification = add_user_email_verification_code(
|
||||
&mut txn,
|
||||
&mut rng,
|
||||
&clock,
|
||||
user_email,
|
||||
Duration::hours(8),
|
||||
code,
|
||||
)
|
||||
.await?;
|
||||
let verification = txn
|
||||
.user_email()
|
||||
.add_verification_code(&mut rng, &clock, &user_email, Duration::hours(8), code)
|
||||
.await?;
|
||||
|
||||
// And send the verification email
|
||||
let mailbox = Mailbox::new(Some(user.username.clone()), address);
|
||||
@ -225,8 +226,7 @@ pub(crate) async fn post(
|
||||
|
||||
mailer.send_verification_email(mailbox, &context).await?;
|
||||
|
||||
let next = mas_router::AccountVerifyEmail::new(verification.email.id)
|
||||
.and_maybe(query.post_auth_action);
|
||||
let next = mas_router::AccountVerifyEmail::new(user_email.id).and_maybe(query.post_auth_action);
|
||||
|
||||
let mut session = start_session(&mut txn, &mut rng, &clock, user).await?;
|
||||
authenticate_session_with_password(&mut txn, &mut rng, &clock, &mut session, &user_password)
|
||||
|
Reference in New Issue
Block a user