mod endpoints;
mod error;
mod model;
pub mod totp;
use fastauth_core::plugin_prelude::*;
use fastauth_core::{ApiResponse, routes::Status};
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
pub use endpoints::{
BackupCodesOutput, Disable, Enable, EnableInput, EnableOutput, GenerateBackupCodes, GetTotpUri,
PasswordInput, SendOtp, TotpUriOutput, VerifyBackupCode, VerifyInput, VerifyOtp, VerifyOutput,
VerifyTotp,
};
pub use error::TwoFactorError;
pub use model::{TwoFactorRow, TwoFactorUser};
const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
#[derive(Clone, Debug)]
pub struct TwoFactor {
issuer: Option<String>,
digits: u32,
period: u32,
backup_codes: usize,
skip_verification_on_enable: bool,
trust_device_for: Duration,
two_factor_cookie_max_age: Duration,
}
impl Default for TwoFactor {
fn default() -> Self {
Self {
issuer: None,
digits: 6,
period: 30,
backup_codes: 10,
skip_verification_on_enable: false,
trust_device_for: Duration::days(30),
two_factor_cookie_max_age: Duration::minutes(10),
}
}
}
impl TwoFactor {
pub fn new() -> Self {
Self::default()
}
pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
self.issuer = Some(issuer.into());
self
}
pub fn digits(mut self, digits: u32) -> Self {
assert!((6..=8).contains(&digits), "TOTP codes have 6 to 8 digits");
self.digits = digits;
self
}
pub fn period(mut self, seconds: u32) -> Self {
assert!(seconds > 0, "a TOTP period is at least one second");
self.period = seconds;
self
}
pub fn backup_codes(mut self, count: usize) -> Self {
self.backup_codes = count;
self
}
pub fn skip_verification_on_enable(mut self, skip: bool) -> Self {
self.skip_verification_on_enable = skip;
self
}
pub fn trust_device_for(mut self, duration: Duration) -> Self {
self.trust_device_for = duration;
self
}
pub fn two_factor_cookie_max_age(mut self, max_age: Duration) -> Self {
self.two_factor_cookie_max_age = max_age;
self
}
fn totp_uri(
&self,
app_name: &str,
issuer: Option<&str>,
account: &str,
secret: &[u8],
) -> String {
let issuer = issuer.or(self.issuer.as_deref()).unwrap_or(app_name);
let issuer = utf8_percent_encode(issuer, URI_COMPONENT);
format!(
"otpauth://totp/{issuer}:{}?secret={}&issuer={issuer}&digits={}&period={}",
utf8_percent_encode(account, URI_COMPONENT),
totp::base32(secret),
self.digits,
self.period
)
}
}
impl Plugin for TwoFactor {
const ID: &'static str = "two-factor";
type Requires = ();
type UserFields = TwoFactorUser;
type SessionFields = ();
fn schema(&self, schema: &mut SchemaBuilder) {
schema.model::<TwoFactorRow>();
}
fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
app.endpoint(Enable(self.clone()))
.endpoint(Disable)
.endpoint(GetTotpUri(self.clone()))
.endpoint(VerifyTotp(self.clone()))
.endpoint(SendOtp)
.endpoint(VerifyOtp(self.clone()))
.endpoint(GenerateBackupCodes(self.clone()))
.endpoint(VerifyBackupCode(self.clone()))
.rate_limit("/two-factor/verify-*", Limit::per(Duration::minutes(1), 5))
.errors::<TwoFactorError>();
let plugin = self.clone();
app.sign_in_gate(move |ctx, attempt| {
let plugin = plugin.clone();
async move { endpoints::gate(&plugin, ctx, attempt).await }
});
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TwoFactorEnabled {
pub user_id: Id,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TwoFactorDisabled {
pub user_id: Id,
}
impl Event for TwoFactorEnabled {}
impl Event for TwoFactorDisabled {}
pub trait TwoFactorExt: AuthInstance + Sized {
fn two_factor<I>(&self) -> TwoFactorApi<'_, Self>
where
Self: HasPlugin<TwoFactor, I>,
{
TwoFactorApi {
auth: self,
plugin: self.plugin_arc().clone(),
}
}
}
impl<A: AuthInstance> TwoFactorExt for A {}
pub struct TwoFactorApi<'a, A> {
auth: &'a A,
plugin: Arc<TwoFactor>,
}
impl<A: AuthInstance> TwoFactorApi<'_, A> {
pub async fn enable(
&self,
headers: &HeaderMap,
input: EnableInput,
) -> Result<ApiResponse<EnableOutput>, AuthError> {
self.auth
.api()
.headers(headers)
.call(&Enable(self.plugin.clone()), input)
.await
}
pub async fn disable(
&self,
headers: &HeaderMap,
input: PasswordInput,
) -> Result<ApiResponse<Status>, AuthError> {
self.auth.api().headers(headers).call(&Disable, input).await
}
pub async fn verify_totp(
&self,
headers: &HeaderMap,
input: VerifyInput,
) -> Result<ApiResponse<VerifyOutput>, AuthError> {
self.auth
.api()
.headers(headers)
.call(&VerifyTotp(self.plugin.clone()), input)
.await
}
}