laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! `model::Users` as the session guard's provider. A test binary of its own, because the
//! verification pages it marks are discovered per crate.

use std::sync::Mutex;

use laravel::auth::VerificationEmail;
use laravel::auth::{
    self, Auth, Authenticatable, Authenticate, Authenticated, EmailVerification, MustVerifyEmail, RememberToken,
    UserProvider,
};
use laravel::config::database::ConnectionConfig;
use laravel::container::Inject;
use laravel::event::Event;
use laravel::hash::{Password, PasswordHash};
use laravel::mail::{self, Address};
use laravel::model::{self, Updated, create, model, update};
use laravel::testing::TestResponse;
use laravel::testing::prelude::*;
use laravel::time::Timestamp;
use laravel::validation::{Valid, Validate, ValidatesRequest};
use serde::Deserialize;
use serde_json::json;

#[model]
#[derive(Authenticatable, MustVerifyEmail)]
pub struct User {
    pub id: i64,
    pub name: String,
    pub email: String,
    pub email_verified_at: Option<Timestamp>,
    #[serde(skip)]
    pub password: PasswordHash,
    #[serde(skip)]
    pub remember_token: Option<RememberToken>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

impl From<&User> for Address {
    fn from(user: &User) -> Self {
        Self::new(&user.email)
    }
}

/// The columns of each `Updated<User>`, in order.
#[derive(Default)]
struct Updates(Mutex<Vec<Vec<&'static str>>>);

#[derive(Deserialize, Validate)]
struct Login {
    #[validate(required)]
    email: String,
    #[validate(required)]
    password: Password,
    #[serde(default)]
    remember: bool,
}

impl ValidatesRequest for Login {
    async fn authorize(_: &Request) -> laravel::Result<bool> {
        Ok(true)
    }
}

#[derive(Deserialize, Validate)]
struct UpdatePassword {
    #[validate(required)]
    password: Password,
}

impl ValidatesRequest for UpdatePassword {
    async fn authorize(_: &Request) -> laravel::Result<bool> {
        Ok(true)
    }
}

#[auth::page(login)]
async fn show_login() -> &'static str {
    "Log in"
}

async fn login(auth: Auth<User>, Valid(form): Valid<Login>) -> laravel::Result<Redirect> {
    auth.attempt(&form.email, &form.password)
        .remember(form.remember)
        .await?;

    Ok(Redirect::to("/dashboard"))
}

async fn dashboard(user: Authenticated<User>) -> String {
    format!("Hello, {}", user.name)
}

async fn update_password(auth: Auth<User>, Valid(form): Valid<UpdatePassword>) -> laravel::Result<Redirect> {
    auth.update_password(&form.password).await?;

    Ok(Redirect::to("/dashboard"))
}

async fn logout(auth: Auth<User>) -> laravel::Result<Redirect> {
    auth.logout().await?;

    Ok(Redirect::to("/"))
}

#[auth::page(verification_notice)]
async fn verification_notice() -> &'static str {
    "Verify your email"
}

async fn send_verification(
    user: Authenticated<User>,
    verification: EmailVerification<User>,
) -> laravel::Result<Redirect> {
    verification.send_link(&user).await?;

    Ok(Redirect::back())
}

#[auth::page(verify_email)]
async fn verify_email(verification: EmailVerification<User>) -> laravel::Result<String> {
    let user = verification.verify().await?;

    Ok(format!("Verified {}", user.has_verified_email()))
}

fn app() -> Application {
    Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_config(|config, _| {
            let mut connection = ConnectionConfig::new("sqlite::memory:");
            connection.max_connections = 1;
            config.database.default = "app".into();
            config.database.add_connection("app", connection);
        })
        .with_services(|app| {
            app.instance(Updates::default());
        })
        .with_events(|events, _| {
            events.listen(|event: Event<Updated<User>>, updates: Inject<Updates>| async move {
                let columns = event.changes.iter().map(|change| change.column).collect();
                updates.0.lock().unwrap().push(columns);
            });
        })
        .with_auth(|auth, _| {
            auth.session::<model::Users<User>>().discover(env!("CARGO_CRATE_NAME"));
        })
        .with_routing(|routing, _| {
            routing.web(|route| {
                route.get("/login", show_login);
                route.post("/login", login);
                route.post("/logout", logout);
                route.middleware(Authenticate).group(|route| {
                    route.get("/dashboard", dashboard);
                    route.post("/password", update_password);
                    route.get("/verify-email", verification_notice);
                    route.post("/verify-email", send_verification);
                    route.get("/verify-email/{id}/{hash}", verify_email);
                });
            });
        })
        .create()
}

/// An application with Taylor's account, whose password is `secret-password`, created at
/// 09:00.
async fn with_taylor() -> laravel::Result<(Application, User)> {
    let app = app();
    app.travel_to("2026-11-03T09:00:00Z".parse::<Timestamp>().unwrap());
    let taylor = app
        .scope(async || {
            laravel::db::default_connection()?
                .schema()
                .create("users", |table| {
                    table.id();
                    table.string("name");
                    table.string("email").unique();
                    table.timestamp("email_verified_at").nullable();
                    table.string("password");
                    table.remember_token();
                    table.timestamps();
                })
                .await?;

            create!(User {
                name: "Taylor",
                email: "taylor@laravel.com",
                password: "secret-password",
            })
            .await
        })
        .await?;

    Ok((app, taylor))
}

async fn log_in(app: &Application, password: &str, remember: bool) -> TestResponse {
    app.post("/login")
        .form(json!({ "email": "taylor@laravel.com", "password": password, "remember": remember }))
        .await
}

async fn stored_taylor(app: &Application) -> laravel::Result<User> {
    app.scope(async || User::find_or_fail(1).await).await
}

async fn updates(app: &Application) -> Vec<Vec<&'static str>> {
    app.scope(async || laravel::resolve::<Updates>().await.unwrap().0.lock().unwrap().clone())
        .await
}

#[tokio::test]
async fn users_log_in_by_email_and_the_session_finds_them_by_key() -> laravel::Result<()> {
    let (app, _) = with_taylor().await?;

    log_in(&app, "wrong-password", false).await.assert_invalid(&["email"]);
    app.post("/login")
        .form(json!({ "email": "abigail@laravel.com", "password": "secret-password" }))
        .await
        .assert_invalid(&["email"]);

    let session = log_in(&app, "secret-password", false).await;
    session.assert_redirect_to("/dashboard");
    app.get("/dashboard")
        .with_cookies_from(&session)
        .await
        .assert_ok()
        .assert_see("Hello, Taylor");
    app.get("/dashboard").await.assert_redirect_to("http://localhost/login");

    app.scope(async || {
        laravel::db::table("users").delete().await?;
        Ok::<_, laravel::Error>(())
    })
    .await?;
    app.get("/dashboard")
        .with_cookies_from(&session)
        .await
        .assert_redirect_to("http://localhost/login");

    Ok(())
}

#[tokio::test]
async fn remember_tokens_are_stored_without_touching_updated_at_or_dispatching_updated() -> laravel::Result<()> {
    let (app, _) = with_taylor().await?;
    app.travel_to("2026-11-03T10:00:00Z".parse::<Timestamp>().unwrap());

    let response = log_in(&app, "secret-password", true).await;
    let remember = response.cookie("remember_web").expect("a remember cookie");
    let taylor = stored_taylor(&app).await?;
    let token = taylor.remember_token.clone().expect("the token is stored");
    assert_eq!(token.as_str().len(), 60);
    assert_eq!(taylor.updated_at, "2026-11-03T09:00:00Z".parse::<Timestamp>().unwrap());
    assert_eq!(updates(&app).await, Vec::<Vec<&str>>::new());

    app.get("/dashboard")
        .cookie("remember_web", &remember)
        .await
        .assert_ok()
        .assert_see("Hello, Taylor");

    app.post("/logout")
        .cookie("remember_web", &remember)
        .await
        .assert_redirect_to("/");
    assert_ne!(
        stored_taylor(&app).await?.remember_token,
        Some(token),
        "logging out replaces the token"
    );
    app.get("/dashboard")
        .cookie("remember_web", &remember)
        .await
        .assert_redirect_to("http://localhost/login");

    Ok(())
}

#[tokio::test]
async fn a_new_password_updates_the_model_and_dispatches_updated() -> laravel::Result<()> {
    let (app, _) = with_taylor().await?;
    let session = log_in(&app, "secret-password", false).await;
    app.travel_to("2026-11-03T10:00:00Z".parse::<Timestamp>().unwrap());

    let changed = app
        .post("/password")
        .with_cookies_from(&session)
        .form(json!({ "password": "new-password" }))
        .await;
    changed.assert_redirect_to("/dashboard");

    let taylor = stored_taylor(&app).await?;
    assert!(laravel::hash::check("new-password", &taylor.password).await);
    assert_eq!(taylor.updated_at, "2026-11-03T10:00:00Z".parse::<Timestamp>().unwrap());
    assert_eq!(updates(&app).await, [["password", "updated_at"]]);

    app.get("/dashboard").with_cookies_from(&changed).await.assert_ok();
    log_in(&app, "secret-password", false).await.assert_invalid(&["email"]);
    log_in(&app, "new-password", false)
        .await
        .assert_redirect_to("/dashboard");

    Ok(())
}

#[tokio::test]
async fn opening_a_verification_link_marks_the_model_verified() -> laravel::Result<()> {
    let (app, _) = with_taylor().await?;
    let session = log_in(&app, "secret-password", false).await;
    let mail = app.scope(async || mail::fake()).await;
    app.travel_to("2026-11-03T10:00:00Z".parse::<Timestamp>().unwrap());

    app.post("/verify-email")
        .with_cookies_from(&session)
        .await
        .assert_redirect();
    let emails = mail.queued::<VerificationEmail>();
    let text = emails
        .first()
        .expect("a link is sent")
        .text()
        .expect("the email has text");
    let start = text
        .find("http://localhost/verify-email/")
        .expect("the email has the link");
    let link = text[start..]
        .split_whitespace()
        .next()
        .unwrap()
        .trim_start_matches("http://localhost");

    app.get(link)
        .with_cookies_from(&session)
        .await
        .assert_ok()
        .assert_see("Verified true");

    let taylor = stored_taylor(&app).await?;
    assert_eq!(taylor.email_verified_at, Some("2026-11-03T10:00:00Z".parse().unwrap()));
    assert_eq!(updates(&app).await, [["email_verified_at", "updated_at"]]);

    Ok(())
}

#[model(table = "members")]
#[derive(Authenticatable)]
pub struct Member {
    pub id: i64,
    #[auth(username)]
    #[column("user_name")]
    pub username: String,
    pub email: String,
    #[serde(skip)]
    pub password: PasswordHash,
    #[serde(skip)]
    pub remember_token: Option<RememberToken>,
}

#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct MemberLogin {
    #[validate(required)]
    username: String,
    #[validate(required)]
    password: Password,
}

async fn member_login(auth: Auth<Member>, Valid(form): Valid<MemberLogin>) -> laravel::Result<String> {
    let member = auth.attempt(&form.username, &form.password).await?;

    Ok(member.email)
}

#[tokio::test]
async fn the_field_marked_username_finds_users_by_its_column() -> laravel::Result<()> {
    let app = Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_config(|config, _| {
            let mut connection = ConnectionConfig::new("sqlite::memory:");
            connection.max_connections = 1;
            config.database.default = "app".into();
            config.database.add_connection("app", connection);
        })
        .with_auth(|auth, _| {
            auth.session::<model::Users<Member>>();
        })
        .with_routing(|routing, _| {
            routing.web(|route| {
                route.post("/login", member_login);
            });
        })
        .create();
    app.scope(async || {
        laravel::db::default_connection()?
            .schema()
            .create("members", |table| {
                table.id();
                table.string("user_name");
                table.string("email");
                table.string("password");
                table.remember_token();
            })
            .await?;
        create!(Member {
            username: "taylor",
            email: "taylor@laravel.com",
            password: "secret-password",
        })
        .await?;
        Ok::<_, laravel::Error>(())
    })
    .await?;

    app.post("/login")
        .form(json!({ "username": "taylor", "password": "secret-password" }))
        .await
        .assert_ok()
        .assert_see("taylor@laravel.com");
    app.post("/login")
        .form(json!({ "username": "taylor@laravel.com", "password": "secret-password" }))
        .await
        .assert_invalid_messages(&[("username", "These credentials do not match our records.")]);

    Ok(())
}

/// Stores remember tokens with `update!`, as the authentication guide's own provider does.
struct Members;

impl UserProvider for Members {
    type User = Member;

    async fn find(&self, id: &i64) -> laravel::Result<Option<Member>> {
        Member::find(*id).await
    }

    async fn find_for_login(&self, username: &str) -> laravel::Result<Option<Member>> {
        Member::first_where(Member::username.eq(username)).await
    }

    async fn update_password(&self, member: &Member, password: &PasswordHash) -> laravel::Result<()> {
        let mut member = member.clone();

        update!(member { password }).await
    }

    async fn update_remember_token(&self, member: &Member, token: &str) -> laravel::Result<()> {
        let mut member = member.clone();

        update!(member { remember_token: token }).quietly().await
    }
}

async fn remember_member(auth: Auth<Member>, Valid(form): Valid<MemberLogin>) -> laravel::Result<Redirect> {
    auth.attempt(&form.username, &form.password).remember(true).await?;

    Ok(Redirect::to("/me"))
}

async fn me(member: Authenticated<Member>) -> String {
    member.username.clone()
}

#[tokio::test]
async fn remember_tokens_stored_with_update_log_users_back_in() -> laravel::Result<()> {
    let app = Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_config(|config, _| {
            let mut connection = ConnectionConfig::new("sqlite::memory:");
            connection.max_connections = 1;
            config.database.default = "app".into();
            config.database.add_connection("app", connection);
        })
        .with_services(|app| {
            app.instance(Members);
        })
        .with_auth(|auth, _| {
            auth.session::<Members>();
        })
        .with_routing(|routing, _| {
            routing.web(|route| {
                route.post("/login", remember_member);
                route.middleware(Authenticate).group(|route| {
                    route.get("/me", me);
                });
            });
        })
        .create();
    app.scope(async || {
        laravel::db::default_connection()?
            .schema()
            .create("members", |table| {
                table.id();
                table.string("user_name");
                table.string("email");
                table.string("password");
                table.remember_token();
            })
            .await?;
        create!(Member {
            username: "taylor",
            email: "taylor@laravel.com",
            password: "secret-password",
        })
        .await?;
        Ok::<_, laravel::Error>(())
    })
    .await?;

    let response = app
        .post("/login")
        .form(json!({ "username": "taylor", "password": "secret-password" }))
        .await;
    response.assert_redirect_to("/me");
    let remember = response.cookie("remember_web").expect("a remember cookie");

    let member = app.scope(async || Member::find_or_fail(1).await).await?;
    let token = member
        .remember_token
        .as_ref()
        .map(RememberToken::as_str)
        .expect("the token is stored");
    assert_eq!(token.len(), 60);
    assert!(!format!("{member:?}").contains(token));

    app.get("/me")
        .cookie("remember_web", &remember)
        .await
        .assert_ok()
        .assert_see("taylor");
    app.get("/me").await.assert_unauthorized();

    Ok(())
}

#[model(table = "accounts")]
#[derive(Authenticatable)]
pub struct Account {
    #[column("account_id")]
    pub id: i64,
    pub email: String,
    #[serde(skip)]
    pub password: PasswordHash,
    #[serde(skip)]
    pub remember_token: Option<RememberToken>,
}

#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct AccountEmail {
    #[validate(required, unique("accounts", "email", ignore = user))]
    email: String,
}

async fn account_login(auth: Auth<Account>, Valid(form): Valid<Login>) -> laravel::Result<&'static str> {
    auth.attempt(&form.email, &form.password).await?;

    Ok("Logged in")
}

#[tokio::test]
async fn unique_skips_the_users_row_by_the_models_key_column() -> laravel::Result<()> {
    let app = Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_config(|config, _| {
            let mut connection = ConnectionConfig::new("sqlite::memory:");
            connection.max_connections = 1;
            config.database.default = "app".into();
            config.database.add_connection("app", connection);
        })
        .with_auth(|auth, _| {
            auth.session::<model::Users<Account>>();
        })
        .with_routing(|routing, _| {
            routing.web(|route| {
                route.post("/login", account_login);
                route.put("/email", |Valid(form): Valid<AccountEmail>| async move { form.email });
            });
        })
        .create();
    let taylor = app
        .scope(async || {
            laravel::db::default_connection()?
                .schema()
                .create("accounts", |table| {
                    table.big_increments("account_id");
                    table.string("email").unique();
                    table.string("password");
                    table.remember_token();
                })
                .await?;
            create!(Account {
                email: "jess@laravel.com",
                password: "secret-password",
            })
            .await?;

            create!(Account {
                email: "taylor@laravel.com",
                password: "secret-password",
            })
            .await
        })
        .await?;

    let session = app
        .post("/login")
        .form(json!({ "email": "taylor@laravel.com", "password": "secret-password" }))
        .await;
    session.assert_ok();
    app.put("/email")
        .with_cookies_from(&session)
        .json(json!({ "email": "taylor@laravel.com" }))
        .await
        .assert_ok()
        .assert_see("taylor@laravel.com");
    app.put("/email")
        .with_cookies_from(&session)
        .json(json!({ "email": "jess@laravel.com" }))
        .await
        .assert_invalid_messages(&[("email", "The email has already been taken.")]);

    app.put("/email")
        .acting_as(&taylor)
        .json(json!({ "email": "taylor@laravel.com" }))
        .await
        .assert_ok();

    Ok(())
}