tinkr 0.0.43

Tinkr is a web framework for quickly building full-stack web applications with Leptos.
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
use crate::EmailAddress;
use crate::auth::oauth::OAuthProvider;
use leptos::{prelude::*, reactive::spawn_local};
use leptos_router::hooks::use_query_map;
use urlencoding::decode;

#[derive(Clone, Debug)]
enum AuthStatus {
    Loading,
    Success,
    Error(String),
}

#[component]
pub fn AuthCallback() -> impl IntoView {
    let query = use_query_map();
    let (auth_status, set_auth_status) = signal(AuthStatus::Loading);

    let params = move || {
        let token = query.get().get("token");
        let callbackurl = query.get().get("callbackUrl");
        (token, callbackurl)
    };

    Effect::new(move || {
        let (token, callback_url) = params();

        #[cfg(feature = "ssr")]
        // Log the parameters for debugging
        tracing::info!(
            "AuthCallback params - Token: {:?}, Callback URL: {:?}",
            token,
            callback_url
        );

        if let Some(token) = token {
            let set_auth_status = set_auth_status.clone();
            spawn_local(async move {
                let result = verify_token_callback_get_session_token(token).await;

                match result {
                    Ok(_) => {
                        #[cfg(feature = "ssr")]
                        tracing::info!("Token verification successful");
                        set_auth_status.set(AuthStatus::Success);

                        // store_token(session_token.clone());
                        // set_cookie_session_token(Some(session_token.clone()));

                        // Redirect or update UI as needed
                        if let Some(url) = callback_url {
                            let url = match decode(url.as_str()) {
                                Ok(decoded) => decoded.to_string(),
                                Err(_e) => {
                                    #[cfg(feature = "ssr")]
                                    tracing::error!("Failed to decode callback URL: {}", _e);

                                    return;
                                }
                            };
                            // Perform redirect to callback URL
                            window().location().set_href(&url).unwrap();
                        }
                    }
                    Err(e) => {
                        #[cfg(feature = "ssr")]
                        tracing::error!("Token verification failed: {:?}", e);

                        set_auth_status
                            .set(AuthStatus::Error(format!("Authentication failed: {}", e)));
                    }
                }
            });
        } else {
            set_auth_status.set(AuthStatus::Error(
                "Missing required parameters: token or email".to_string(),
            ));
        }
    });

    view! {
        <div class="h-full flex items-center justify-center bg-neutral-50 dark:bg-neutral-900 py-12 px-4 sm:px-6 lg:px-8">
            <div class="max-w-md w-full space-y-8">
                {move || match auth_status.get() {
                    AuthStatus::Loading => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8 text-center">
                                <div class="flex justify-center mb-4">
                                    <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                                </div>
                                <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                    "Processing authentication..."
                                </p>
                                <p class="mt-2 text-sm text-neutral-600 dark:text-neutral-400">
                                    "Please wait while we verify your credentials"
                                </p>
                            </div>
                        }
                            .into_any()
                    }
                    AuthStatus::Success => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8 text-center">
                                <div class="flex justify-center mb-4">
                                    <div class="rounded-full bg-green-100 dark:bg-green-900/20 p-3">
                                        <svg
                                            class="h-8 w-8 text-green-600 dark:text-green-400"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M5 13l4 4L19 7"
                                            ></path>
                                        </svg>
                                    </div>
                                </div>
                                <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                    "Authentication successful!"
                                </p>
                                <p class="mt-2 text-sm text-neutral-600 dark:text-neutral-400">
                                    "Redirecting..."
                                </p>
                            </div>
                        }
                            .into_any()
                    }
                    AuthStatus::Error(error) => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8">
                                <div class="flex justify-center mb-4">
                                    <div class="rounded-full bg-red-100 dark:bg-red-900/20 p-3">
                                        <svg
                                            class="h-8 w-8 text-red-600 dark:text-red-400"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M6 18L18 6M6 6l12 12"
                                            ></path>
                                        </svg>
                                    </div>
                                </div>
                                <div class="text-center">
                                    <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                        "Authentication failed"
                                    </p>
                                    <p class="mt-2 text-sm text-red-600 dark:text-red-400 break-words">
                                        {error}
                                    </p>
                                    <p class="mt-4 text-sm text-neutral-600 dark:text-neutral-400">
                                        "Please try signing in again or contact support if the issue persists."
                                    </p>
                                </div>
                            </div>
                        }
                            .into_any()
                    }
                }}
            </div>
        </div>
    }
}

#[server]
pub async fn verify_token_callback_get_session_token(
    token: String,
) -> Result<String, ServerFnError> {
    use http::header::HeaderValue;
    use leptos_axum::ResponseOptions;

    let verified = crate::token::VerificationToken::use_verification_token(token).await?;
    let user = crate::user::AdapterUser::get_user(verified.user_id).await?;

    if &verified.email == &user.email {
        user.set_verified_email().await?;
    } else {
        return Err(ServerFnError::ServerError(
            "Token email does not match user email".into(),
        ));
    }

    let session = user.new_session().await?;

    // Create the cookie
    let cookie = session.build_session_cookie();

    // Set the cookie via ResponseOptions
    if let Some(resp) = use_context::<ResponseOptions>() {
        resp.insert_header(
            axum::http::header::SET_COOKIE,
            HeaderValue::from_str(&cookie.to_string()).unwrap(),
        );
    }

    Ok(session.session_token)
}

#[component]
pub fn VerifyEmailCallback() -> impl IntoView {
    let query = use_query_map();
    let (verify_status, set_verify_status) = signal(AuthStatus::Loading);

    let token = move || query.get().get("token");

    Effect::new(move || {
        let token = token();

        #[cfg(feature = "ssr")]
        tracing::info!("VerifyEmailCallback - Token: {:?}", token);

        if let Some(token) = token {
            let set_verify_status = set_verify_status.clone();
            spawn_local(async move {
                let result = verify_email_with_token(token).await;

                match result {
                    Ok(_email) => {
                        #[cfg(feature = "ssr")]
                        tracing::info!("Email verification successful for: {}", _email);
                        set_verify_status.set(AuthStatus::Success);

                        // Redirect to settings page after 2 seconds
                        set_timeout(
                            move || {
                                window().location().set_href("/settings").unwrap();
                            },
                            std::time::Duration::from_secs(2),
                        );
                    }
                    Err(e) => {
                        #[cfg(feature = "ssr")]
                        tracing::error!("Email verification failed: {:?}", e);

                        set_verify_status
                            .set(AuthStatus::Error(format!("Verification failed: {}", e)));
                    }
                }
            });
        } else {
            set_verify_status.set(AuthStatus::Error("Missing verification token".to_string()));
        }
    });

    view! {
        <div class="h-full flex items-center justify-center bg-neutral-50 dark:bg-neutral-900 py-12 px-4 sm:px-6 lg:px-8">
            <div class="max-w-md w-full space-y-8">
                {move || match verify_status.get() {
                    AuthStatus::Loading => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8 text-center">
                                <div class="flex justify-center mb-4">
                                    <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                                </div>
                                <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                    "Verifying your email..."
                                </p>
                                <p class="mt-2 text-sm text-neutral-600 dark:text-neutral-400">
                                    "Please wait while we confirm your email address"
                                </p>
                            </div>
                        }
                            .into_any()
                    }
                    AuthStatus::Success => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8 text-center">
                                <div class="flex justify-center mb-4">
                                    <div class="rounded-full bg-green-100 dark:bg-green-900/20 p-3">
                                        <svg
                                            class="h-8 w-8 text-green-600 dark:text-green-400"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M5 13l4 4L19 7"
                                            ></path>
                                        </svg>
                                    </div>
                                </div>
                                <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                    "Email verified successfully!"
                                </p>
                                <p class="mt-2 text-sm text-neutral-600 dark:text-neutral-400">
                                    "Redirecting to settings page..."
                                </p>
                            </div>
                        }
                            .into_any()
                    }
                    AuthStatus::Error(error) => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8">
                                <div class="flex justify-center mb-4">
                                    <div class="rounded-full bg-red-100 dark:bg-red-900/20 p-3">
                                        <svg
                                            class="h-8 w-8 text-red-600 dark:text-red-400"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M6 18L18 6M6 6l12 12"
                                            ></path>
                                        </svg>
                                    </div>
                                </div>
                                <div class="text-center">
                                    <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                        "Email verification failed"
                                    </p>
                                    <p class="mt-2 text-sm text-red-600 dark:text-red-400 break-words">
                                        {error}
                                    </p>
                                    <p class="mt-4 text-sm text-neutral-600 dark:text-neutral-400">
                                        "The verification link may have expired or is invalid. Please request a new verification email."
                                    </p>
                                    <a
                                        href="/settings"
                                        class="mt-4 inline-block text-sm text-blue-600 dark:text-blue-400 hover:underline"
                                    >
                                        "Go to Settings"
                                    </a>
                                </div>
                            </div>
                        }
                            .into_any()
                    }
                }}
            </div>
        </div>
    }
}

#[server]
pub async fn verify_email_with_token(
    token: String,
) -> Result<EmailAddress, leptos::server_fn::ServerFnError> {
    let token = crate::token::VerificationToken::use_verification_token(token).await?;
    let user = crate::user::AdapterUser::get_user(token.user_id.clone()).await?;
    user.set_verified_email().await?;
    Ok(token.email)
}

#[component]
pub fn OAuthCallback() -> impl IntoView {
    let query = use_query_map();
    let (auth_status, set_auth_status) = signal(AuthStatus::Loading);

    let params = move || {
        let code = query.get().get("code");
        let state = query.get().get("state");
        let error = query.get().get("error");
        (code, state, error)
    };

    Effect::new(move || {
        let (code, state, error) = params();

        if let Some(error) = error {
            set_auth_status.set(AuthStatus::Error(format!("OAuth error: {}", error)));
            return;
        }

        if let (Some(code), Some(state)) = (code, state) {
            let set_auth_status = set_auth_status.clone();
            spawn_local(async move {
                let result = handle_oauth_callback(code, state).await;

                match result {
                    Ok(callback_url) => {
                        set_auth_status.set(AuthStatus::Success);
                        // Redirect to callback URL
                        window().location().set_href(&callback_url).unwrap();
                    }
                    Err(e) => {
                        set_auth_status
                            .set(AuthStatus::Error(format!("Authentication failed: {}", e)));
                    }
                }
            });
        } else {
            set_auth_status.set(AuthStatus::Error(
                "Missing required parameters: code or state".to_string(),
            ));
        }
    });

    view! {
        <div class="h-full flex items-center justify-center bg-neutral-50 dark:bg-neutral-900 py-12 px-4 sm:px-6 lg:px-8">
            <div class="max-w-md w-full space-y-8">
                {move || match auth_status.get() {
                    AuthStatus::Loading => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8 text-center">
                                <div class="flex justify-center mb-4">
                                    <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                                </div>
                                <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                    "Processing authentication..."
                                </p>
                                <p class="mt-2 text-sm text-neutral-600 dark:text-neutral-400">
                                    "Please wait while we verify your credentials"
                                </p>
                            </div>
                        }
                            .into_any()
                    }
                    AuthStatus::Success => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8 text-center">
                                <div class="flex justify-center mb-4">
                                    <div class="rounded-full bg-green-100 dark:bg-green-900/20 p-3">
                                        <svg
                                            class="h-8 w-8 text-green-600 dark:text-green-400"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M5 13l4 4L19 7"
                                            ></path>
                                        </svg>
                                    </div>
                                </div>
                                <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                    "Authentication successful!"
                                </p>
                                <p class="mt-2 text-sm text-neutral-600 dark:text-neutral-400">
                                    "Redirecting..."
                                </p>
                            </div>
                        }
                            .into_any()
                    }
                    AuthStatus::Error(error) => {
                        view! {
                            <div class="bg-white dark:bg-neutral-800 rounded-lg shadow-lg p-8">
                                <div class="flex justify-center mb-4">
                                    <div class="rounded-full bg-red-100 dark:bg-red-900/20 p-3">
                                        <svg
                                            class="h-8 w-8 text-red-600 dark:text-red-400"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M6 18L18 6M6 6l12 12"
                                            ></path>
                                        </svg>
                                    </div>
                                </div>
                                <div class="text-center">
                                    <p class="text-lg font-medium text-neutral-900 dark:text-neutral-100">
                                        "Authentication failed"
                                    </p>
                                    <p class="mt-2 text-sm text-red-600 dark:text-red-400 break-words">
                                        {error}
                                    </p>
                                    <p class="mt-4 text-sm text-neutral-600 dark:text-neutral-400">
                                        "Please try signing in again or contact support if the issue persists."
                                    </p>
                                </div>
                            </div>
                        }
                            .into_any()
                    }
                }}
            </div>
        </div>
    }
}

#[server]
pub async fn handle_oauth_callback(code: String, state: String) -> Result<String, ServerFnError> {
    use crate::auth::oauth::{OAuthConfig, OAuthUserInfo};
    use crate::auth::session::{delete_oauth_state, get_oauth_state};
    use http::header::HeaderValue;
    use leptos_axum::ResponseOptions;
    use oauth2::{AuthorizationCode, PkceCodeVerifier, TokenResponse};

    // Retrieve and validate OAuth state
    let oauth_state = get_oauth_state(state.clone()).await?;

    // Delete the state to prevent reuse
    delete_oauth_state(state).await?;

    // Get the provider config
    let config = match oauth_state.provider {
        OAuthProvider::Github => OAuthConfig::github(),
        OAuthProvider::Google => OAuthConfig::google(),
        OAuthProvider::Discord => OAuthConfig::discord(),
    }
    .map_err(|e| ServerFnError::new(e))?;

    let client = config.build_client().map_err(|e| ServerFnError::new(e))?;

    // Exchange the code for a token using async HTTP client
    let token_result = client
        .exchange_code(AuthorizationCode::new(code))
        .set_pkce_verifier(PkceCodeVerifier::new(oauth_state.pkce_verifier))
        .request_async(oauth2::reqwest::async_http_client)
        .await
        .map_err(|e| ServerFnError::new(format!("Failed to exchange code for token: {}", e)))?;

    // Fetch user info from the provider
    let user_info = fetch_user_info(&config, token_result.access_token().secret()).await?;

    // Create or get user
    let user = get_or_create_user_from_oauth(&user_info, &oauth_state.provider).await?;

    // Create session
    let session = user.new_session().await?;

    // Set session cookie
    let cookie = session.build_session_cookie();
    if let Some(resp) = use_context::<ResponseOptions>() {
        resp.insert_header(
            axum::http::header::SET_COOKIE,
            HeaderValue::from_str(&cookie.to_string()).unwrap(),
        );
    }

    Ok(oauth_state.callback_url)
}

#[cfg(feature = "ssr")]
async fn fetch_user_info(
    config: &crate::auth::oauth::OAuthConfig,
    access_token: &str,
) -> Result<crate::auth::oauth::OAuthUserInfo, ServerFnError> {
    use crate::auth::oauth::{OAuthProvider, OAuthUserInfo};

    let http_client = reqwest::Client::new();
    let response = http_client
        .get(&config.user_info_url)
        .header("Authorization", format!("Bearer {}", access_token))
        .header("User-Agent", "Tinkr-OAuth-Client")
        .send()
        .await
        .map_err(|e| ServerFnError::new(format!("Failed to fetch user info: {}", e)))?;

    let json: serde_json::Value = response
        .json()
        .await
        .map_err(|e| ServerFnError::new(format!("Failed to parse user info: {}", e)))?;

    // Parse based on provider
    let user_info = match config.provider {
        OAuthProvider::Github => OAuthUserInfo {
            id: json["id"].as_i64().unwrap_or(0).to_string(),
            email: json["email"].as_str().map(|s| s.to_string()),
            name: json["login"].as_str().map(|s| s.to_string()),
            avatar: json["avatar_url"].as_str().map(|s| s.to_string()),
        },
        OAuthProvider::Google => OAuthUserInfo {
            id: json["id"].as_str().unwrap_or("").to_string(),
            email: json["email"].as_str().map(|s| s.to_string()),
            name: json["name"].as_str().map(|s| s.to_string()),
            avatar: json["picture"].as_str().map(|s| s.to_string()),
        },
        OAuthProvider::Discord => OAuthUserInfo {
            id: json["id"].as_str().unwrap_or("").to_string(),
            email: json["email"].as_str().map(|s| s.to_string()),
            name: json["username"].as_str().map(|s| s.to_string()),
            avatar: json["avatar"].as_str().map(|avatar| {
                format!(
                    "https://cdn.discordapp.com/avatars/{}/{}.png",
                    json["id"].as_str().unwrap_or(""),
                    avatar
                )
            }),
        },
    };

    Ok(user_info)
}

#[cfg(feature = "ssr")]
async fn get_or_create_user_from_oauth(
    user_info: &crate::auth::oauth::OAuthUserInfo,
    provider: &OAuthProvider,
) -> Result<crate::auth::user::AdapterUser, ServerFnError> {
    use crate::theme::Theme;
    use crate::user::{AdapterUser, CreateUserData};

    // Try to find existing user by OAuth provider ID
    let existing_user = AdapterUser::get_user_by_oauth_id(&user_info.id, provider).await;

    if let Ok(user) = existing_user {
        return Ok(user);
    }

    // If user has email, try to find by email
    if let Some(ref email) = user_info.email {
        let email_addr = crate::EmailAddress(email.clone());
        if let Ok(user) = AdapterUser::get_user_by_email(email_addr).await {
            // Link OAuth account to existing user
            AdapterUser::link_oauth_account(&user.id, &user_info.id, provider).await?;
            return Ok(user);
        }
    }

    // Create new user
    let username = user_info
        .name
        .clone()
        .unwrap_or_else(|| format!("user_{}", &user_info.id[..8]));

    let user = AdapterUser::create_user(CreateUserData {
        email: crate::EmailAddress(user_info.email.clone().unwrap_or_default()),
        email_verified: Some(surrealdb::Datetime::from(chrono::Utc::now())), // OAuth providers verify emails
        image: user_info.avatar.clone(),
        name: username,
        theme: Theme::System,
        address1: None,
        address2: None,
        address3: None,
        postcode: None,
        phone: None,
        telephone: None,
        first_name: None,
        last_name: None,
    })
    .await?;

    // Link OAuth account
    AdapterUser::link_oauth_account(&user.id, &user_info.id, provider).await?;

    Ok(user)
}