fastauth_plugin_two_factor/
lib.rs1mod endpoints;
43mod error;
44mod model;
45pub mod totp;
46
47use fastauth_core::plugin_prelude::*;
48use fastauth_core::{ApiResponse, routes::Status};
49use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
50
51pub use endpoints::{
52 BackupCodesOutput, Disable, Enable, EnableInput, EnableOutput, GenerateBackupCodes, GetTotpUri,
53 PasswordInput, SendOtp, TotpUriOutput, VerifyBackupCode, VerifyInput, VerifyOtp, VerifyOutput,
54 VerifyTotp,
55};
56pub use error::TwoFactorError;
57pub use model::{TwoFactorRow, TwoFactorUser};
58
59const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
60 .remove(b'-')
61 .remove(b'.')
62 .remove(b'_')
63 .remove(b'~');
64
65#[derive(Clone, Debug)]
67pub struct TwoFactor {
68 issuer: Option<String>,
69 digits: u32,
70 period: u32,
71 backup_codes: usize,
72 skip_verification_on_enable: bool,
73 trust_device_for: Duration,
74 two_factor_cookie_max_age: Duration,
75}
76
77impl Default for TwoFactor {
78 fn default() -> Self {
79 Self {
80 issuer: None,
81 digits: 6,
82 period: 30,
83 backup_codes: 10,
84 skip_verification_on_enable: false,
85 trust_device_for: Duration::days(30),
86 two_factor_cookie_max_age: Duration::minutes(10),
87 }
88 }
89}
90
91impl TwoFactor {
92 pub fn new() -> Self {
93 Self::default()
94 }
95
96 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
98 self.issuer = Some(issuer.into());
99 self
100 }
101
102 pub fn digits(mut self, digits: u32) -> Self {
104 assert!((6..=8).contains(&digits), "TOTP codes have 6 to 8 digits");
105 self.digits = digits;
106 self
107 }
108
109 pub fn period(mut self, seconds: u32) -> Self {
111 assert!(seconds > 0, "a TOTP period is at least one second");
112 self.period = seconds;
113 self
114 }
115
116 pub fn backup_codes(mut self, count: usize) -> Self {
118 self.backup_codes = count;
119 self
120 }
121
122 pub fn skip_verification_on_enable(mut self, skip: bool) -> Self {
124 self.skip_verification_on_enable = skip;
125 self
126 }
127
128 pub fn trust_device_for(mut self, duration: Duration) -> Self {
130 self.trust_device_for = duration;
131 self
132 }
133
134 pub fn two_factor_cookie_max_age(mut self, max_age: Duration) -> Self {
136 self.two_factor_cookie_max_age = max_age;
137 self
138 }
139
140 fn totp_uri(
141 &self,
142 app_name: &str,
143 issuer: Option<&str>,
144 account: &str,
145 secret: &[u8],
146 ) -> String {
147 let issuer = issuer.or(self.issuer.as_deref()).unwrap_or(app_name);
148 let issuer = utf8_percent_encode(issuer, URI_COMPONENT);
149 format!(
150 "otpauth://totp/{issuer}:{}?secret={}&issuer={issuer}&digits={}&period={}",
151 utf8_percent_encode(account, URI_COMPONENT),
152 totp::base32(secret),
153 self.digits,
154 self.period
155 )
156 }
157}
158
159impl Plugin for TwoFactor {
160 const ID: &'static str = "two-factor";
161 type Requires = ();
162 type UserFields = TwoFactorUser;
163 type SessionFields = ();
164
165 fn schema(&self, schema: &mut SchemaBuilder) {
166 schema.model::<TwoFactorRow>();
167 }
168
169 fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
170 app.endpoint(Enable(self.clone()))
171 .endpoint(Disable)
172 .endpoint(GetTotpUri(self.clone()))
173 .endpoint(VerifyTotp(self.clone()))
174 .endpoint(SendOtp)
175 .endpoint(VerifyOtp(self.clone()))
176 .endpoint(GenerateBackupCodes(self.clone()))
177 .endpoint(VerifyBackupCode(self.clone()))
178 .rate_limit("/two-factor/verify-*", Limit::per(Duration::minutes(1), 5))
179 .errors::<TwoFactorError>();
180 let plugin = self.clone();
181 app.sign_in_gate(move |ctx, attempt| {
182 let plugin = plugin.clone();
183 async move { endpoints::gate(&plugin, ctx, attempt).await }
184 });
185 }
186}
187
188#[derive(Clone, Debug, PartialEq, Eq)]
190pub struct TwoFactorEnabled {
191 pub user_id: Id,
192}
193
194#[derive(Clone, Debug, PartialEq, Eq)]
196pub struct TwoFactorDisabled {
197 pub user_id: Id,
198}
199
200impl Event for TwoFactorEnabled {}
201impl Event for TwoFactorDisabled {}
202
203pub trait TwoFactorExt: AuthInstance + Sized {
205 fn two_factor<I>(&self) -> TwoFactorApi<'_, Self>
206 where
207 Self: HasPlugin<TwoFactor, I>,
208 {
209 TwoFactorApi {
210 auth: self,
211 plugin: self.plugin_arc().clone(),
212 }
213 }
214}
215
216impl<A: AuthInstance> TwoFactorExt for A {}
217
218pub struct TwoFactorApi<'a, A> {
221 auth: &'a A,
222 plugin: Arc<TwoFactor>,
223}
224
225impl<A: AuthInstance> TwoFactorApi<'_, A> {
226 pub async fn enable(
228 &self,
229 headers: &HeaderMap,
230 input: EnableInput,
231 ) -> Result<ApiResponse<EnableOutput>, AuthError> {
232 self.auth
233 .api()
234 .headers(headers)
235 .call(&Enable(self.plugin.clone()), input)
236 .await
237 }
238
239 pub async fn disable(
241 &self,
242 headers: &HeaderMap,
243 input: PasswordInput,
244 ) -> Result<ApiResponse<Status>, AuthError> {
245 self.auth.api().headers(headers).call(&Disable, input).await
246 }
247
248 pub async fn verify_totp(
251 &self,
252 headers: &HeaderMap,
253 input: VerifyInput,
254 ) -> Result<ApiResponse<VerifyOutput>, AuthError> {
255 self.auth
256 .api()
257 .headers(headers)
258 .call(&VerifyTotp(self.plugin.clone()), input)
259 .await
260 }
261}