rustauth 0.2.0

Rust authentication toolkit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Public RustAuth initializer.

use rustauth_core::api::{
    core_auth_async_endpoints, core_endpoints, ApiRequest, ApiResponse, AsyncAuthEndpoint,
    AuthEndpoint, AuthRouter, EndpointInfo,
};
#[cfg(feature = "telemetry")]
use rustauth_core::context::ContextTelemetryEvent;
use rustauth_core::context::{create_auth_context, create_auth_context_with_adapter, AuthContext};
use rustauth_core::db::{DbAdapter, JoinAdapter, SchemaCreation};
use rustauth_core::error::RustAuthError;
use rustauth_core::options::{DeploymentMode, RustAuthOptions};
#[cfg(feature = "telemetry")]
use rustauth_telemetry::{create_telemetry, TelemetryContext, TelemetryEvent};
use std::sync::Arc;

pub use rustauth_core::auth::oauth;

/// Initialized RustAuth instance.
#[derive(Clone)]
pub struct RustAuth {
    router: AuthRouter,
    options: RustAuthOptions,
    context: AuthContext,
    adapter: Option<Arc<dyn DbAdapter>>,
}

impl RustAuth {
    /// Start an [`RustAuthBuilder`] using default [`RustAuthOptions`].
    pub fn builder() -> RustAuthBuilder {
        RustAuthBuilder::new()
    }

    /// Handle a request through the synchronous endpoint router.
    ///
    /// This is useful for endpoint sets that do not require async database or
    /// network work. Most adapter-backed applications should use
    /// [`RustAuth::handler_async`].
    pub fn handler(&self, request: ApiRequest) -> Result<ApiResponse, RustAuthError> {
        self.router.handle(request)
    }

    /// Handle a request through the async endpoint router.
    pub async fn handler_async(&self, request: ApiRequest) -> Result<ApiResponse, RustAuthError> {
        self.router.handle_async(request).await
    }

    /// Return the effective options used to build this instance.
    pub fn options(&self) -> &RustAuthOptions {
        &self.options
    }

    /// Return the initialized authentication context.
    pub fn context(&self) -> &AuthContext {
        &self.context
    }

    /// Return metadata for all registered endpoints.
    pub fn endpoint_registry(&self) -> Vec<EndpointInfo> {
        self.router.endpoint_registry()
    }

    /// Generate the OpenAPI schema for the registered endpoint surface.
    pub fn openapi_schema(&self) -> serde_json::Value {
        self.router.openapi_schema()
    }

    /// Create the database schema for this instance.
    ///
    /// Returns an error when the instance was created without an adapter.
    /// When `file` is provided, adapter implementations may write migration
    /// SQL to that path and return adapter-specific creation metadata.
    pub async fn create_schema(
        &self,
        file: Option<&str>,
    ) -> Result<Option<SchemaCreation>, RustAuthError> {
        let adapter = self.adapter.as_ref().ok_or_else(|| {
            RustAuthError::InvalidConfig(
                "RustAuth::create_schema requires an adapter-backed instance".to_owned(),
            )
        })?;
        adapter.create_schema(&self.context.db_schema, file).await
    }

    #[cfg(feature = "telemetry")]
    /// Publish a telemetry event through the initialized context publisher.
    pub async fn publish_telemetry(&self, event: ContextTelemetryEvent) {
        self.context.publish_telemetry(event).await;
    }
}

/// Builder for constructing an [`RustAuth`] instance.
///
/// The builder mirrors common [`RustAuthOptions`] setters and can also attach
/// database adapters, plugins, social providers, and custom endpoints.
#[derive(Default)]
pub struct RustAuthBuilder {
    options: RustAuthOptions,
    adapter: Option<Arc<dyn DbAdapter>>,
    extra_endpoints: Vec<AuthEndpoint>,
    async_endpoints: Vec<AsyncAuthEndpoint>,
    #[cfg(feature = "telemetry")]
    telemetry_context: Option<TelemetryContext>,
}

impl RustAuthBuilder {
    /// Create a builder with default options and no adapter.
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    /// Replace all options used by the builder.
    pub fn options(mut self, options: RustAuthOptions) -> Self {
        self.options = options;
        self
    }

    #[must_use]
    /// Set the public base URL used for redirects, cookies, and generated URLs.
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.options = self.options.base_url(base_url);
        self
    }

    #[must_use]
    /// Set the URL path prefix for auth endpoints.
    pub fn base_path(mut self, base_path: impl Into<String>) -> Self {
        self.options = self.options.base_path(base_path);
        self
    }

    #[must_use]
    /// Set the primary application secret.
    pub fn secret(mut self, secret: impl Into<String>) -> Self {
        self.options = self.options.secret(secret);
        self
    }

    #[must_use]
    /// Replace rate limit configuration.
    pub fn rate_limit(mut self, rate_limit: rustauth_core::options::RateLimitOptions) -> Self {
        self.options = self.options.rate_limit(rate_limit);
        self
    }

    #[must_use]
    /// Replace session configuration.
    pub fn session(mut self, session: rustauth_core::options::SessionOptions) -> Self {
        self.options = self.options.session(session);
        self
    }

    #[must_use]
    /// Replace user model and lifecycle configuration.
    pub fn user(mut self, user: rustauth_core::options::UserOptions) -> Self {
        self.options = self.options.user(user);
        self
    }

    #[must_use]
    /// Replace password authentication configuration.
    pub fn password(mut self, password: rustauth_core::options::PasswordOptions) -> Self {
        self.options = self.options.password(password);
        self
    }

    #[must_use]
    /// Replace email/password sign-in and sign-up configuration.
    pub fn email_password(
        mut self,
        email_password: rustauth_core::options::EmailPasswordOptions,
    ) -> Self {
        self.options = self.options.email_password(email_password);
        self
    }

    #[must_use]
    /// Replace account linking and account model configuration.
    pub fn account(mut self, account: rustauth_core::options::AccountOptions) -> Self {
        self.options = self.options.account(account);
        self
    }

    #[must_use]
    /// Replace advanced runtime configuration.
    pub fn advanced(mut self, advanced: rustauth_core::options::AdvancedOptions) -> Self {
        self.options = self.options.advanced(advanced);
        self
    }

    #[must_use]
    /// Enable or disable production-mode behavior.
    pub fn production(mut self, production: bool) -> Self {
        self.options = self.options.production(production);
        self
    }

    #[must_use]
    /// Enable or disable development-mode behavior.
    pub fn development(mut self, development: bool) -> Self {
        self.options = self.options.development(development);
        self
    }

    #[must_use]
    /// Set deployment posture explicitly.
    pub fn deployment_mode(mut self, mode: DeploymentMode) -> Self {
        self.options = self.options.deployment_mode(mode);
        self
    }

    #[must_use]
    /// Replace telemetry configuration.
    pub fn telemetry(mut self, telemetry: rustauth_core::options::TelemetryOptions) -> Self {
        self.options = self.options.telemetry(telemetry);
        self
    }

    #[must_use]
    /// Register an RustAuth plugin.
    pub fn plugin(mut self, plugin: rustauth_core::plugin::AuthPlugin) -> Self {
        self.options = self.options.plugin(plugin);
        self
    }

    #[must_use]
    /// Register an RustAuth plugin (alias for [`Self::plugin`]).
    pub fn push_plugin(self, plugin: rustauth_core::plugin::AuthPlugin) -> Self {
        self.plugin(plugin)
    }

    #[must_use]
    /// Register multiple RustAuth plugins.
    ///
    /// Appends each plugin to the builder list, like chaining [`.plugin`](Self::plugin).
    /// For a full replacement list, use [`RustAuthOptions::set_plugins`].
    pub fn plugins(mut self, plugins: Vec<rustauth_core::plugin::AuthPlugin>) -> Self {
        self.options = self.options.plugins(plugins);
        self
    }

    #[must_use]
    /// Register multiple RustAuth plugins (alias for [`Self::plugins`]).
    pub fn extend_plugins(self, plugins: Vec<rustauth_core::plugin::AuthPlugin>) -> Self {
        self.plugins(plugins)
    }

    #[cfg(feature = "oauth")]
    #[must_use]
    /// Register a social OAuth provider.
    pub fn social_provider<P>(mut self, provider: P) -> Self
    where
        P: rustauth_core::oauth::oauth2::SocialOAuthProvider,
    {
        self.options = self.options.social_provider(provider);
        self
    }

    #[cfg(feature = "oauth")]
    #[must_use]
    /// Register multiple social OAuth providers.
    pub fn social_providers<I, P>(mut self, providers: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: rustauth_core::oauth::oauth2::SocialOAuthProvider + 'static,
    {
        self.options = self.options.social_providers(providers);
        self
    }

    #[cfg(feature = "oauth")]
    /// Register social OAuth providers built from fallible constructors.
    pub fn try_social_providers<I, P, E>(mut self, iter: I) -> Result<Self, E>
    where
        I: IntoIterator<Item = Result<P, E>>,
        P: rustauth_core::oauth::oauth2::SocialOAuthProvider + 'static,
        E: std::error::Error,
    {
        self.options = self.options.try_social_providers(iter)?;
        Ok(self)
    }

    #[must_use]
    /// Attach a database adapter by value.
    pub fn adapter<A>(mut self, adapter: A) -> Self
    where
        A: DbAdapter + 'static,
    {
        self.adapter = Some(Arc::new(adapter));
        self
    }

    #[must_use]
    /// Attach a shared database adapter.
    pub fn adapter_arc(mut self, adapter: Arc<dyn DbAdapter>) -> Self {
        self.adapter = Some(adapter);
        self
    }

    #[must_use]
    /// Add one synchronous endpoint to the router.
    pub fn endpoint(mut self, endpoint: AuthEndpoint) -> Self {
        self.extra_endpoints.push(endpoint);
        self
    }

    #[must_use]
    /// Add multiple synchronous endpoints to the router.
    pub fn endpoints(mut self, endpoints: Vec<AuthEndpoint>) -> Self {
        self.extra_endpoints.extend(endpoints);
        self
    }

    #[must_use]
    /// Add one async endpoint to the router.
    pub fn async_endpoint(mut self, endpoint: AsyncAuthEndpoint) -> Self {
        self.async_endpoints.push(endpoint);
        self
    }

    #[must_use]
    /// Add multiple async endpoints to the router.
    pub fn async_endpoints(mut self, endpoints: Vec<AsyncAuthEndpoint>) -> Self {
        self.async_endpoints.extend(endpoints);
        self
    }

    #[cfg(feature = "telemetry")]
    #[must_use]
    /// Provide telemetry initialization context for [`Self::build`].
    pub fn telemetry_context(mut self, context: TelemetryContext) -> Self {
        self.telemetry_context = Some(context);
        self
    }

    /// Build the configured [`RustAuth`] instance.
    ///
    /// When the `telemetry` feature is enabled, this also initializes the
    /// telemetry publisher before returning.
    pub async fn build(self) -> Result<RustAuth, RustAuthError> {
        if let Some(adapter) = self.adapter {
            build_with_adapter(
                self.options,
                adapter,
                self.extra_endpoints,
                self.async_endpoints,
                #[cfg(feature = "telemetry")]
                self.telemetry_context,
            )
            .await
        } else {
            build_without_adapter(
                self.options,
                self.extra_endpoints,
                self.async_endpoints,
                #[cfg(feature = "telemetry")]
                self.telemetry_context,
            )
            .await
        }
    }
}

async fn build_without_adapter(
    options: RustAuthOptions,
    extra_endpoints: Vec<AuthEndpoint>,
    async_endpoints: Vec<AsyncAuthEndpoint>,
    #[cfg(feature = "telemetry")] telemetry_context: Option<TelemetryContext>,
) -> Result<RustAuth, RustAuthError> {
    let context = create_auth_context(options.clone())?;
    let context = {
        #[cfg(feature = "telemetry")]
        {
            let mut context = context;
            attach_telemetry(
                &mut context,
                &options,
                telemetry_context.unwrap_or_default(),
            )
            .await;
            context
        }
        #[cfg(not(feature = "telemetry"))]
        {
            context
        }
    };
    let mut endpoints = core_endpoints();
    endpoints.extend(extra_endpoints);
    let router = AuthRouter::with_async_endpoints(context.clone(), endpoints, async_endpoints)?;
    Ok(RustAuth {
        router,
        options,
        context,
        adapter: None,
    })
}

async fn build_with_adapter(
    options: RustAuthOptions,
    adapter: Arc<dyn DbAdapter>,
    extra_endpoints: Vec<AuthEndpoint>,
    async_endpoints: Vec<AsyncAuthEndpoint>,
    #[cfg(feature = "telemetry")] telemetry_context: Option<TelemetryContext>,
) -> Result<RustAuth, RustAuthError> {
    let context = create_auth_context(options.clone())?;
    let joined_adapter: Arc<dyn DbAdapter> = Arc::new(JoinAdapter::new(
        context.db_schema.clone(),
        adapter,
        options.experimental.joins,
    ));
    let context = create_auth_context_with_adapter(options.clone(), Arc::clone(&joined_adapter))?;
    let adapter = context.adapter.clone().unwrap_or(joined_adapter);
    let context = {
        #[cfg(feature = "telemetry")]
        {
            let mut context = context;
            attach_telemetry(
                &mut context,
                &options,
                telemetry_context.unwrap_or_default(),
            )
            .await;
            context
        }
        #[cfg(not(feature = "telemetry"))]
        {
            context
        }
    };
    let mut endpoints = core_endpoints();
    endpoints.extend(extra_endpoints);
    let mut product_async_endpoints = core_auth_async_endpoints();
    product_async_endpoints.extend(async_endpoints);
    let router =
        AuthRouter::with_async_endpoints(context.clone(), endpoints, product_async_endpoints)?;
    Ok(RustAuth {
        router,
        options,
        context,
        adapter: Some(adapter),
    })
}

#[cfg(feature = "telemetry")]
async fn attach_telemetry(
    context: &mut AuthContext,
    options: &RustAuthOptions,
    telemetry_context: TelemetryContext,
) {
    let publisher = create_telemetry(options, telemetry_context).await;
    context.telemetry_publisher = Arc::new(move |event: ContextTelemetryEvent| {
        let publisher = publisher.clone();
        Box::pin(async move {
            publisher
                .publish(TelemetryEvent {
                    event_type: event.event_type,
                    anonymous_id: event.anonymous_id,
                    payload: event.payload,
                })
                .await;
        })
    });
}