totp: new crate, sql migration + queries, enable totp page, save secret in database
This commit is contained in:
parent
cb46556717
commit
233e26520c
26 changed files with 1116 additions and 364 deletions
|
|
@ -27,4 +27,5 @@ jwt = { path = "../jwt" }
|
|||
apps = { path = "../apps" }
|
||||
authorization_codes = { path = "../authorization_codes" }
|
||||
refresh_tokens = { path = "../refresh_tokens" }
|
||||
email = { path = "../email" }
|
||||
email = { path = "../email" }
|
||||
totp = { path = "../totp" }
|
||||
|
|
|
|||
|
|
@ -86,3 +86,23 @@ impl From<refresh_tokens::Error> for Error {
|
|||
Error::internal_server_error(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<totp::Error> for Error {
|
||||
fn from(e: totp::Error) -> Self {
|
||||
Error::internal_server_error(e)
|
||||
}
|
||||
}
|
||||
|
||||
// std Types
|
||||
|
||||
impl From<String> for Error {
|
||||
fn from(e: String) -> Self {
|
||||
Error::internal_server_error(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::time::SystemTimeError> for Error {
|
||||
fn from(e: std::time::SystemTimeError) -> Self {
|
||||
Error::internal_server_error(e)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ pub enum Page {
|
|||
AdminUsersList(AdminUsersList),
|
||||
ForgotPassword,
|
||||
ResetPassword(ResetPassword),
|
||||
UserSecurityTotp(UserSecurityTotp),
|
||||
}
|
||||
|
||||
impl Page {
|
||||
|
|
@ -50,6 +51,7 @@ impl Page {
|
|||
Page::AdminUsersList(_) => "pages/admin/users/list",
|
||||
Page::ForgotPassword => "pages/forgot-password",
|
||||
Page::ResetPassword(_) => "pages/reset-password",
|
||||
Page::UserSecurityTotp(_) => "pages/settings/totp",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -73,6 +75,7 @@ impl Page {
|
|||
Page::AdminUsersList(_) => "Users",
|
||||
Page::ForgotPassword => "Forgot password",
|
||||
Page::ResetPassword(_) => "Reset password",
|
||||
Page::UserSecurityTotp(_) => "Enable One-time password",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -98,6 +101,7 @@ impl Page {
|
|||
Page::AdminUsersList(_) => Some(AdminMenu::Users.into()),
|
||||
Page::ForgotPassword => None,
|
||||
Page::ResetPassword(_) => None,
|
||||
Page::UserSecurityTotp(_) => Some(UserMenu::Settings.into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -121,6 +125,7 @@ impl Page {
|
|||
Page::AdminUsersList(list) => Box::new(list),
|
||||
Page::ForgotPassword => Box::new(()),
|
||||
Page::ResetPassword(reset) => Box::new(reset),
|
||||
Page::UserSecurityTotp(totp) => Box::new(totp),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ pub fn routes() -> Vec<Route> {
|
|||
user_settings_security_logout_everywhere,
|
||||
user_settings_security_paper_key,
|
||||
user_settings_security_password,
|
||||
user_settings_security_totp,
|
||||
user_settings_security_totp_form,
|
||||
user_settings_visual,
|
||||
]
|
||||
}
|
||||
|
|
@ -49,6 +51,7 @@ pub mod content {
|
|||
pub struct UserSecuritySettings {
|
||||
pub user: JwtClaims,
|
||||
pub logout_time_effective: i64,
|
||||
pub totp_enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -57,4 +60,13 @@ pub mod content {
|
|||
pub struct UserVisualSettings {
|
||||
pub user: JwtClaims,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
#[derive(Clone)]
|
||||
pub struct UserSecurityTotp {
|
||||
pub user: JwtClaims,
|
||||
pub qr: String,
|
||||
pub url: String,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,16 +13,28 @@ use rocket::time::Duration;
|
|||
use rocket::{get, post};
|
||||
use settings::Settings;
|
||||
use std::net::IpAddr;
|
||||
use url::Url;
|
||||
use users::User;
|
||||
|
||||
#[get("/settings/security")]
|
||||
pub async fn user_settings_security(
|
||||
mut db: Connection<Database>,
|
||||
jwt_user: JwtUser,
|
||||
flash: Option<FlashMessage<'_>>,
|
||||
) -> Result<Template> {
|
||||
let mut transaction = db.begin().await?;
|
||||
|
||||
// Get user info
|
||||
let user = User::get_by_login(&mut transaction, &jwt_user.0.subject)
|
||||
.await?
|
||||
.ok_or_else(|| Error::not_found("Could not find user"))?;
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
let page = Page::UserSecuritySettings(super::content::UserSecuritySettings {
|
||||
user: jwt_user.0,
|
||||
logout_time_effective: JWT_DURATION_MINUTES,
|
||||
totp_enabled: user.is_totp_enabled(),
|
||||
});
|
||||
|
||||
Ok(flash
|
||||
|
|
@ -216,3 +228,173 @@ pub async fn user_settings_security_password(
|
|||
flash_message,
|
||||
))
|
||||
}
|
||||
|
||||
const TOTP_COOKIE_NAME: &str = "totp";
|
||||
|
||||
#[get("/settings/security/totp")]
|
||||
pub async fn user_settings_security_totp(
|
||||
jwt_user: JwtUser,
|
||||
mut db: Connection<Database>,
|
||||
flash: Option<FlashMessage<'_>>,
|
||||
cookie_jar: &CookieJar<'_>,
|
||||
) -> Result<Template> {
|
||||
let mut transaction = db.begin().await?;
|
||||
|
||||
// Get settings
|
||||
let settings = Settings::get(&mut transaction).await?;
|
||||
|
||||
// Get issuer
|
||||
let issuer = settings
|
||||
.url()
|
||||
.map(Url::parse)
|
||||
.transpose()?
|
||||
.and_then(|url| url.host_str().map(|res| res.to_string()))
|
||||
.ok_or_else(|| Error::internal_server_error("Failed to get issuer for totp"))?;
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
// Get secret from cookie
|
||||
let secret = cookie_jar
|
||||
.get(TOTP_COOKIE_NAME)
|
||||
.map(|cookie| totp::Secret::Encoded(cookie.value().into()))
|
||||
.ok_or_else(|| Error::internal_server_error("Failed to get totp secret"))?;
|
||||
|
||||
let totp = totp::new(
|
||||
totp::secret_to_bytes(&secret)?,
|
||||
issuer,
|
||||
jwt_user.0.username.to_string(),
|
||||
)?;
|
||||
|
||||
let totp_for_qr = totp.clone();
|
||||
|
||||
let page = Page::UserSecurityTotp(super::content::UserSecurityTotp {
|
||||
user: jwt_user.0,
|
||||
qr: task::spawn_blocking(move || totp_for_qr.get_qr()).await??,
|
||||
url: totp.get_url(),
|
||||
});
|
||||
|
||||
Ok(flash
|
||||
.map(|flash| Page::with_flash(page.clone(), flash))
|
||||
.unwrap_or_else(|| page.into()))
|
||||
}
|
||||
|
||||
#[derive(Debug, FromForm)]
|
||||
pub struct TotpForm<'r> {
|
||||
pub enable: Option<&'r str>,
|
||||
pub disable: Option<&'r str>,
|
||||
pub token: Option<&'r str>,
|
||||
}
|
||||
|
||||
#[post("/settings/security/totp", data = "<form>")]
|
||||
pub async fn user_settings_security_totp_form(
|
||||
mut db: Connection<Database>,
|
||||
jwt_user: JwtUser,
|
||||
form: Form<TotpForm<'_>>,
|
||||
cookie_jar: &CookieJar<'_>,
|
||||
) -> Result<Flash<Redirect>> {
|
||||
let enable = matches!(form.enable, Some("true"));
|
||||
let disable = matches!(form.disable, Some("true"));
|
||||
|
||||
let mut transaction = db.begin().await?;
|
||||
|
||||
// Get user info
|
||||
let user = User::get_by_login(&mut transaction, &jwt_user.0.subject)
|
||||
.await?
|
||||
.ok_or_else(|| Error::not_found("Could not find user"))?;
|
||||
|
||||
// Get settings
|
||||
let settings = Settings::get(&mut transaction).await?;
|
||||
|
||||
// Get issuer
|
||||
let issuer = settings
|
||||
.url()
|
||||
.map(Url::parse)
|
||||
.transpose()?
|
||||
.and_then(|url| url.host_str().map(|res| res.to_string()))
|
||||
.ok_or_else(|| Error::not_found("Failed to get issuer for totp"))?;
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
if disable {
|
||||
return match user.is_totp_enabled() {
|
||||
true => {
|
||||
// Delete secret and backup
|
||||
let mut transaction = db.begin().await?;
|
||||
|
||||
user.set_totp_secret(&mut transaction, None).await?;
|
||||
user.set_totp_backup(&mut transaction, None).await?;
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
Ok(Flash::new(
|
||||
Redirect::to(uri!(user_settings_security)),
|
||||
FlashKind::Success,
|
||||
"One-time password has been disabled.",
|
||||
))
|
||||
}
|
||||
false => Ok(Flash::new(
|
||||
Redirect::to(uri!(user_settings_security)),
|
||||
FlashKind::Warning,
|
||||
"One-time password is not enabled.",
|
||||
)),
|
||||
};
|
||||
}
|
||||
|
||||
if enable && user.is_totp_enabled() {
|
||||
return Ok(Flash::new(
|
||||
Redirect::to(uri!(user_settings_security)),
|
||||
FlashKind::Warning,
|
||||
"One-time password is already enabled.",
|
||||
));
|
||||
}
|
||||
|
||||
let secret = match cookie_jar.get(TOTP_COOKIE_NAME) {
|
||||
Some(cookie) => totp::Secret::Encoded(cookie.value().into()),
|
||||
None => task::spawn_blocking(totp::Secret::generate_secret).await?,
|
||||
};
|
||||
|
||||
let totp_secret = totp::secret_to_bytes(&secret)?;
|
||||
|
||||
let totp = totp::new(totp_secret.clone(), issuer, user.username().to_string())?;
|
||||
|
||||
if let Some(token) = form.token {
|
||||
return if totp.check_current(token)? {
|
||||
let mut transaction = db.begin().await?;
|
||||
|
||||
user.set_totp_secret(&mut transaction, Some(&totp_secret))
|
||||
.await?;
|
||||
user.set_totp_backup(&mut transaction, None).await?;
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
// Remove cookie
|
||||
cookie_jar.remove(Cookie::named(TOTP_COOKIE_NAME));
|
||||
|
||||
Ok(Flash::new(
|
||||
Redirect::to(uri!(user_settings_security)),
|
||||
FlashKind::Success,
|
||||
"One-time password has been saved.",
|
||||
))
|
||||
} else {
|
||||
Ok(Flash::new(
|
||||
Redirect::to(uri!(user_settings_security_totp)),
|
||||
FlashKind::Danger,
|
||||
"Wrong code. Please try again.",
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
// Store secret in cookie, used when refreshing page, or on invalid verification
|
||||
let mut cookie = Cookie::new(TOTP_COOKIE_NAME, totp.get_secret_base32());
|
||||
cookie.set_secure(true);
|
||||
cookie.set_http_only(true);
|
||||
cookie.set_same_site(SameSite::Strict);
|
||||
cookie.set_max_age(Duration::minutes(15));
|
||||
cookie_jar.add(cookie);
|
||||
|
||||
Ok(Flash::new(
|
||||
Redirect::to(uri!(user_settings_security_totp)),
|
||||
FlashKind::Success,
|
||||
"One-time password has been generated.",
|
||||
))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,6 +51,26 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<!-- One-time password -->
|
||||
<div class="mb-4">
|
||||
<h3 class="card-title">One-time password (2FA)</h3>
|
||||
<p class="card-subtitle">
|
||||
Protect your account by requiring an additional code when you log in.</p>
|
||||
<div>
|
||||
{% if totp_enabled %}
|
||||
<a class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#modal-disable-totp">
|
||||
Disable OTP
|
||||
</a>
|
||||
{% else %}
|
||||
<form action="./security/totp" method="post">
|
||||
<button type="submit" name="enable" value="true" class="btn">
|
||||
Enable OTP
|
||||
</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Paper key -->
|
||||
<div class="mb-4">
|
||||
<h3 class="card-title">Paper key</h3>
|
||||
|
|
@ -207,4 +227,50 @@
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Disable totp modal -->
|
||||
<div class="modal modal-blur" tabindex="-1" id="modal-disable-totp">
|
||||
<div class="modal-dialog modal-sm modal-dialog-centered" role="document">
|
||||
<div class="modal-content">
|
||||
|
||||
<div class="modal-status bg-danger"></div>
|
||||
|
||||
<div class="modal-body text-center py-4">
|
||||
|
||||
<div class="text-danger mb-2">
|
||||
{% include "icons/alert-triangle-large" %}
|
||||
</div>
|
||||
|
||||
<h3>Do you want to disable One-time password?</h3>
|
||||
<div class="mt-2">This will also delete your backup code.</div>
|
||||
<div class="mt-2">
|
||||
You will not need to enter a code when you log in, but this makes your account less secure.
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<div class="w-100">
|
||||
<div class="row">
|
||||
|
||||
<div class="col">
|
||||
<a href="#" class="btn w-100" data-bs-dismiss="modal">Cancel</a>
|
||||
</div>
|
||||
|
||||
<div class="col">
|
||||
<form action="./security/totp" method="post">
|
||||
<button type="submit" name="disable" value="true" class="btn btn-danger w-100">
|
||||
Disable OTP
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock content %}
|
||||
|
|
|
|||
70
crates/ezidam/templates/pages/settings/totp.html.tera
Normal file
70
crates/ezidam/templates/pages/settings/totp.html.tera
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
{% extends "shell" %}
|
||||
|
||||
{% block content %}
|
||||
<!-- Page header -->
|
||||
<div class="page-header d-print-none">
|
||||
<div class="container-xl">
|
||||
<div class="row g-2 align-items-center">
|
||||
<div class="col">
|
||||
<h2 class="page-title">
|
||||
Enable One-time password
|
||||
</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Page body -->
|
||||
<div class="page-body">
|
||||
<div class="container-xl">
|
||||
|
||||
{% if flash %}
|
||||
<div class="alert alert-{{flash.0}}" role="alert">
|
||||
<h4 class="alert-title">{{ flash.1 | safe }}</h4>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h2 class="mb-4">Confirm One-time password</h2>
|
||||
|
||||
<div>
|
||||
On your device, add your one-time password by adding the following url
|
||||
or by scanning the qr code bellow:
|
||||
</div>
|
||||
|
||||
<div class="mt-2"><strong>{{ url }}</strong></div>
|
||||
|
||||
{% set base_64_qr = "data:image/png;base64," ~ qr %}
|
||||
<img class="my-4" src="{{ base_64_qr }}" alt="qr code to add one-time password">
|
||||
|
||||
<div class="mt-2">
|
||||
Please keep the url or the qr code safely, it will be only shown once!
|
||||
</div>
|
||||
<div class="mt-2">
|
||||
If you lose it <strong>you will not be able to access your account</strong>!
|
||||
</div>
|
||||
|
||||
<form action="" method="post" class="mt-4">
|
||||
<label class="form-label required" for="token">Enter the code displayed on your device</label>
|
||||
<input
|
||||
class="form-control"
|
||||
type="text"
|
||||
name="token"
|
||||
id="token"
|
||||
inputmode="numeric"
|
||||
pattern="[0-9]*"
|
||||
autocomplete="one-time-code"
|
||||
required
|
||||
>
|
||||
|
||||
<button type="submit" name="enable" value="true" class="mt-2 btn btn-primary">
|
||||
Enable OTP
|
||||
</button>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock content %}
|
||||
Loading…
Add table
Add a link
Reference in a new issue