Skip to content

Commit

Permalink
fix: do not send email for expired token
Browse files Browse the repository at this point in the history
  • Loading branch information
Rustin170506 committed Apr 8, 2024
1 parent e6c8e45 commit d0efb44
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/models/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,12 @@ impl ApiToken {
.filter(
api_tokens::expired_at
.is_not_null()
.and(api_tokens::expired_at.lt(now.nullable() + days_until_expiry.days())),
.and(api_tokens::expired_at.assume_not_null().gt(now)) // Ignore already expired tokens
.and(
api_tokens::expired_at
.assume_not_null()
.lt(now + days_until_expiry.days()),
),
)
.filter(api_tokens::expiry_notification_at.is_null())
.select(ApiToken::as_select())
Expand Down
23 changes: 21 additions & 2 deletions src/worker/jobs/expiry_notification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ mod tests {
models::token::ApiToken, schema::api_tokens, test_util::test_db_connection,
typosquat::test_util::Faker, util::token::PlainToken,
};
use diesel::dsl::IntervalDsl;
use diesel::{QueryDsl, SelectableHelper};
use lettre::Address;

Expand All @@ -112,14 +113,13 @@ mod tests {
// Set up a user and a token that is about to expire.
let user = faker.user(&mut conn, "a", Some("[email protected]".to_owned()))?;
let token = PlainToken::generate();
let expired_at = diesel::dsl::now;

let token: ApiToken = diesel::insert_into(api_tokens::table)
.values((
api_tokens::user_id.eq(user.id),
api_tokens::name.eq("test_token"),
api_tokens::token.eq(token.hashed()),
api_tokens::expired_at.eq(expired_at),
api_tokens::expired_at.eq(now.nullable() + 2.days()),
))
.returning(ApiToken::as_returning())
.get_result(&mut conn)?;
Expand All @@ -139,6 +139,25 @@ mod tests {
.first::<ApiToken>(&mut conn)?;
assert!(update_token.expiry_notification_at.is_some());

// Insert a already expired token.
let token = PlainToken::generate();
diesel::insert_into(api_tokens::table)
.values((
api_tokens::user_id.eq(user.id),
api_tokens::name.eq("expired_token"),
api_tokens::token.eq(token.hashed()),
api_tokens::expired_at.eq(diesel::dsl::now.nullable() - 1.day()),
))
.returning(ApiToken::as_returning())
.get_result(&mut conn)?;

// Check that the token is not about to expire.
check(&emails, &mut conn)?;

// Check that no email was sent.
let sent_mail = emails.mails_in_memory().unwrap();
assert_eq!(sent_mail.len(), 1);

Ok(())
}
}

0 comments on commit d0efb44

Please sign in to comment.