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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};

use crate::auth::{
    AccessTokenClaims, Auth, PaginationParams, Permission, Role, User, UserChangeset, UserSession,
    UserSessionChangeset, UserSessionJson, UserSessionResponse, ID,
};
use crate::{Database, Mailer};

use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};

pub const COOKIE_NAME: &str = "refresh_token";

lazy_static! {
    static ref ARGON_CONFIG: argon2::Config<'static> = argon2::Config {
        variant: argon2::Variant::Argon2id,
        version: argon2::Version::Version13,
        secret: match std::env::var("SECRET_KEY") {
            Ok(s) => Box::leak(s.into_boxed_str()).as_bytes(),
            Err(_) => panic!("No SECRET_KEY environment variable set!"),
        },
        ..Default::default()
    };
}

#[cfg(not(debug_assertions))]
type Seconds = i64;
type StatusCode = i32;
type Message = &'static str;

#[derive(Deserialize, Serialize)]
#[cfg_attr(feature = "plugin_utoipa", derive(utoipa::ToSchema))]
/// Rust struct representing the Json body of
/// POST requests to the .../login endpoint
pub struct LoginInput {
    email: String,
    password: String,
    device: Option<String>,
    #[cfg(not(debug_assertions))]
    ttl: Option<Seconds>, // Seconds
    #[cfg(debug_assertions)]
    ttl: Option<i64>, // Seconds
}

#[derive(Debug, Serialize, Deserialize)]
/// TODO: documentation
pub struct RefreshTokenClaims {
    exp: usize,
    sub: ID,
    token_type: String,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "plugin_utoipa", derive(utoipa::ToSchema))]
/// Rust struct representing the Json body of
/// POST requests to the .../register endpoint
pub struct RegisterInput {
    email: String,
    password: String,
}

#[derive(Debug, Serialize, Deserialize)]
/// TODO: documentation
pub struct RegistrationClaims {
    exp: usize,
    sub: ID,
    token_type: String,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "plugin_utoipa", derive(utoipa::IntoParams))]
/// Rust struct representing the Json body of
/// GET requests to the .../activate endpoint
pub struct ActivationInput {
    activation_token: String,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "plugin_utoipa", derive(utoipa::ToSchema))]
/// Rust struct representing the Json body of
/// POST requests to the /forgot endpoint
pub struct ForgotInput {
    email: String,
}

#[derive(Debug, Serialize, Deserialize)]
/// TODO: documentation
pub struct ResetTokenClaims {
    exp: usize,
    sub: ID,
    token_type: String,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "plugin_utoipa", derive(utoipa::ToSchema))]
/// Rust struct representing the Json body of
/// POST requests to the /change endpoint
pub struct ChangeInput {
    old_password: String,
    new_password: String,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "plugin_utoipa", derive(utoipa::ToSchema))]
/// Rust struct representing the Json body of
/// POST requests to the /reset endpoint
pub struct ResetInput {
    reset_token: String,
    new_password: String,
}

/// /sessions
///
/// queries [`db`](`Database`) for all sessions owned by the User
/// associated with [`auth`](`Auth`)
///
/// breaks up the results of that query as defined by [`info`](`PaginationParams`)
///
///
/// # Returns [`Result`]
/// - Ok([`UserSessionResponse`])
///     - the results of the query paginated according to [`info`](`PaginationParams`)
/// - Err([`StatusCode`], [`Message`])
pub fn get_sessions(
    db: &Database,
    auth: &Auth,
    info: &PaginationParams,
) -> Result<UserSessionResponse, (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    let sessions = UserSession::read_all(&mut db, info, auth.user_id);

    if sessions.is_err() {
        return Err((500, "Could not fetch sessions."));
    }

    let sessions: Vec<UserSession> = sessions.unwrap();
    let mut sessions_json: Vec<UserSessionJson> = vec![];

    for session in sessions {
        let session_json = UserSessionJson {
            id: session.id,
            device: session.device,
            created_at: session.created_at,
            #[cfg(not(feature = "database_sqlite"))]
            updated_at: session.updated_at,
        };

        sessions_json.push(session_json);
    }

    let num_sessions = UserSession::count_all(&mut db, auth.user_id);
    if num_sessions.is_err() {
        return Err((500, "Could not fetch sessions."));
    }

    let num_sessions = num_sessions.unwrap();
    let num_pages = (num_sessions / info.page_size) + i64::from(num_sessions % info.page_size != 0);

    let resp = UserSessionResponse {
        sessions: sessions_json,
        num_pages,
    };

    Ok(resp)
}

/// /sessions/{id}
///
/// deletes the entry in the `user_session` with the specified [`item_id`](`ID`) from
/// [`db`](`Database`) if it's owned by the User associated with [`auth`](`Auth`)
///
/// # Returns [`Result`]
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn destroy_session(
    db: &Database,
    auth: &Auth,
    item_id: ID,
) -> Result<(), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    let user_session = UserSession::read(&mut db, item_id);

    if user_session.is_err() {
        return Err((500, "Internal error."));
    }

    let user_session = user_session.unwrap();

    if user_session.user_id != auth.user_id {
        return Err((404, "Session not found."));
    }

    if UserSession::delete(&mut db, user_session.id).is_err() {
        return Err((500, "Could not delete session."));
    }

    Ok(())
}

/// /sessions
///
/// destroys all entries in the `user_session` table in [`db`](`Database`) owned
/// by the User associated with [`auth`](`Auth`)
///
/// # Returns [`Result`]
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn destroy_sessions(db: &Database, auth: &Auth) -> Result<(), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    if UserSession::delete_all_for_user(&mut db, auth.user_id).is_err() {
        return Err((500, "Could not delete sessions."));
    }

    Ok(())
}

type AccessToken = String;
type RefreshToken = String;

/// /login
///
/// creates a user session for the user associated with [`item`](`LoginInput`)
/// in the request body (have the `content-type` header set to `application/json` and content that can be deserialized into [`LoginInput`])
///
/// # Returns [`Result`]
/// - Ok([`AccessToken`], [`RefreshToken`])
///     - an access token that should be sent to the user in the response body,
///     - a reset token that should be sent as a secure, http-only, and same_site=strict cookie.
/// - Err([`StatusCode`], [`Message`])
pub fn login(
    db: &Database,
    item: &LoginInput,
) -> Result<(AccessToken, RefreshToken), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    // verify device
    let mut device = None;
    if item.device.is_some() {
        let device_string = item.device.as_ref().unwrap();
        if device_string.len() > 256 {
            return Err((400, "'device' cannot be longer than 256 characters."));
        } else {
            device = Some(device_string.to_owned());
        }
    }

    let user = User::find_by_email(&mut db, item.email.clone());

    if user.is_err() {
        return Err((401, "Invalid credentials."));
    }

    let user = user.unwrap();

    if !user.activated {
        return Err((400, "Account has not been activated."));
    }

    let is_valid = argon2::verify_encoded_ext(
        &user.hash_password,
        item.password.as_bytes(),
        ARGON_CONFIG.secret,
        ARGON_CONFIG.ad,
    )
    .unwrap();

    if !is_valid {
        return Err((401, "Invalid credentials."));
    }

    let permissions = Permission::fetch_all(&mut db, user.id);
    if permissions.is_err() {
        println!("{:#?}", permissions.err());
        return Err((500, "An internal server error occurred."));
    }
    let permissions = permissions.unwrap();

    let roles = Role::fetch_all(&mut db, user.id);
    if roles.is_err() {
        println!("{:#?}", roles.err());
        return Err((500, "An internal server error occurred."));
    }
    let roles = roles.unwrap();

    let access_token_duration = chrono::Duration::seconds(if item.ttl.is_some() {
        std::cmp::max(item.ttl.unwrap(), 1)
    } else {
        /* 15 minutes */
        15 * 60
    });

    let access_token_claims = AccessTokenClaims {
        exp: (chrono::Utc::now() + access_token_duration).timestamp() as usize,
        sub: user.id,
        token_type: "access_token".to_string(),
        roles,
        permissions,
    };

    let refresh_token_claims = RefreshTokenClaims {
        exp: (chrono::Utc::now() + chrono::Duration::hours(24)).timestamp() as usize,
        sub: user.id,
        token_type: "refresh_token".to_string(),
    };

    let access_token = encode(
        &Header::default(),
        &access_token_claims,
        &EncodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
    )
    .unwrap();

    let refresh_token = encode(
        &Header::default(),
        &refresh_token_claims,
        &EncodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
    )
    .unwrap();

    let user_session = UserSession::create(
        &mut db,
        &UserSessionChangeset {
            user_id: user.id,
            refresh_token: refresh_token.clone(),
            device,
        },
    );

    if user_session.is_err() {
        return Err((500, "Could not create a session."));
    }

    Ok((access_token, refresh_token))
}

/// /logout
/// If this is successful, delete the cookie storing the refresh token
///
/// # Returns [`Result`]
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn logout(db: &Database, refresh_token: Option<&'_ str>) -> Result<(), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    if refresh_token.is_none() {
        return Err((401, "Invalid session."));
    }

    let refresh_token = refresh_token.unwrap();

    let session = UserSession::find_by_refresh_token(&mut db, refresh_token);

    if session.is_err() {
        return Err((401, "Invalid session."));
    }

    let session = session.unwrap();

    let is_deleted = UserSession::delete(&mut db, session.id);

    if is_deleted.is_err() {
        return Err((401, "Could not delete session."));
    }

    Ok(())
}

/// /refresh
///
/// refreshes the user session associated with the clients refresh_token cookie
///
/// # Returns [`Result`]
/// - Ok([`AccessToken`], [`RefreshToken`])
///     - an access token that should be sent to the user in the response body,
///     - a reset token that should be sent as a secure, http-only, and same_site=strict cookie.
/// - Err([`StatusCode`], [`Message`])
pub fn refresh(
    db: &Database,
    refresh_token_str: Option<&'_ str>,
) -> Result<(AccessToken, RefreshToken), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    if refresh_token_str.is_none() {
        return Err((401, "Invalid session."));
    }

    let refresh_token_str = refresh_token_str.unwrap();

    let refresh_token = decode::<RefreshTokenClaims>(
        refresh_token_str,
        &DecodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
        &Validation::default(),
    );

    if refresh_token.is_err() {
        return Err((401, "Invalid token."));
    }

    let refresh_token = refresh_token.unwrap();

    if !refresh_token
        .claims
        .token_type
        .eq_ignore_ascii_case("refresh_token")
    {
        return Err((401, "Invalid token."));
    }

    let session = UserSession::find_by_refresh_token(&mut db, refresh_token_str);

    if session.is_err() {
        return Err((401, "Invalid session."));
    }

    let session = session.unwrap();

    let permissions = Permission::fetch_all(&mut db, session.user_id);
    if permissions.is_err() {
        return Err((500, "An internal server error occurred."));
    }
    let permissions = permissions.unwrap();

    let roles = Role::fetch_all(&mut db, session.user_id);
    if roles.is_err() {
        return Err((500, "An internal server error occurred."));
    }
    let roles = roles.unwrap();

    let access_token_claims = AccessTokenClaims {
        exp: (chrono::Utc::now() + chrono::Duration::minutes(15)).timestamp() as usize,
        sub: session.user_id,
        token_type: "access_token".to_string(),
        roles,
        permissions,
    };

    let refresh_token_claims = RefreshTokenClaims {
        exp: (chrono::Utc::now() + chrono::Duration::hours(24)).timestamp() as usize,
        sub: session.user_id,
        token_type: "refresh_token".to_string(),
    };

    let access_token = encode(
        &Header::default(),
        &access_token_claims,
        &EncodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
    )
    .unwrap();

    let refresh_token_str = encode(
        &Header::default(),
        &refresh_token_claims,
        &EncodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
    )
    .unwrap();

    // update session with the new refresh token
    let session_update = UserSession::update(
        &mut db,
        session.id,
        &UserSessionChangeset {
            user_id: session.user_id,
            refresh_token: refresh_token_str.clone(),
            device: session.device,
        },
    );

    if session_update.is_err() {
        return Err((500, "Could not update the session."));
    }

    Ok((access_token, refresh_token_str))
}

/// /register
///
/// creates a new User with the information in [`item`](`RegisterInput`)
///
/// sends an email, using [`mailer`](`Mailer`), to the email address in [`item`](`RegisterInput`)
/// that contains a unique link that allows the recipient to activate the account associated with
/// that email address
///
/// # Returns [`Result`]
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn register(
    db: &Database,
    item: &RegisterInput,
    mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    let user = User::find_by_email(&mut db, item.email.to_string());

    if let Ok(user) = user {
        if !user.activated {
            User::delete(&mut db, user.id).unwrap();
        } else {
            return Err((400, "Already registered."));
        }
    }

    let salt = generate_salt();
    let hash = argon2::hash_encoded(item.password.as_bytes(), &salt, &ARGON_CONFIG).unwrap();

    let user = User::create(
        &mut db,
        &UserChangeset {
            activated: false,
            email: item.email.clone(),
            hash_password: hash,
        },
    )
    .unwrap();

    let registration_claims = RegistrationClaims {
        exp: (chrono::Utc::now() + chrono::Duration::days(30)).timestamp() as usize,
        sub: user.id,
        token_type: "activation_token".to_string(),
    };

    let token = encode(
        &Header::default(),
        &registration_claims,
        &EncodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
    )
    .unwrap();

    mailer
        .templates
        .send_register(mailer, &user.email, &format!("activate?token={token}"));

    Ok(())
}

/// /activate
///
/// activates the account associated with the token in [`item`](`ActivationInput`)
///
/// # Returns [`Result`]
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn activate(
    db: &Database,
    item: &ActivationInput,
    mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    let token = decode::<RegistrationClaims>(
        &item.activation_token,
        &DecodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
        &Validation::default(),
    );

    if token.is_err() {
        return Err((401, "Invalid token."));
    }

    let token = token.unwrap();

    if !token
        .claims
        .token_type
        .eq_ignore_ascii_case("activation_token")
    {
        return Err((401, "Invalid token."));
    }

    let user = User::read(&mut db, token.claims.sub);

    if user.is_err() {
        return Err((400, "Invalid token."));
    }

    let user = user.unwrap();

    if user.activated {
        return Err((200, "Already activated!"));
    }

    let activated_user = User::update(
        &mut db,
        user.id,
        &UserChangeset {
            activated: true,
            email: user.email.clone(),
            hash_password: user.hash_password,
        },
    );

    if activated_user.is_err() {
        return Err((500, "Could not activate user."));
    }

    mailer.templates.send_activated(mailer, &user.email);

    Ok(())
}

/// /forgot
/// sends an email to the email in the ['ForgotInput'] Json in the request body
/// that will allow the user associated with that email to change their password
///
/// sends an email, using [`mailer`](`Mailer`), to the email address in [`item`](`RegisterInput`)
/// that contains a unique link that allows the recipient to reset the password
/// of the account associated with that email address (or create a new account if there is
/// no accound accosiated with the email address)
///
/// # Returns [`Result`]
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn forgot_password(
    db: &Database,
    item: &ForgotInput,
    mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    let user_result = User::find_by_email(&mut db, item.email.clone());

    if let Ok(user) = user_result {
        // if !user.activated {
        //   return Ok(HttpResponse::build(400).body(" has not been activate"))
        // }

        let reset_token_claims = ResetTokenClaims {
            exp: (chrono::Utc::now() + chrono::Duration::hours(24)).timestamp() as usize,
            sub: user.id,
            token_type: "reset_token".to_string(),
        };

        let reset_token = encode(
            &Header::default(),
            &reset_token_claims,
            &EncodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
        )
        .unwrap();

        let link = &format!("reset?token={reset_token}");
        mailer
            .templates
            .send_recover_existent_account(mailer, &user.email, link);
    } else {
        let link = &"register".to_string();
        mailer
            .templates
            .send_recover_nonexistent_account(mailer, &item.email, link);
    }

    Ok(())
}

/// /change
///
/// change the password of the User associated with [`auth`](`Auth`)
/// from [`item.old_password`](`ChangeInput`) to [`item.new_password`](`ChangeInput`)
///
/// # Returns [`Result`]
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn change_password(
    db: &Database,
    item: &ChangeInput,
    auth: &Auth,
    mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
    if item.old_password.is_empty() || item.new_password.is_empty() {
        return Err((400, "Missing password"));
    }

    if item.old_password.eq(&item.new_password) {
        return Err((400, "The new password must be different"));
    }

    let mut db = db.pool.get().unwrap();

    let user = User::read(&mut db, auth.user_id);

    if user.is_err() {
        return Err((500, "Could not find user"));
    }

    let user = user.unwrap();

    if !user.activated {
        return Err((400, "Account has not been activated"));
    }

    let is_old_password_valid = argon2::verify_encoded_ext(
        &user.hash_password,
        item.old_password.as_bytes(),
        ARGON_CONFIG.secret,
        ARGON_CONFIG.ad,
    )
    .unwrap();

    if !is_old_password_valid {
        return Err((400, "Invalid credentials"));
    }

    let salt = generate_salt();
    let new_hash =
        argon2::hash_encoded(item.new_password.as_bytes(), &salt, &ARGON_CONFIG).unwrap();

    let updated_user = User::update(
        &mut db,
        auth.user_id,
        &UserChangeset {
            email: user.email.clone(),
            hash_password: new_hash,
            activated: user.activated,
        },
    );

    if updated_user.is_err() {
        return Err((500, "Could not update password"));
    }

    mailer.templates.send_password_changed(mailer, &user.email);

    Ok(())
}

/// /check
///
/// just a lifeline function, clients can post to this endpoint to check
/// if the auth service is running
pub fn check(_: &Auth) {}

/// reset
///
/// changes the password of the user associated with [`item.reset_token`](`ResetInput`)
/// to [`item.new_password`](`ResetInput`)
///
/// # Returns [`Result`]
/// - Ok(`()`)
/// - Err([`StatusCode`], [`Message`])
pub fn reset_password(
    db: &Database,
    item: &ResetInput,
    mailer: &Mailer,
) -> Result<(), (StatusCode, Message)> {
    let mut db = db.pool.get().unwrap();

    if item.new_password.is_empty() {
        return Err((400, "Missing password"));
    }

    let token = decode::<ResetTokenClaims>(
        &item.reset_token,
        &DecodingKey::from_secret(std::env::var("SECRET_KEY").unwrap().as_ref()),
        &Validation::default(),
    );

    if token.is_err() {
        return Err((401, "Invalid token."));
    }

    let token = token.unwrap();

    if !token.claims.token_type.eq_ignore_ascii_case("reset_token") {
        return Err((401, "Invalid token."));
    }

    let user = User::read(&mut db, token.claims.sub);

    if user.is_err() {
        return Err((400, "Invalid token."));
    }

    let user = user.unwrap();

    if !user.activated {
        return Err((400, "Account has not been activated"));
    }

    let salt = generate_salt();
    let new_hash =
        argon2::hash_encoded(item.new_password.as_bytes(), &salt, &ARGON_CONFIG).unwrap();

    let update = User::update(
        &mut db,
        user.id,
        &UserChangeset {
            email: user.email.clone(),
            hash_password: new_hash,
            activated: user.activated,
        },
    );

    if update.is_err() {
        return Err((500, "Could not update password"));
    }

    mailer.templates.send_password_reset(mailer, &user.email);

    Ok(())
}

pub fn generate_salt() -> [u8; 16] {
    use rand::Fill;
    let mut salt = [0; 16];
    salt.try_fill(&mut rand::thread_rng()).unwrap();
    salt
}