File size: 27,805 Bytes
f0743f4 | 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 810 811 812 813 814 815 816 817 818 819 820 821 822 823 | import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import type * as t from '~/types';
import { createTokenMethods } from './token';
import tokenSchema from '~/schema/token';
/** Mocking logger */
jest.mock('~/config/winston', () => ({
error: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
}));
let mongoServer: MongoMemoryServer;
let Token: mongoose.Model<t.IToken>;
let methods: ReturnType<typeof createTokenMethods>;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
await mongoose.connect(mongoUri);
/** Register models */
Token = mongoose.models.Token || mongoose.model<t.IToken>('Token', tokenSchema);
/** Initialize methods */
methods = createTokenMethods(mongoose);
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
beforeEach(async () => {
await mongoose.connection.dropDatabase();
});
describe('Token Methods - Detailed Tests', () => {
describe('createToken', () => {
test('should create a token with correct expiry time', async () => {
const userId = new mongoose.Types.ObjectId();
const tokenData = {
token: 'test-token-123',
userId: userId,
email: 'test@example.com',
expiresIn: 3600, // 1 hour
};
const token = await methods.createToken(tokenData);
expect(token).toBeDefined();
expect(token.token).toBe(tokenData.token);
expect(token.userId.toString()).toBe(userId.toString());
expect(token.email).toBe(tokenData.email);
// Check expiry time
const expectedExpiry = new Date(token.createdAt.getTime() + tokenData.expiresIn * 1000);
expect(token.expiresAt.getTime()).toBe(expectedExpiry.getTime());
});
test('should create token with all required fields', async () => {
const userId = new mongoose.Types.ObjectId();
const tokenData = {
token: 'minimal-token',
userId: userId,
expiresIn: 1800,
};
const token = await methods.createToken(tokenData);
expect(token).toBeDefined();
expect(token.token).toBe(tokenData.token);
expect(token.userId.toString()).toBe(userId.toString());
expect(token.email).toBeUndefined();
});
test('should create token with identifier field', async () => {
const userId = new mongoose.Types.ObjectId();
const tokenData = {
token: 'identifier-token',
userId: userId,
identifier: 'oauth-identifier-123',
expiresIn: 7200,
};
const token = await methods.createToken(tokenData);
expect(token).toBeDefined();
expect(token.identifier).toBe(tokenData.identifier);
});
});
describe('findToken', () => {
let user1Id: mongoose.Types.ObjectId;
let user2Id: mongoose.Types.ObjectId;
beforeEach(async () => {
user1Id = new mongoose.Types.ObjectId();
user2Id = new mongoose.Types.ObjectId();
await Token.create([
{
token: 'token-1',
userId: user1Id,
email: 'user1@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
},
{
token: 'token-2',
userId: user2Id,
email: 'user2@example.com',
identifier: 'oauth-123',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
},
{
token: 'token-3',
userId: user1Id,
email: 'user1-alt@example.com', // Different email for realistic scenario
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
},
]);
});
test('should find token by token value', async () => {
const found = await methods.findToken({ token: 'token-1' });
expect(found).toBeDefined();
expect(found?.token).toBe('token-1');
expect(found?.userId.toString()).toBe(user1Id.toString());
});
test('should find token by userId', async () => {
const found = await methods.findToken({ userId: user2Id.toString() });
expect(found).toBeDefined();
expect(found?.token).toBe('token-2');
expect(found?.email).toBe('user2@example.com');
});
test('should find token by email', async () => {
const found = await methods.findToken({ email: 'user2@example.com' });
expect(found).toBeDefined();
expect(found?.token).toBe('token-2');
expect(found?.userId.toString()).toBe(user2Id.toString());
});
test('should find token by identifier', async () => {
const found = await methods.findToken({ identifier: 'oauth-123' });
expect(found).toBeDefined();
expect(found?.token).toBe('token-2');
expect(found?.identifier).toBe('oauth-123');
});
test('should find token by multiple criteria (AND condition)', async () => {
const found = await methods.findToken({
userId: user1Id.toString(),
email: 'user1@example.com',
});
expect(found).toBeDefined();
expect(found?.token).toBe('token-1'); // Should find the only token matching both criteria
});
test('should return null for non-existent token', async () => {
const found = await methods.findToken({ token: 'non-existent' });
expect(found).toBeNull();
});
test('should return null when criteria do not match together', async () => {
const found = await methods.findToken({
userId: user1Id.toString(),
email: 'user2@example.com', // Mismatched email
});
expect(found).toBeNull();
});
test('should find most recent token with sort option', async () => {
const recentUserId = new mongoose.Types.ObjectId();
// Create tokens with different timestamps
const oldDate = new Date(Date.now() - 7200000); // 2 hours ago
const midDate = new Date(Date.now() - 3600000); // 1 hour ago
const newDate = new Date(); // now
await Token.create([
{
token: 'old-token',
userId: recentUserId,
email: 'recent@example.com',
createdAt: oldDate,
expiresAt: new Date(oldDate.getTime() + 86400000),
},
{
token: 'mid-token',
userId: recentUserId,
email: 'recent@example.com',
createdAt: midDate,
expiresAt: new Date(midDate.getTime() + 86400000),
},
{
token: 'new-token',
userId: recentUserId,
email: 'recent@example.com',
createdAt: newDate,
expiresAt: new Date(newDate.getTime() + 86400000),
},
]);
// Find most recent token for the user with sort option
const found = await methods.findToken(
{ userId: recentUserId.toString() },
{ sort: { createdAt: -1 } },
);
expect(found).toBeDefined();
expect(found?.token).toBe('new-token');
expect(found?.createdAt.getTime()).toBe(newDate.getTime());
});
test('should find oldest token with ascending sort', async () => {
const sortUserId = new mongoose.Types.ObjectId();
const oldDate = new Date(Date.now() - 7200000);
const midDate = new Date(Date.now() - 3600000);
const newDate = new Date();
await Token.create([
{
token: 'sort-old',
userId: sortUserId,
email: 'sort@example.com',
createdAt: oldDate,
expiresAt: new Date(oldDate.getTime() + 86400000),
},
{
token: 'sort-mid',
userId: sortUserId,
email: 'sort@example.com',
createdAt: midDate,
expiresAt: new Date(midDate.getTime() + 86400000),
},
{
token: 'sort-new',
userId: sortUserId,
email: 'sort@example.com',
createdAt: newDate,
expiresAt: new Date(newDate.getTime() + 86400000),
},
]);
// Find oldest token with ascending sort
const found = await methods.findToken(
{ userId: sortUserId.toString() },
{ sort: { createdAt: 1 } },
);
expect(found).toBeDefined();
expect(found?.token).toBe('sort-old');
expect(found?.createdAt.getTime()).toBe(oldDate.getTime());
});
test('should handle multiple sort criteria', async () => {
const multiSortUserId = new mongoose.Types.ObjectId();
const sameDate = new Date();
await Token.create([
{
token: 'token-a',
userId: multiSortUserId,
email: 'z@example.com',
createdAt: sameDate,
expiresAt: new Date(sameDate.getTime() + 86400000),
},
{
token: 'token-b',
userId: multiSortUserId,
email: 'a@example.com',
createdAt: sameDate,
expiresAt: new Date(sameDate.getTime() + 86400000),
},
{
token: 'token-c',
userId: multiSortUserId,
email: 'm@example.com',
createdAt: new Date(Date.now() - 1000), // slightly older
expiresAt: new Date(Date.now() + 86400000),
},
]);
// Sort by createdAt descending, then by email ascending
const found = await methods.findToken(
{ userId: multiSortUserId.toString() },
{ sort: { createdAt: -1, email: 1 } },
);
expect(found).toBeDefined();
// Should get token-b (same recent date but 'a@example.com' comes first alphabetically)
expect(found?.token).toBe('token-b');
expect(found?.email).toBe('a@example.com');
});
test('should find token with projection option', async () => {
const projectionUserId = new mongoose.Types.ObjectId();
await Token.create({
token: 'projection-token',
userId: projectionUserId,
email: 'projection@example.com',
identifier: 'oauth-projection',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 86400000),
});
// Find token with projection to only include specific fields
const found = await methods.findToken(
{ userId: projectionUserId.toString() },
{ projection: { token: 1, email: 1 } },
);
expect(found).toBeDefined();
expect(found?.token).toBe('projection-token');
expect(found?.email).toBe('projection@example.com');
// Note: _id is usually included by default unless explicitly excluded
});
test('should respect combined query options', async () => {
const combinedUserId = new mongoose.Types.ObjectId();
// Create multiple tokens with different attributes
await Token.create([
{
token: 'combined-1',
userId: combinedUserId,
email: 'combined1@example.com',
createdAt: new Date(Date.now() - 7200000),
expiresAt: new Date(Date.now() + 86400000),
},
{
token: 'combined-2',
userId: combinedUserId,
email: 'combined2@example.com',
createdAt: new Date(Date.now() - 3600000),
expiresAt: new Date(Date.now() + 86400000),
},
{
token: 'combined-3',
userId: combinedUserId,
email: 'combined3@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 86400000),
},
]);
// Use multiple query options together
const found = await methods.findToken(
{ userId: combinedUserId.toString() },
{
sort: { createdAt: -1 },
projection: { token: 1, createdAt: 1 },
},
);
expect(found).toBeDefined();
expect(found?.token).toBe('combined-3'); // Most recent
expect(found?.createdAt).toBeDefined();
});
});
describe('updateToken', () => {
let updateUserId: mongoose.Types.ObjectId;
beforeEach(async () => {
updateUserId = new mongoose.Types.ObjectId();
await Token.create({
token: 'update-token',
userId: updateUserId,
email: 'update@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
});
});
test('should update token by token value', async () => {
const updated = await methods.updateToken(
{ token: 'update-token' },
{ email: 'newemail@example.com' },
);
expect(updated).toBeDefined();
expect(updated?.email).toBe('newemail@example.com');
expect(updated?.userId.toString()).toBe(updateUserId.toString()); // Unchanged
});
test('should update token by userId', async () => {
const updated = await methods.updateToken(
{ userId: updateUserId.toString() },
{ email: 'newemail@example.com' },
);
expect(updated).toBeDefined();
expect(updated?.email).toBe('newemail@example.com');
expect(updated?.token).toBe('update-token'); // Unchanged
});
test('should return null for non-existent token', async () => {
const updated = await methods.updateToken(
{ token: 'non-existent' },
{ email: 'newemail@example.com' },
);
expect(updated).toBeNull();
});
test('should update expiresAt when expiresIn is provided', async () => {
const beforeUpdate = Date.now();
const newExpiresIn = 7200;
const updated = await methods.updateToken(
{ token: 'update-token' },
{ expiresIn: newExpiresIn },
);
const afterUpdate = Date.now();
expect(updated).toBeDefined();
expect(updated?.expiresAt).toBeDefined();
const expectedMinExpiry = beforeUpdate + newExpiresIn * 1000;
const expectedMaxExpiry = afterUpdate + newExpiresIn * 1000;
expect(updated!.expiresAt.getTime()).toBeGreaterThanOrEqual(expectedMinExpiry);
expect(updated!.expiresAt.getTime()).toBeLessThanOrEqual(expectedMaxExpiry);
});
test('should not modify expiresAt when expiresIn is not provided', async () => {
const original = await Token.findOne({ token: 'update-token' });
const originalExpiresAt = original!.expiresAt.getTime();
const updated = await methods.updateToken(
{ token: 'update-token' },
{ email: 'changed@example.com' },
);
expect(updated).toBeDefined();
expect(updated?.email).toBe('changed@example.com');
expect(updated!.expiresAt.getTime()).toBe(originalExpiresAt);
});
});
describe('deleteTokens', () => {
let user1Id: mongoose.Types.ObjectId;
let user2Id: mongoose.Types.ObjectId;
let user3Id: mongoose.Types.ObjectId;
let oauthUserId: mongoose.Types.ObjectId;
beforeEach(async () => {
user1Id = new mongoose.Types.ObjectId();
user2Id = new mongoose.Types.ObjectId();
user3Id = new mongoose.Types.ObjectId();
oauthUserId = new mongoose.Types.ObjectId();
await Token.create([
{
token: 'verify-token-1',
userId: user1Id,
email: 'user1@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
},
{
token: 'verify-token-2',
userId: user2Id,
email: 'user2@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
},
{
token: 'verify-token-3',
userId: user3Id,
email: 'user3@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
},
{
token: 'oauth-token',
userId: oauthUserId,
identifier: 'oauth-identifier-456',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
},
]);
});
test('should delete only tokens matching specific token value', async () => {
const result = await methods.deleteTokens({ token: 'verify-token-1' });
expect(result.deletedCount).toBe(1);
// Verify other tokens still exist
const remainingTokens = await Token.find({});
expect(remainingTokens).toHaveLength(3);
expect(remainingTokens.find((t) => t.token === 'verify-token-2')).toBeDefined();
expect(remainingTokens.find((t) => t.token === 'verify-token-3')).toBeDefined();
expect(remainingTokens.find((t) => t.token === 'oauth-token')).toBeDefined();
});
test('should delete only tokens matching specific userId', async () => {
// Create another token for user-1
await Token.create({
token: 'another-user-1-token',
userId: user1Id,
email: 'user1@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
});
const result = await methods.deleteTokens({ userId: user1Id.toString() });
expect(result.deletedCount).toBe(2); // Both tokens for user-1
const remainingTokens = await Token.find({});
expect(remainingTokens).toHaveLength(3);
expect(remainingTokens.every((t) => t.userId.toString() !== user1Id.toString())).toBe(true);
});
test('should delete only tokens matching specific email', async () => {
const result = await methods.deleteTokens({ email: 'user2@example.com' });
expect(result.deletedCount).toBe(1);
const remainingTokens = await Token.find({});
expect(remainingTokens).toHaveLength(3);
expect(remainingTokens.find((t) => t.email === 'user2@example.com')).toBeUndefined();
});
test('should delete only tokens matching specific identifier', async () => {
const result = await methods.deleteTokens({ identifier: 'oauth-identifier-456' });
expect(result.deletedCount).toBe(1);
const remainingTokens = await Token.find({});
expect(remainingTokens).toHaveLength(3);
expect(remainingTokens.find((t) => t.identifier === 'oauth-identifier-456')).toBeUndefined();
});
test('should not delete tokens when undefined fields are passed', async () => {
// This is the critical test case for the bug fix
const result = await methods.deleteTokens({
token: 'verify-token-1',
identifier: undefined,
userId: undefined,
email: undefined,
});
expect(result.deletedCount).toBe(1); // Only the token with 'verify-token-1'
const remainingTokens = await Token.find({});
expect(remainingTokens).toHaveLength(3);
});
test('should delete multiple tokens when they match OR conditions', async () => {
// Create tokens that will match multiple conditions
await Token.create({
token: 'multi-match',
userId: user2Id, // Will match userId condition
email: 'different@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
});
const result = await methods.deleteTokens({
token: 'verify-token-1',
userId: user2Id.toString(),
});
// Should delete: verify-token-1 (by token) + verify-token-2 (by userId) + multi-match (by userId)
expect(result.deletedCount).toBe(3);
const remainingTokens = await Token.find({});
expect(remainingTokens).toHaveLength(2);
});
test('should throw error when no query parameters provided', async () => {
await expect(methods.deleteTokens({})).rejects.toThrow(
'At least one query parameter must be provided',
);
// Verify no tokens were deleted
const tokens = await Token.find({});
expect(tokens).toHaveLength(4);
});
test('should handle deletion when no tokens match', async () => {
const result = await methods.deleteTokens({ token: 'non-existent-token' });
expect(result.deletedCount).toBe(0);
// Verify all tokens still exist
const tokens = await Token.find({});
expect(tokens).toHaveLength(4);
});
test('should handle email verification scenario correctly', async () => {
// This simulates the exact scenario from the bug report
// Multiple users register and get verification tokens
const newUser1Id = new mongoose.Types.ObjectId();
const newUser2Id = new mongoose.Types.ObjectId();
const newUser3Id = new mongoose.Types.ObjectId();
await Token.create([
{
token: 'email-verify-token-1',
userId: newUser1Id,
email: 'newuser1@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 86400000), // 24 hours
},
{
token: 'email-verify-token-2',
userId: newUser2Id,
email: 'newuser2@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 86400000),
},
{
token: 'email-verify-token-3',
userId: newUser3Id,
email: 'newuser3@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 86400000),
},
]);
// User 2 verifies their email - only their token should be deleted
const result = await methods.deleteTokens({ token: 'email-verify-token-2' });
expect(result.deletedCount).toBe(1);
// Verify other users' tokens still exist
const remainingTokens = await Token.find({ token: { $regex: /^email-verify-token-/ } });
expect(remainingTokens).toHaveLength(2);
expect(remainingTokens.find((t) => t.token === 'email-verify-token-1')).toBeDefined();
expect(remainingTokens.find((t) => t.token === 'email-verify-token-3')).toBeDefined();
expect(remainingTokens.find((t) => t.token === 'email-verify-token-2')).toBeUndefined();
});
});
describe('Email Normalization', () => {
let normUserId: mongoose.Types.ObjectId;
beforeEach(async () => {
normUserId = new mongoose.Types.ObjectId();
// Create token with lowercase email (as stored in DB)
await Token.create({
token: 'norm-token-1',
userId: normUserId,
email: 'john.doe@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
});
});
describe('findToken email normalization', () => {
test('should find token by email with different case (case-insensitive)', async () => {
const foundUpper = await methods.findToken({ email: 'JOHN.DOE@EXAMPLE.COM' });
const foundMixed = await methods.findToken({ email: 'John.Doe@Example.COM' });
const foundLower = await methods.findToken({ email: 'john.doe@example.com' });
expect(foundUpper).toBeDefined();
expect(foundUpper?.token).toBe('norm-token-1');
expect(foundMixed).toBeDefined();
expect(foundMixed?.token).toBe('norm-token-1');
expect(foundLower).toBeDefined();
expect(foundLower?.token).toBe('norm-token-1');
});
test('should find token by email with leading/trailing whitespace', async () => {
const foundWithSpaces = await methods.findToken({ email: ' john.doe@example.com ' });
const foundWithTabs = await methods.findToken({ email: '\tjohn.doe@example.com\t' });
expect(foundWithSpaces).toBeDefined();
expect(foundWithSpaces?.token).toBe('norm-token-1');
expect(foundWithTabs).toBeDefined();
expect(foundWithTabs?.token).toBe('norm-token-1');
});
test('should find token by email with both case difference and whitespace', async () => {
const found = await methods.findToken({ email: ' JOHN.DOE@EXAMPLE.COM ' });
expect(found).toBeDefined();
expect(found?.token).toBe('norm-token-1');
});
test('should find token with combined email and other criteria', async () => {
const found = await methods.findToken({
userId: normUserId.toString(),
email: 'John.Doe@Example.COM',
});
expect(found).toBeDefined();
expect(found?.token).toBe('norm-token-1');
});
});
describe('deleteTokens email normalization', () => {
test('should delete token by email with different case', async () => {
const result = await methods.deleteTokens({ email: 'JOHN.DOE@EXAMPLE.COM' });
expect(result.deletedCount).toBe(1);
const remaining = await Token.find({});
expect(remaining).toHaveLength(0);
});
test('should delete token by email with whitespace', async () => {
const result = await methods.deleteTokens({ email: ' john.doe@example.com ' });
expect(result.deletedCount).toBe(1);
const remaining = await Token.find({});
expect(remaining).toHaveLength(0);
});
test('should delete token by email with case and whitespace combined', async () => {
const result = await methods.deleteTokens({ email: ' John.Doe@EXAMPLE.COM ' });
expect(result.deletedCount).toBe(1);
const remaining = await Token.find({});
expect(remaining).toHaveLength(0);
});
test('should only delete matching token when using normalized email', async () => {
// Create additional token with different email
await Token.create({
token: 'norm-token-2',
userId: new mongoose.Types.ObjectId(),
email: 'jane.doe@example.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 3600000),
});
const result = await methods.deleteTokens({ email: 'JOHN.DOE@EXAMPLE.COM' });
expect(result.deletedCount).toBe(1);
const remaining = await Token.find({});
expect(remaining).toHaveLength(1);
expect(remaining[0].email).toBe('jane.doe@example.com');
});
});
describe('Email verification flow with normalization', () => {
test('should handle OpenID provider email case mismatch scenario', async () => {
/**
* Simulate the exact bug scenario:
* 1. User registers with email stored as lowercase
* 2. OpenID provider returns email with different casing
* 3. System should still find and delete the correct token
*/
const userId = new mongoose.Types.ObjectId();
// Token created during registration (email stored lowercase)
await Token.create({
token: 'verification-token',
userId: userId,
email: 'user@company.com',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 86400000),
});
// OpenID provider returns email with different case
const emailFromProvider = 'User@Company.COM';
// Should find the token despite case mismatch
const found = await methods.findToken({ email: emailFromProvider });
expect(found).toBeDefined();
expect(found?.token).toBe('verification-token');
// Should delete the token despite case mismatch
const deleted = await methods.deleteTokens({ email: emailFromProvider });
expect(deleted.deletedCount).toBe(1);
});
test('should handle resend verification email with case mismatch', async () => {
const userId = new mongoose.Types.ObjectId();
// Old verification token
await Token.create({
token: 'old-verification',
userId: userId,
email: 'john.smith@enterprise.com',
createdAt: new Date(Date.now() - 3600000),
expiresAt: new Date(Date.now() + 82800000),
});
// User requests resend with different email casing
const userInputEmail = ' John.Smith@ENTERPRISE.COM ';
// Delete old tokens for this email
const deleted = await methods.deleteTokens({ email: userInputEmail });
expect(deleted.deletedCount).toBe(1);
// Verify token was actually deleted
const remaining = await Token.find({ userId });
expect(remaining).toHaveLength(0);
});
});
});
});
|