Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use code for email verification #25

Merged
merged 16 commits into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions migration/1723936796571-RenameUserEmailVerificationFields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
ae2079 marked this conversation as resolved.
Show resolved Hide resolved

export class RenameUserEmailVerificationFields1723936796571
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
// Rename emailConfirmationToken to emailVerificationCode
await queryRunner.renameColumn(
'user',
'emailConfirmationToken',
'emailVerificationCode',
);

// Rename emailConfirmationTokenExpiredAt to emailVerificationCodeExpiredAt
await queryRunner.renameColumn(
'user',
'emailConfirmationTokenExpiredAt',
'emailVerificationCodeExpiredAt',
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
// Revert emailVerificationCode back to emailConfirmationToken
await queryRunner.renameColumn(
'user',
'emailVerificationCode',
'emailConfirmationToken',
);

// Revert emailVerificationCodeExpiredAt back to emailConfirmationTokenExpiredAt
await queryRunner.renameColumn(
'user',
'emailVerificationCodeExpiredAt',
'emailConfirmationTokenExpiredAt',
);
}
}
2 changes: 1 addition & 1 deletion src/adapters/notifications/MockNotificationAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class MockNotificationAdapter implements NotificationAdapterInterface {
async sendUserEmailConfirmation(params: {
email: string;
user: User;
token: string;
code: string;
}) {
logger.debug('MockNotificationAdapter sendUserEmailConfirmation', params);
return Promise.resolve(undefined);
Expand Down
2 changes: 1 addition & 1 deletion src/adapters/notifications/NotificationAdapterInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export interface NotificationAdapterInterface {
sendUserEmailConfirmation(params: {
email: string;
user: User;
token: string;
code: string;
}): Promise<void>;

userSuperTokensCritical(params: {
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/notifications/NotificationCenterAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,16 @@ export class NotificationCenterAdapter implements NotificationAdapterInterface {
async sendUserEmailConfirmation(params: {
email: string;
user: User;
token: string;
code: string;
}): Promise<void> {
const { email, user, token } = params;
const { email, code } = params;
try {
await callSendNotification({
eventName: NOTIFICATIONS_EVENT_NAMES.SEND_EMAIL_CONFIRMATION,
segment: {
payload: {
email,
verificationLink: `${dappUrl}/verification/user/${user.walletAddress}/${token}`,
verificationLink: code, // todo: we just set this for test and we should change the schema
},
},
});
Expand Down
4 changes: 2 additions & 2 deletions src/entities/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,11 @@ export class User extends BaseEntity {

@Field(_type => String, { nullable: true })
@Column('text', { nullable: true })
emailConfirmationToken: string | null;
emailConfirmationCode: string | null;

@Field(_type => Date, { nullable: true })
@Column('timestamptz', { nullable: true })
emailConfirmationTokenExpiredAt: Date | null;
emailConfirmationCodeExpiredAt: Date | null;

@Field(_type => Boolean, { nullable: true })
@Column({ default: false })
Expand Down
65 changes: 20 additions & 45 deletions src/repositories/userRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ import { User, UserRole } from '../entities/user';
import {
findAdminUserByEmail,
findAllUsers,
findUserByEmailConfirmationToken,
findUserById,
findUserByWalletAddress,
findUsersWhoDonatedToProjectExcludeWhoLiked,
findUsersWhoLikedProjectExcludeProjectOwner,
findUsersWhoSupportProject,
updateUserEmailConfirmationStatus,
updateUserEmailConfirmationToken,
updateUserEmailConfirmationCode,
} from './userRepository';
import { Reaction } from '../entities/reaction';

Expand Down Expand Up @@ -47,17 +46,13 @@ describe(
findUsersWhoDonatedToProjectTestCases,
);

describe(
'userRepository.findUserByEmailConfirmationToken',
findUserByEmailConfirmationTokenTestCases,
);
describe(
'userRepository.updateUserEmailConfirmationStatus',
updateUserEmailConfirmationStatusTestCases,
);
describe(
'userRepository.updateUserEmailConfirmationToken',
updateUserEmailConfirmationTokenTestCases,
'userRepository.updateUserEmailConfirmationCode',
updateUserEmailConfirmationCodeTestCases,
);

function findUsersWhoDonatedToProjectTestCases() {
Expand Down Expand Up @@ -506,87 +501,67 @@ function findUsersWhoSupportProjectTestCases() {
});
}

function findUserByEmailConfirmationTokenTestCases() {
it('should return a user if a valid email confirmation token is provided', async () => {
await User.create({
email: '[email protected]',
emailConfirmationToken: 'validToken123',
loginType: 'wallet',
}).save();

const foundUser = await findUserByEmailConfirmationToken('validToken123');
assert.isNotNull(foundUser);
assert.equal(foundUser!.email, '[email protected]');
assert.equal(foundUser!.emailConfirmationToken, 'validToken123');
});

it('should return null if no user is found with the provided email confirmation token', async () => {
const foundUser = await findUserByEmailConfirmationToken('invalidToken123');
assert.isNull(foundUser);
});
}

function updateUserEmailConfirmationStatusTestCases() {
it('should update the email confirmation status of a user', async () => {
const user = await User.create({
email: '[email protected]',
emailConfirmed: false,
emailConfirmationToken: 'validToken123',
emailConfirmationCode: '234567',
loginType: 'wallet',
}).save();

await updateUserEmailConfirmationStatus({
userId: user.id,
emailConfirmed: true,
emailConfirmationTokenExpiredAt: null,
emailConfirmationToken: null,
emailConfirmationCodeExpiredAt: null,
emailConfirmationCode: null,
emailConfirmationSentAt: null,
});

// Using findOne with options object
const updatedUser = await User.findOne({ where: { id: user.id } });
assert.isNotNull(updatedUser);
assert.isTrue(updatedUser!.emailConfirmed);
assert.isNull(updatedUser!.emailConfirmationToken);
assert.isNull(updatedUser!.emailConfirmationCode);
});

it('should not update any user if the userId does not exist', async () => {
const result = await updateUserEmailConfirmationStatus({
userId: 999, // non-existent userId
emailConfirmed: true,
emailConfirmationTokenExpiredAt: null,
emailConfirmationToken: null,
emailConfirmationCodeExpiredAt: null,
emailConfirmationCode: null,
emailConfirmationSentAt: null,
});

assert.equal(result.affected, 0); // No rows should be affected
});
}

function updateUserEmailConfirmationTokenTestCases() {
it('should update the email confirmation token and expiry date for a user', async () => {
function updateUserEmailConfirmationCodeTestCases() {
it('should update the email confirmation code and expiry date for a user', async () => {
const user = await User.create({
email: '[email protected]',
loginType: 'wallet',
}).save();

const newToken = 'newToken123';
const newCode = '654321';
const newExpiryDate = new Date(Date.now() + 3600 * 1000); // 1 hour from now
const sentAtDate = new Date();

await updateUserEmailConfirmationToken({
await updateUserEmailConfirmationCode({
userId: user.id,
emailConfirmationToken: newToken,
emailConfirmationTokenExpiredAt: newExpiryDate,
emailConfirmationCode: newCode,
emailConfirmationCodeExpiredAt: newExpiryDate,
emailConfirmationSentAt: sentAtDate,
});

// Using findOne with options object
const updatedUser = await User.findOne({ where: { id: user.id } });
assert.isNotNull(updatedUser);
assert.equal(updatedUser!.emailConfirmationToken, newToken);
assert.equal(updatedUser!.emailConfirmationCode, newCode);
assert.equal(
updatedUser!.emailConfirmationTokenExpiredAt!.getTime(),
updatedUser!.emailConfirmationCodeExpiredAt!.getTime(),
newExpiryDate.getTime(),
);
assert.equal(
Expand All @@ -597,10 +572,10 @@ function updateUserEmailConfirmationTokenTestCases() {

it('should throw an error if the userId does not exist', async () => {
try {
await updateUserEmailConfirmationToken({
await updateUserEmailConfirmationCode({
userId: 999, // non-existent userId
emailConfirmationToken: 'newToken123',
emailConfirmationTokenExpiredAt: new Date(),
emailConfirmationCode: '765432',
emailConfirmationCodeExpiredAt: new Date(),
emailConfirmationSentAt: new Date(),
});
assert.fail('Expected an error to be thrown');
Expand Down
36 changes: 13 additions & 23 deletions src/repositories/userRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,53 +179,43 @@ export const findUsersWhoSupportProject = async (
return users;
};

export const findUserByEmailConfirmationToken = async (
emailConfirmationToken: string,
): Promise<User | null> => {
return User.createQueryBuilder('user')
.where({
emailConfirmationToken,
})
.getOne();
};

export const updateUserEmailConfirmationStatus = async (params: {
userId: number;
emailConfirmed: boolean;
emailConfirmationTokenExpiredAt: Date | null;
emailConfirmationToken: string | null;
emailConfirmationCodeExpiredAt: Date | null;
emailConfirmationCode: string | null;
emailConfirmationSentAt: Date | null;
}): Promise<UpdateResult> => {
const {
userId,
emailConfirmed,
emailConfirmationTokenExpiredAt,
emailConfirmationToken,
emailConfirmationCodeExpiredAt,
emailConfirmationCode,
emailConfirmationSentAt,
} = params;

return User.createQueryBuilder()
.update(User)
.set({
emailConfirmed,
emailConfirmationTokenExpiredAt,
emailConfirmationToken,
emailConfirmationCodeExpiredAt,
emailConfirmationCode,
emailConfirmationSentAt,
})
.where('id = :userId', { userId })
.execute();
};

export const updateUserEmailConfirmationToken = async (params: {
export const updateUserEmailConfirmationCode = async (params: {
userId: number;
emailConfirmationToken: string;
emailConfirmationTokenExpiredAt: Date;
emailConfirmationCode: string;
emailConfirmationCodeExpiredAt: Date;
emailConfirmationSentAt: Date;
}): Promise<User> => {
const {
userId,
emailConfirmationToken,
emailConfirmationTokenExpiredAt,
emailConfirmationCode,
emailConfirmationCodeExpiredAt,
emailConfirmationSentAt,
} = params;

Expand All @@ -234,8 +224,8 @@ export const updateUserEmailConfirmationToken = async (params: {
throw new Error('User not found');
}

user.emailConfirmationToken = emailConfirmationToken;
user.emailConfirmationTokenExpiredAt = emailConfirmationTokenExpiredAt;
user.emailConfirmationCode = emailConfirmationCode;
user.emailConfirmationCodeExpiredAt = emailConfirmationCodeExpiredAt;
user.emailConfirmationSentAt = emailConfirmationSentAt;
user.emailConfirmed = false;

Expand Down
Loading
Loading