Skip to content

Commit c2ca897

Browse files
committed
fix: do not send email for expired token
1 parent e6c8e45 commit c2ca897

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/models/token.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,12 @@ impl ApiToken {
110110
.filter(
111111
api_tokens::expired_at
112112
.is_not_null()
113-
.and(api_tokens::expired_at.lt(now.nullable() + days_until_expiry.days())),
113+
.and(api_tokens::expired_at.assume_not_null().gt(now)) // Ignore already expired tokens
114+
.and(
115+
api_tokens::expired_at
116+
.assume_not_null()
117+
.lt(now + days_until_expiry.days()),
118+
),
114119
)
115120
.filter(api_tokens::expiry_notification_at.is_null())
116121
.select(ApiToken::as_select())

src/worker/jobs/expiry_notification.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ mod tests {
100100
models::token::ApiToken, schema::api_tokens, test_util::test_db_connection,
101101
typosquat::test_util::Faker, util::token::PlainToken,
102102
};
103+
use diesel::dsl::IntervalDsl;
103104
use diesel::{QueryDsl, SelectableHelper};
104105
use lettre::Address;
105106

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

117117
let token: ApiToken = diesel::insert_into(api_tokens::table)
118118
.values((
119119
api_tokens::user_id.eq(user.id),
120120
api_tokens::name.eq("test_token"),
121121
api_tokens::token.eq(token.hashed()),
122-
api_tokens::expired_at.eq(expired_at),
122+
api_tokens::expired_at.eq(now.nullable() + ( EXPIRY_THRESHOLD-1).day())
123123
))
124124
.returning(ApiToken::as_returning())
125125
.get_result(&mut conn)?;
@@ -139,6 +139,25 @@ mod tests {
139139
.first::<ApiToken>(&mut conn)?;
140140
assert!(update_token.expiry_notification_at.is_some());
141141

142+
// Insert a already expired token.
143+
let token = PlainToken::generate();
144+
diesel::insert_into(api_tokens::table)
145+
.values((
146+
api_tokens::user_id.eq(user.id),
147+
api_tokens::name.eq("expired_token"),
148+
api_tokens::token.eq(token.hashed()),
149+
api_tokens::expired_at.eq(diesel::dsl::now.nullable() - 1.day()),
150+
))
151+
.returning(ApiToken::as_returning())
152+
.get_result(&mut conn)?;
153+
154+
// Check that the token is not about to expire.
155+
check(&emails, &mut conn)?;
156+
157+
// Check that no email was sent.
158+
let sent_mail = emails.mails_in_memory().unwrap();
159+
assert_eq!(sent_mail.len(), 1);
160+
142161
Ok(())
143162
}
144163
}

0 commit comments

Comments
 (0)