2023-09-20 14:49:54 +00:00
|
|
|
use crate::{build_totp_2fa, generate_totp_2fa_secret};
|
|
|
|
use activitypub_federation::config::Data;
|
|
|
|
use actix_web::web::Json;
|
2024-05-17 00:41:57 +00:00
|
|
|
use lemmy_api_common::{context::LemmyContext, person::GenerateTotpSecretResponse};
|
2024-03-25 20:02:12 +00:00
|
|
|
use lemmy_db_schema::source::local_user::{LocalUser, LocalUserUpdateForm};
|
2023-09-20 14:49:54 +00:00
|
|
|
use lemmy_db_views::structs::{LocalUserView, SiteView};
|
2024-04-10 14:14:11 +00:00
|
|
|
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
|
2023-09-20 14:49:54 +00:00
|
|
|
|
|
|
|
/// Generate a new secret for two-factor-authentication. Afterwards you need to call [toggle_totp]
|
|
|
|
/// to enable it. This can only be called if 2FA is currently disabled.
|
|
|
|
#[tracing::instrument(skip(context))]
|
|
|
|
pub async fn generate_totp_secret(
|
|
|
|
local_user_view: LocalUserView,
|
|
|
|
context: Data<LemmyContext>,
|
2024-04-10 14:14:11 +00:00
|
|
|
) -> LemmyResult<Json<GenerateTotpSecretResponse>> {
|
2024-04-16 12:48:15 +00:00
|
|
|
let site_view = SiteView::read_local(&mut context.pool())
|
|
|
|
.await?
|
|
|
|
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
|
2023-09-20 14:49:54 +00:00
|
|
|
|
|
|
|
if local_user_view.local_user.totp_2fa_enabled {
|
|
|
|
return Err(LemmyErrorType::TotpAlreadyEnabled)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
let secret = generate_totp_2fa_secret();
|
|
|
|
let secret_url =
|
|
|
|
build_totp_2fa(&site_view.site.name, &local_user_view.person.name, &secret)?.get_url();
|
|
|
|
|
|
|
|
let local_user_form = LocalUserUpdateForm {
|
|
|
|
totp_2fa_secret: Some(Some(secret)),
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
LocalUser::update(
|
|
|
|
&mut context.pool(),
|
|
|
|
local_user_view.local_user.id,
|
|
|
|
&local_user_form,
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
Ok(Json(GenerateTotpSecretResponse {
|
2024-05-17 00:41:57 +00:00
|
|
|
totp_secret_url: secret_url.into(),
|
2023-09-20 14:49:54 +00:00
|
|
|
}))
|
|
|
|
}
|