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