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
use crate::{EmailAddress, session::get_user};

use leptos::prelude::*;

use partial_struct::Partial;
use serde::{Deserialize, Serialize};

#[cfg(feature = "ssr")]
use crate::{
    session::{AdapterSession, CreateSessionData},
    token::{CreateVerificationToken, VerificationToken},
    wallet::Wallet,
};

#[cfg(feature = "ssr")]
use crate::AppError;

#[cfg(feature = "ssr")]
use chrono::Utc;

#[cfg(feature = "ssr")]
use surrealdb::{Datetime, RecordId};

#[cfg(not(feature = "ssr"))]
use crate::{Datetime, RecordId};

use crate::theme::Theme;

#[derive(Debug, Clone, Serialize, Deserialize, Partial, PartialEq)]
#[partial(
    "CreateUserData",
    derive(Debug, Serialize, Deserialize, Clone),
    omit(id, is_admin, superadmin)
)]
#[partial(
    "UpdateUserData",
    derive(Debug, Serialize, Deserialize, Clone),
    omit(is_admin, superadmin)
)]
#[partial(
    "DeliveryDetails",
    derive(Debug, Serialize, Deserialize, Clone, PartialEq),
    omit(id, name, email_verified, is_admin, superadmin, theme, image)
)]
pub struct AdapterUser {
    pub id: RecordId,
    pub name: String,
    #[serde(rename = "emailVerified")]
    pub email_verified: Option<Datetime>,
    pub image: Option<String>,
    pub email: EmailAddress,
    pub is_admin: Option<bool>,
    pub superadmin: Option<bool>,
    #[serde(default)]
    pub theme: Theme,

    pub address1: Option<String>,
    pub address2: Option<String>,
    pub address3: Option<String>,
    pub postcode: Option<String>,
    pub phone: Option<String>,
    pub telephone: Option<String>,
    #[serde(rename = "firstName")]
    pub first_name: Option<String>,
    #[serde(rename = "lastName")]
    pub last_name: Option<String>,
}

impl Default for AdapterUser {
    fn default() -> Self {
        Self {
            id: RecordId::from_table_key("user", "default"),
            name: "Guest".to_string(),
            email_verified: None,
            image: None,
            email: EmailAddress::create_blank(),
            is_admin: Some(false),
            superadmin: Some(false),
            theme: Theme::System,
            address1: None,
            address2: None,
            address3: None,
            postcode: None,
            phone: None,
            telephone: None,
            first_name: None,
            last_name: None,
        }
    }
}

impl Default for DeliveryDetails {
    fn default() -> Self {
        Self {
            first_name: None,
            last_name: None,
            email: EmailAddress::create_blank(),
            address1: None,
            address2: None,
            address3: None,
            postcode: None,
            phone: None,
            telephone: None,
        }
    }
}

#[cfg(feature = "ssr")]
use crate::db_init;

#[cfg(feature = "ssr")]
impl AdapterUser {
    pub async fn create_user(user_data: CreateUserData) -> Result<Self, AppError> {
        use tracing::debug;

        let client = db_init().await?;

        debug!("Creating user with data: {:#?}", user_data);
        // if !user_data.email.is_empty() {
        //     let user = AdapterUser::get_user_by_email(user_data.email.clone()).await;
        //     if let Ok(_) = user {
        //         return Err(AppError::AuthError("Email already in use".into()));
        //     }
        // }
        debug!("Saving user to db");
        let create_result: Option<Self> = client.create("user").content(user_data).await?;
        let created: Self =
            create_result.ok_or_else(|| AppError::AuthError("Could not create user".into()))?;
        Ok(created)
    }

    pub async fn new_guest() -> Result<Self, AppError> {
        let user = Self::create_user(CreateUserData {
            email: EmailAddress::create_blank(),
            email_verified: None,
            name: format!("guest_{}", uuid::Uuid::new_v4()),
            image: None,
            theme: Theme::System,
            address1: None,
            address2: None,
            address3: None,
            postcode: None,
            phone: None,
            telephone: None,
            first_name: None,
            last_name: None,
        })
        .await?;
        Ok(user)
    }

    pub async fn create_test_user() -> Result<Self, AppError> {
        let user = Self::create_user(CreateUserData {
            email: EmailAddress::create_test_email(),
            email_verified: None,
            name: "Test User".to_string(),
            image: None,
            theme: Theme::System,
            address1: None,
            address2: None,
            address3: None,
            postcode: None,
            phone: None,
            telephone: None,
            first_name: None,
            last_name: None,
        })
        .await?;
        Ok(user)
    }

    pub fn is_super_admin(&self) -> Result<bool, AppError> {
        if let Some(superadmin) = self.superadmin {
            Ok(superadmin)
        } else {
            Err(AppError::AuthError("User is not a super admin".into()))
        }
    }

    pub async fn get_user(id: RecordId) -> Result<Self, AppError> {
        let client = db_init().await?;

        if id.table() != "user" {
            return Err(AppError::AuthError("Invalid user ID".into()));
        }

        let result: Option<Self> = client.select(id).await?;

        match result {
            Some(user) => Ok(user),
            None => Err(AppError::AuthError("User not found".into())),
        }
    }

    pub async fn get_user_by_email(email: EmailAddress) -> Result<Self, AppError> {
        let client = db_init().await?;

        let mut result = client
            .query("SELECT * FROM ONLY user WHERE email = $email LIMIT 1;")
            .bind(("email", email))
            .await?;

        let user: Option<Self> = result.take(0)?;

        match user {
            Some(user) => Ok(user),
            None => Err(AppError::AuthError("User not found".into())),
        }
    }

    pub async fn get_by_email(email: String) -> Result<Self, AppError> {
        use std::str::FromStr;
        let email_address = EmailAddress::from_str(&email)
            .map_err(|_| AppError::AuthError("Invalid email address".into()))?;
        Self::get_user_by_email(email_address).await
    }

    pub async fn get_user_by_account(
        provider_account_id: RecordId,
    ) -> Result<Option<AdapterUser>, AppError> {
        let client = db_init().await?;

        let mut result = client
            .query(
                "SELECT * FROM ONLY account WHERE providerAccountId = $providerAccountId LIMIT 1;",
            )
            .bind(("providerAccountId", provider_account_id))
            .await?;

        let user: Option<Self> = result.take(0)?;

        Ok(user)
    }

    pub async fn get_user_from_session(session_token: String) -> Result<Self, AppError> {
        use crate::db_seperate_connection;

        let client = db_seperate_connection().await?;

        let mut result = client
            .query("(SELECT user_id from ONLY session where session_token = $session_token LIMIT 1 FETCH user_id).user_id;")
            .bind(("session_token", session_token))
            .await?;

        let user: Option<Self> = result.take(0)?;

        if let Some(user) = user {
            Ok(user)
        } else {
            Err(AppError::AuthError(
                "User not found for session_token".into(),
            ))
        }
    }

    pub async fn set_verified_email(&self) -> Result<Self, AppError> {
        let client = db_init().await?;

        let mut user_update = client
            .query("UPDATE $userid SET email_verified = time::now() RETURN AFTER;")
            .bind(("userid", self.id.clone()))
            .await?;

        let user: Option<Self> = user_update.take(0)?;
        let user = user.ok_or_else(|| AppError::AuthError("User not found".into()))?;
        Ok(user)
    }

    pub async fn update_user(data: UpdateUserData) -> Result<AdapterUser, AppError> {
        let db = db_init().await?;

        let mut query = db
            .query("UPDATE $userid SET name = $name, email = $email, image = $image RETURN AFTER;")
            .bind(("userid", data.id.clone()))
            .bind(("name", data.name))
            .bind(("email", data.email.to_string()))
            .bind(("image", data.image))
            .await?;

        let user: Option<Self> = query.take(0)?;
        let user = user.ok_or_else(|| AppError::AuthError("User not found".into()))?;
        Ok(user)
    }

    pub async fn update_user_theme(&self, theme: Theme) -> Result<Self, AppError> {
        let client = db_init().await?;

        let mut query = client
            .query("UPDATE $userid SET theme = $theme RETURN AFTER;")
            .bind(("userid", self.id.clone()))
            .bind(("theme", theme))
            .await?;

        let user: Option<Self> = query.take(0)?;
        let user = user.ok_or_else(|| AppError::AuthError("User not found".into()))?;
        Ok(user)
    }

    pub async fn update_user_image(&self, image: String) -> Result<Self, AppError> {
        let client = db_init().await?;

        let mut query = client
            .query("UPDATE $userid SET image = $image RETURN AFTER;")
            .bind(("userid", self.id.clone()))
            .bind(("image", image))
            .await?;

        let user: Option<Self> = query.take(0)?;
        let user = user.ok_or_else(|| AppError::AuthError("User not found".into()))?;
        Ok(user)
    }

    pub async fn delete_user(&self) -> Result<(), AppError> {
        let client = db_init().await?;
        let _: Option<AdapterUser> = client.delete(&self.id).await?;
        // delete all related data?
        Ok(())
    }

    /// Creates a new verification token for the user.
    pub async fn new_verification_token(&self) -> Result<VerificationToken, AppError> {
        let token = VerificationToken::create_verification_token(CreateVerificationToken {
            email: self.email.clone(),
            user_id: self.id.clone(),
        })
        .await?;

        Ok(token)
    }

    pub async fn new_session(&self) -> Result<AdapterSession, AppError> {
        let session_data = CreateSessionData {
            user_id: self.id.clone(),
            session_token: uuid::Uuid::new_v4().to_string(),
            expires: Datetime::from(Utc::now() + chrono::Duration::days(365)),
        };

        AdapterSession::create_session(session_data).await
    }

    pub async fn get_all_users() -> Result<Vec<Self>, AppError> {
        let client = db_init().await?;
        let users: Vec<Self> = client.select("user").await?;
        Ok(users)
    }

    pub async fn wallets(&self) -> Result<Vec<Wallet>, AppError> {
        Wallet::get_by_user(self.id.clone()).await
    }

    pub async fn check_email_availability(&self, email: String) -> Result<bool, AppError> {
        use std::str::FromStr;
        let email_address = EmailAddress::from_str(&email)
            .map_err(|_| AppError::AuthError("Invalid email address".into()))?;

        let user = Self::get_user_by_email(email_address.clone()).await;
        if let Ok(user) = user {
            // If we found a user with this email and it's not the current user, it's not available
            if user.id != self.id {
                return Ok(false);
            }
        }

        // If the email is the same as the current user's, it's available
        if self.email == email_address {
            return Ok(true);
        }

        let client = db_init().await?;

        let mut result = client
            .query("SELECT count() as count FROM user WHERE email = $email;")
            .bind(("email", email_address.to_string()))
            .await?;

        #[derive(serde::Deserialize)]
        struct CountResult {
            count: i64,
        }

        let count: Option<CountResult> = result.take(0)?;
        let is_available = count.map_or(true, |c| c.count == 0);

        Ok(is_available)
    }

    pub async fn check_username_availability(username: String) -> Result<bool, AppError> {
        let client = db_init().await?;

        let mut result = client
            .query("SELECT count() as count FROM user WHERE name = $name;")
            .bind(("name", username.clone()))
            .await?;

        #[derive(serde::Deserialize)]
        struct CountResult {
            count: i64,
        }

        let count: Option<CountResult> = result.take(0)?;
        let is_available = count.map_or(true, |c| c.count == 0);

        Ok(is_available)
    }

    pub async fn get_user_by_oauth_id(
        oauth_id: &str,
        provider: &crate::auth::oauth::OAuthProvider,
    ) -> Result<Self, AppError> {
        let client = db_init().await?;

        let mut result = client
            .query("SELECT VALUE ->links->user FROM oauth_account WHERE provider_account_id = $oauth_id AND provider = $provider LIMIT 1;")
            .bind(("oauth_id", oauth_id.to_string()))
            .bind(("provider", provider.as_str().to_string()))
            .await?;

        let user_ids: Option<Vec<RecordId>> = result.take(0)?;

        if let Some(ids) = user_ids {
            if let Some(user_id) = ids.first() {
                return Self::get_user(user_id.clone()).await;
            }
        }

        Err(AppError::AuthError("User not found".into()))
    }

    pub async fn link_oauth_account(
        user_id: &RecordId,
        oauth_id: &str,
        provider: &crate::auth::oauth::OAuthProvider,
    ) -> Result<(), AppError> {
        let client = db_init().await?;

        client
            .query("CREATE oauth_account CONTENT { provider_account_id: $oauth_id, provider: $provider, user: $user_id } RETURN NONE;")
            .bind(("oauth_id", oauth_id.to_string()))
            .bind(("provider", provider.as_str().to_string()))
            .bind(("user_id", user_id.clone()))
            .await?;

        Ok(())
    }
}

#[server]
pub async fn check_username_availability(username: String) -> Result<bool, ServerFnError> {
    Ok(AdapterUser::check_username_availability(username.clone()).await?)
}

#[server]
pub async fn check_email_availability(email: String) -> Result<bool, ServerFnError> {
    let current_user = get_user().await?;
    let is_available = current_user.check_email_availability(email.clone()).await?;
    Ok(is_available)
}

#[server]
pub async fn update_user_profile(
    name: String,
    email: String,
) -> Result<AdapterUser, ServerFnError> {
    use crate::EmailAddress;
    use std::str::FromStr;

    let user = get_user().await?;

    // Check if name is available (if changed)
    if user.name != name {
        let name_available = check_username_availability(name.clone()).await?;
        if !name_available {
            return Err(ServerFnError::ServerError(
                "Username is already taken".to_string(),
            ));
        }
    }

    // Check if email is available (if changed)
    let email_changed = user.email.0 != email;
    if email_changed {
        let email_available = check_email_availability(email.clone()).await?;
        if !email_available {
            return Err(ServerFnError::ServerError(
                "Email is already in use".to_string(),
            ));
        }
    }

    // Parse email
    let email_address = match EmailAddress::from_str(&email) {
        Ok(addr) => addr,
        Err(_) => {
            return Err(ServerFnError::ServerError(
                "Invalid email format".to_string(),
            ));
        }
    };

    // If email changed, reset verification status
    let email_verified = if email_changed {
        None
    } else {
        user.email_verified
    };

    // Create update data
    let update_data = UpdateUserData {
        id: user.id.clone(),
        name,
        email_verified,
        image: user.image,
        email: email_address,
        theme: user.theme,
        address1: None,
        address2: None,
        address3: None,
        postcode: None,
        phone: None,
        telephone: None,
        first_name: None,
        last_name: None,
    };

    // Update user
    let updated_user = AdapterUser::update_user(update_data).await?;

    if email_changed {
        let _ = send_verification_email().await;
    }

    Ok(updated_user)
}

#[server]
pub async fn send_verification_email() -> Result<(), ServerFnError> {
    use crate::email::send_email;

    let user = get_user().await?;

    // Check if email is already verified
    if user.email_verified.is_some() {
        return Err(ServerFnError::ServerError(
            "Email is already verified".to_string(),
        ));
    }

    // Create verification token
    let token = user.new_verification_token().await?;

    // Construct verification URL
    let base_url =
        std::env::var("TINKR_AUTH_URL").unwrap_or_else(|_| "http://localhost:3000".to_string());
    let verification_url = format!(
        "{}/api/auth/callback/email-verify?token={}",
        base_url, token.token
    );

    let email_body = format!(
        r#"<html>
        <body>
            <h2>Verify Your Email</h2>
            <p>Hello {},</p>
            <p>Please click the link below to verify your email address:</p>
            <p><a href="{}">Verify Email</a></p>
            <p>Or copy and paste this URL into your browser:</p>
            <p>{}</p>
            <p>This link will expire in 1 hour.</p>
        </body>
        </html>"#,
        user.name, verification_url, verification_url
    );

    send_email(user.email.clone(), "Verify Your Email", &email_body).await?;

    Ok(())
}