runique 3.0.2

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Provides SeaORM table creation statements for internal RBAC components.
//! Usable by developers in their own `up` migrations.

use sea_query::{
    Alias, Check, ColumnDef, Expr, ExprTrait, ForeignKey, ForeignKeyAction, Index, Table,
    TableCreateStatement,
};

// ── EihwazUsersMigration ──────────────────────────────────────────────────────

/// Generates the `TableCreateStatement` for the `eihwaz_users` table.
pub fn create_eihwaz_users_table() -> TableCreateStatement {
    let mut pk_col = ColumnDef::new(Alias::new("id"));
    #[cfg(feature = "pk-uuid")]
    pk_col.uuid();
    #[cfg(all(feature = "big-pk", not(feature = "pk-uuid")))]
    pk_col.big_integer();
    #[cfg(not(any(feature = "big-pk", feature = "pk-uuid")))]
    pk_col.integer();
    pk_col.not_null().primary_key();
    // UUID primary keys are generated application-side (Uuid::now_v7()), never DB auto-increment.
    #[cfg(not(feature = "pk-uuid"))]
    pk_col.auto_increment();

    Table::create()
        .table(Alias::new("eihwaz_users"))
        .if_not_exists()
        .col(&mut pk_col)
        .col(
            ColumnDef::new(Alias::new("username"))
                .string()
                .not_null()
                .unique_key(),
        )
        .col(
            ColumnDef::new(Alias::new("email"))
                .string()
                .not_null()
                .unique_key(),
        )
        .col(ColumnDef::new(Alias::new("password")).string().not_null())
        .col(
            ColumnDef::new(Alias::new("is_active"))
                .boolean()
                .not_null()
                .default(false),
        )
        .col(
            ColumnDef::new(Alias::new("is_staff"))
                .boolean()
                .not_null()
                .default(false),
        )
        .col(
            ColumnDef::new(Alias::new("is_superuser"))
                .boolean()
                .not_null()
                .default(false),
        )
        .col(ColumnDef::new(Alias::new("created_at")).date_time().null())
        .col(ColumnDef::new(Alias::new("updated_at")).date_time().null())
        // When the account's owner first took it over through the emailed link.
        .col(
            ColumnDef::new(Alias::new("activated_at"))
                .date_time()
                .null(),
        )
        // The database itself refuses an active account that was never
        // activated, whatever writes it — the ORM, raw SQL, a script.
        .check(Check::named(
            ACTIVE_NEEDS_ACTIVATION,
            Expr::col(Alias::new("is_active"))
                .not()
                .or(Expr::col(Alias::new("activated_at")).is_not_null()),
        ))
        .to_owned()
}

/// "Turnkey" migration to create the `eihwaz_users` table.
/// To be placed first in the `Migrator` `vec!`.
pub struct EihwazUsersMigration;

impl sea_orm_migration::MigrationName for EihwazUsersMigration {
    fn name(&self) -> &str {
        "m000000_000001_runique_eihwaz_users"
    }
}

#[async_trait::async_trait]
impl sea_orm_migration::MigrationTrait for EihwazUsersMigration {
    async fn up(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager.create_table(create_eihwaz_users_table()).await
    }

    async fn down(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager
            .drop_table(Table::drop().table(Alias::new("eihwaz_users")).to_owned())
            .await
    }
}

/// Name of the `CHECK` constraint "an active account has been activated", so a
/// refusal can be recognised whatever the engine.
pub const ACTIVE_NEEDS_ACTIVATION: &str = "eihwaz_users_active_needs_activation";

/// Generates the `TableCreateStatement` for the `eihwaz_groupes` table.
pub fn create_eihwaz_groupes_table() -> TableCreateStatement {
    Table::create()
        .table(Alias::new("eihwaz_groupes"))
        .if_not_exists()
        .col(
            ColumnDef::new(Alias::new("id"))
                .integer()
                .not_null()
                .auto_increment()
                .primary_key(),
        )
        .col(
            ColumnDef::new(Alias::new("nom"))
                .string()
                .not_null()
                .unique_key(),
        )
        .to_owned()
}

/// Generates the `TableCreateStatement` for the `eihwaz_groupes_droits` table.
/// Each row represents a group's permissions on a specific resource.
/// Composite PK: (groupe_id, resource_key).
pub fn create_eihwaz_groupes_droits_table() -> TableCreateStatement {
    Table::create()
        .table(Alias::new("eihwaz_groupes_droits"))
        .if_not_exists()
        .col(ColumnDef::new(Alias::new("groupe_id")).integer().not_null())
        .col(
            ColumnDef::new(Alias::new("resource_key"))
                .string()
                .not_null(),
        )
        .col(
            ColumnDef::new(Alias::new("can_create"))
                .boolean()
                .not_null()
                .default(false),
        )
        .col(
            ColumnDef::new(Alias::new("can_read"))
                .boolean()
                .not_null()
                .default(false),
        )
        .col(
            ColumnDef::new(Alias::new("can_update"))
                .boolean()
                .not_null()
                .default(false),
        )
        .col(
            ColumnDef::new(Alias::new("can_delete"))
                .boolean()
                .not_null()
                .default(false),
        )
        .col(
            ColumnDef::new(Alias::new("can_update_own"))
                .boolean()
                .not_null()
                .default(false),
        )
        .col(
            ColumnDef::new(Alias::new("can_delete_own"))
                .boolean()
                .not_null()
                .default(false),
        )
        .primary_key(
            Index::create()
                .name("pk_eihwaz_groupes_droits")
                .col(Alias::new("groupe_id"))
                .col(Alias::new("resource_key")),
        )
        .foreign_key(
            ForeignKey::create()
                .name("fk_eihwaz_groupes_droits_groupe_id")
                .from(Alias::new("eihwaz_groupes_droits"), Alias::new("groupe_id"))
                .to(Alias::new("eihwaz_groupes"), Alias::new("id"))
                .on_delete(ForeignKeyAction::Cascade),
        )
        .to_owned()
}

/// Generates the `TableCreateStatement` for the `eihwaz_users_groupes` junction table.
pub fn create_eihwaz_users_groupes_table() -> TableCreateStatement {
    let fk_name = "fk_eihwaz_users_groupes_eihwaz_users_id";

    // user_id doit suivre le type de eihwaz_users.id (BIGINT sous big-pk, UUID sous pk-uuid),
    // sinon la FK est de type incompatible et échoue à la création (Postgres strict).
    let mut user_id_col = ColumnDef::new(Alias::new("user_id"));
    #[cfg(feature = "pk-uuid")]
    user_id_col.uuid();
    #[cfg(all(feature = "big-pk", not(feature = "pk-uuid")))]
    user_id_col.big_integer();
    #[cfg(not(any(feature = "big-pk", feature = "pk-uuid")))]
    user_id_col.integer();
    user_id_col.not_null();

    Table::create()
        .table(Alias::new("eihwaz_users_groupes"))
        .if_not_exists()
        .col(&mut user_id_col)
        .col(ColumnDef::new(Alias::new("groupe_id")).integer().not_null())
        .primary_key(
            Index::create()
                .name("pk_eihwaz_users_groupes")
                .col(Alias::new("user_id"))
                .col(Alias::new("groupe_id")),
        )
        .foreign_key(
            ForeignKey::create()
                .name(fk_name)
                .from(Alias::new("eihwaz_users_groupes"), Alias::new("user_id"))
                .to(Alias::new("eihwaz_users"), Alias::new("id"))
                .on_delete(ForeignKeyAction::Cascade),
        )
        .foreign_key(
            ForeignKey::create()
                .name("fk_eihwaz_users_groupes_groupe_id")
                .from(Alias::new("eihwaz_users_groupes"), Alias::new("groupe_id"))
                .to(Alias::new("eihwaz_groupes"), Alias::new("id"))
                .on_delete(ForeignKeyAction::Cascade),
        )
        .to_owned()
}

/// Generates the `TableCreateStatement` for the `eihwaz_sessions` table.
pub fn create_eihwaz_sessions_table() -> TableCreateStatement {
    let mut user_id_col = ColumnDef::new(Alias::new("user_id"));
    #[cfg(feature = "pk-uuid")]
    user_id_col.uuid();
    #[cfg(all(feature = "big-pk", not(feature = "pk-uuid")))]
    user_id_col.big_integer();
    #[cfg(not(any(feature = "big-pk", feature = "pk-uuid")))]
    user_id_col.integer();
    user_id_col.not_null();

    let fk_name = "fk_eihwaz_sessions_eihwaz_users_id";

    Table::create()
        .table(Alias::new("eihwaz_sessions"))
        .if_not_exists()
        .col(
            ColumnDef::new(Alias::new("id"))
                .integer()
                .not_null()
                .auto_increment()
                .primary_key(),
        )
        .col(
            ColumnDef::new(Alias::new("cookie_id"))
                .string()
                .not_null()
                .unique_key(),
        )
        .col(&mut user_id_col)
        .col(ColumnDef::new(Alias::new("session_id")).string().not_null())
        .col(ColumnDef::new(Alias::new("session_data")).text().null())
        .col(
            ColumnDef::new(Alias::new("expires_at"))
                .date_time()
                .not_null(),
        )
        .foreign_key(
            ForeignKey::create()
                .name(fk_name)
                .from(Alias::new("eihwaz_sessions"), Alias::new("user_id"))
                .to(Alias::new("eihwaz_users"), Alias::new("id"))
                .on_delete(ForeignKeyAction::Cascade),
        )
        .to_owned()
}

/// "Turnkey" migration to create the `eihwaz_sessions` table.
/// To be placed in the `Migrator` `vec!` after `EihwazUsersMigration`.
pub struct EihwazSessionsMigration;

impl sea_orm_migration::MigrationName for EihwazSessionsMigration {
    fn name(&self) -> &str {
        "m000000_000003_runique_eihwaz_sessions"
    }
}

#[async_trait::async_trait]
impl sea_orm_migration::MigrationTrait for EihwazSessionsMigration {
    async fn up(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager.create_table(create_eihwaz_sessions_table()).await
    }

    async fn down(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager
            .drop_table(
                Table::drop()
                    .table(Alias::new("eihwaz_sessions"))
                    .if_exists()
                    .to_owned(),
            )
            .await
    }
}

/// Generates the `TableCreateStatement` for the `eihwaz_history` table.
///
/// `user_id` **deliberately has no FK** to the user table: the audit trail must
/// survive a user's deletion (a CASCADE FK would erase the history of their
/// actions). `username` is denormalized to keep a readable trace even after
/// deletion. Don't "fix" this by adding a CASCADE FK.
pub fn create_eihwaz_history_table() -> TableCreateStatement {
    let mut user_id_col = ColumnDef::new(Alias::new("user_id"));
    #[cfg(feature = "pk-uuid")]
    user_id_col.uuid();
    #[cfg(all(feature = "big-pk", not(feature = "pk-uuid")))]
    user_id_col.big_integer();
    #[cfg(not(any(feature = "big-pk", feature = "pk-uuid")))]
    user_id_col.integer();
    user_id_col.not_null();

    Table::create()
        .table(Alias::new("eihwaz_history"))
        .if_not_exists()
        .col(
            ColumnDef::new(Alias::new("id"))
                .big_integer()
                .not_null()
                .auto_increment()
                .primary_key(),
        )
        .col(
            ColumnDef::new(Alias::new("resource_key"))
                .string()
                .not_null(),
        )
        .col(ColumnDef::new(Alias::new("object_pk")).string().not_null())
        .col(ColumnDef::new(Alias::new("action")).string().not_null())
        .col(&mut user_id_col)
        .col(ColumnDef::new(Alias::new("username")).string().not_null())
        .col(
            ColumnDef::new(Alias::new("created_at"))
                .date_time()
                .not_null(),
        )
        .col(ColumnDef::new(Alias::new("summary")).text().null())
        .col(ColumnDef::new(Alias::new("batch_id")).string().null())
        .to_owned()
}

/// "Turnkey" migration to create the `eihwaz_history` table.
pub struct EihwazHistoryMigration;

impl sea_orm_migration::MigrationName for EihwazHistoryMigration {
    fn name(&self) -> &str {
        "m000000_000004_runique_eihwaz_history"
    }
}

#[async_trait::async_trait]
impl sea_orm_migration::MigrationTrait for EihwazHistoryMigration {
    async fn up(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager.create_table(create_eihwaz_history_table()).await
    }

    async fn down(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager
            .drop_table(Table::drop().table(Alias::new("eihwaz_history")).to_owned())
            .await
    }
}

/// Generates the `TableCreateStatement` for the `eihwaz_reset_tokens` table.
///
/// Stores **hashed** password-reset tokens (never the raw token) so a DB read leak
/// cannot be replayed. `user_id` is the authoritative target of the reset, derived
/// from the token row — never from a URL/form field.
pub fn create_eihwaz_reset_tokens_table() -> TableCreateStatement {
    let mut user_id_col = ColumnDef::new(Alias::new("user_id"));
    #[cfg(feature = "pk-uuid")]
    user_id_col.uuid();
    #[cfg(all(feature = "big-pk", not(feature = "pk-uuid")))]
    user_id_col.big_integer();
    #[cfg(not(any(feature = "big-pk", feature = "pk-uuid")))]
    user_id_col.integer();
    user_id_col.not_null();

    let fk_name = "fk_eihwaz_reset_tokens_eihwaz_users_id";

    Table::create()
        .table(Alias::new("eihwaz_reset_tokens"))
        .if_not_exists()
        .col(
            ColumnDef::new(Alias::new("id"))
                .big_integer()
                .not_null()
                .auto_increment()
                .primary_key(),
        )
        .col(
            ColumnDef::new(Alias::new("token_hash"))
                .string()
                .not_null()
                .unique_key(),
        )
        .col(&mut user_id_col)
        .col(
            ColumnDef::new(Alias::new("expires_at"))
                .date_time()
                .not_null(),
        )
        .foreign_key(
            ForeignKey::create()
                .name(fk_name)
                .from(Alias::new("eihwaz_reset_tokens"), Alias::new("user_id"))
                .to(Alias::new("eihwaz_users"), Alias::new("id"))
                .on_delete(ForeignKeyAction::Cascade),
        )
        .to_owned()
}

/// "Turnkey" migration to create the `eihwaz_reset_tokens` table.
/// To be placed in the `Migrator` `vec!` after `EihwazUsersMigration`.
pub struct EihwazResetTokensMigration;

impl sea_orm_migration::MigrationName for EihwazResetTokensMigration {
    fn name(&self) -> &str {
        "m000000_000005_runique_reset_tokens"
    }
}

#[async_trait::async_trait]
impl sea_orm_migration::MigrationTrait for EihwazResetTokensMigration {
    async fn up(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager
            .create_table(create_eihwaz_reset_tokens_table())
            .await
    }

    async fn down(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager
            .drop_table(
                Table::drop()
                    .table(Alias::new("eihwaz_reset_tokens"))
                    .if_exists()
                    .to_owned(),
            )
            .await
    }
}

/// Complete "turnkey" migration to initialize Runique's native RBAC architecture.
/// To be injected directly into the `Migrations::up()` `vec!` after your User table migration.
pub struct AdminTableMigration;

impl sea_orm_migration::MigrationName for AdminTableMigration {
    fn name(&self) -> &str {
        "m000000_000002_runique_admin_table"
    }
}

#[async_trait::async_trait]
impl sea_orm_migration::MigrationTrait for AdminTableMigration {
    async fn up(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager.create_table(create_eihwaz_groupes_table()).await?;
        manager
            .create_table(create_eihwaz_groupes_droits_table())
            .await?;
        manager
            .create_table(create_eihwaz_users_groupes_table())
            .await?;
        manager.create_table(create_eihwaz_sessions_table()).await?;
        manager.create_table(create_eihwaz_history_table()).await?;
        Ok(())
    }

    async fn down(&self, manager: &sea_orm_migration::SchemaManager) -> Result<(), sea_orm::DbErr> {
        manager
            .drop_table(Table::drop().table(Alias::new("eihwaz_history")).to_owned())
            .await?;
        manager
            .drop_table(
                Table::drop()
                    .table(Alias::new("eihwaz_sessions"))
                    .if_exists()
                    .to_owned(),
            )
            .await?;
        manager
            .drop_table(
                Table::drop()
                    .table(Alias::new("eihwaz_users_groupes"))
                    .to_owned(),
            )
            .await?;
        manager
            .drop_table(
                Table::drop()
                    .table(Alias::new("eihwaz_groupes_droits"))
                    .to_owned(),
            )
            .await?;
        manager
            .drop_table(Table::drop().table(Alias::new("eihwaz_groupes")).to_owned())
            .await?;
        Ok(())
    }
}