updated api to create totp struct, get totp secret directly if it exists

This commit is contained in:
Philippe Loctaux 2023-05-01 11:48:57 +02:00
parent e70d035c86
commit f891d2f940
4 changed files with 18 additions and 20 deletions

View file

@ -34,7 +34,7 @@ pub async fn user_settings_security(
let page = Page::UserSecuritySettings(super::content::UserSecuritySettings {
user: jwt_user.0,
logout_time_effective: JWT_DURATION_MINUTES,
totp_enabled: user.is_totp_enabled(),
totp_enabled: user.totp_secret().is_some(),
});
Ok(flash
@ -261,7 +261,7 @@ pub async fn user_settings_security_totp(
let totp = totp::new(
totp::secret_to_bytes(&secret)?,
issuer,
Some(issuer),
jwt_user.0.username.to_string(),
)?;
@ -305,7 +305,7 @@ pub async fn user_settings_security_totp_form(
// Get settings
let settings = Settings::get(&mut transaction).await?;
// Get issuer
// Get totp issuer
let issuer = settings
.url()
.map(Url::parse)
@ -316,7 +316,7 @@ pub async fn user_settings_security_totp_form(
transaction.commit().await?;
if disable {
return match user.is_totp_enabled() {
return match user.totp_secret().is_some() {
true => {
// Delete secret and backup
let mut transaction = db.begin().await?;
@ -340,7 +340,7 @@ pub async fn user_settings_security_totp_form(
};
}
if enable && user.is_totp_enabled() {
if enable && user.totp_secret().is_some() {
return Ok(Flash::new(
Redirect::to(uri!(user_settings_security)),
FlashKind::Warning,
@ -355,7 +355,11 @@ pub async fn user_settings_security_totp_form(
let totp_secret = totp::secret_to_bytes(&secret)?;
let totp = totp::new(totp_secret.clone(), issuer, user.username().to_string())?;
let totp = totp::new(
totp_secret.clone(),
Some(issuer),
user.username().to_string(),
)?;
if let Some(token) = form.token {
return if totp.check_current(token)? {

View file

@ -14,17 +14,8 @@ pub enum Error {
Secret(String),
}
pub fn new(secret: Vec<u8>, issuer: String, account_name: String) -> Result<TOTP, Error> {
TOTP::new(
Algorithm::SHA1,
6,
1,
30,
secret,
Some(issuer),
account_name,
)
.map_err(Error::Url)
pub fn new(secret: Vec<u8>, issuer: Option<String>, account_name: String) -> Result<TOTP, Error> {
TOTP::new(Algorithm::SHA1, 6, 1, 30, secret, issuer, account_name).map_err(Error::Url)
}
pub fn secret_to_bytes(secret: &Secret) -> Result<Vec<u8>, Error> {

View file

@ -50,7 +50,10 @@ impl User {
)
}
async fn get_by_id(conn: impl SqliteExecutor<'_>, id: &UserID) -> Result<Option<Self>, Error> {
pub async fn get_by_id(
conn: impl SqliteExecutor<'_>,
id: &UserID,
) -> Result<Option<Self>, Error> {
Ok(DatabaseUsers::get_one_by_id(conn, &id.0)
.await?
.map(Self::from))

View file

@ -57,7 +57,7 @@ impl User {
pub fn paper_key_hashed(&self) -> Option<&str> {
self.paper_key.as_deref()
}
pub fn is_totp_enabled(&self) -> bool {
self.totp_secret.is_some()
pub fn totp_secret(&self) -> Option<Vec<u8>> {
self.totp_secret.clone()
}
}