From 2faad50919eedf01ae3a42360ace60e80d1608c1 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Wed, 23 Mar 2022 13:33:07 +0100 Subject: [PATCH 01/19] set email code valid time to 24h --- backend/.env.dist | 2 +- backend/src/config/index.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/.env.dist b/backend/.env.dist index 3c93f1576..bbea28989 100644 --- a/backend/.env.dist +++ b/backend/.env.dist @@ -40,7 +40,7 @@ EMAIL_SMTP_URL=gmail.com EMAIL_SMTP_PORT=587 EMAIL_LINK_VERIFICATION=http://localhost/checkEmail/{code} EMAIL_LINK_SETPASSWORD=http://localhost/reset/{code} -EMAIL_CODE_VALID_TIME=10 +EMAIL_CODE_VALID_TIME=1440 # Webhook WEBHOOK_ELOPAGE_SECRET=secret \ No newline at end of file diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index 754bfbf08..81d72478a 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -66,8 +66,8 @@ const email = { EMAIL_LINK_SETPASSWORD: process.env.EMAIL_LINK_SETPASSWORD || 'http://localhost/reset-password/{code}', EMAIL_CODE_VALID_TIME: process.env.EMAIL_CODE_VALID_TIME - ? parseInt(process.env.EMAIL_CODE_VALID_TIME) || 10 - : 10, + ? parseInt(process.env.EMAIL_CODE_VALID_TIME) || 1440 + : 1440, } const webhook = { From 662285161cb80f33dea50765892b4d63db62486b Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Wed, 23 Mar 2022 14:28:24 +0100 Subject: [PATCH 02/19] time span for email code valid time --- backend/src/graphql/resolver/UserResolver.ts | 26 +++++++++++++++++--- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index a56b67945..9b4fa6fa1 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -157,7 +157,7 @@ const createEmailOptIn = async ( }) if (emailOptIn) { if (isOptInCodeValid(emailOptIn)) { - throw new Error(`email already sent less than $(CONFIG.EMAIL_CODE_VALID_TIME} minutes ago`) + throw new Error(`email already sent less than ${printEmailCodeValidTime()} ago`) } emailOptIn.updatedAt = new Date() emailOptIn.resendCount++ @@ -184,7 +184,7 @@ const getOptInCode = async (loginUserId: number): Promise => { // Check for `CONFIG.EMAIL_CODE_VALID_TIME` minute delay if (optInCode) { if (isOptInCodeValid(optInCode)) { - throw new Error(`email already sent less than $(CONFIG.EMAIL_CODE_VALID_TIME} minutes ago`) + throw new Error(`email already sent less than $(printEmailCodeValidTime()} minutes ago`) } optInCode.updatedAt = new Date() optInCode.resendCount++ @@ -486,7 +486,7 @@ export class UserResolver { // Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes if (!isOptInCodeValid(optInCode)) { - throw new Error(`email already more than $(CONFIG.EMAIL_CODE_VALID_TIME} minutes ago`) + throw new Error(`email was sent more than ${printEmailCodeValidTime()} ago`) } // load user @@ -565,7 +565,7 @@ export class UserResolver { const optInCode = await LoginEmailOptIn.findOneOrFail({ verificationCode: optIn }) // Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes if (!isOptInCodeValid(optInCode)) { - throw new Error(`email was sent more than $(CONFIG.EMAIL_CODE_VALID_TIME} minutes ago`) + throw new Error(`email was sent more than $(printEmailCodeValidTime()} ago`) } return true } @@ -671,7 +671,25 @@ export class UserResolver { return hasElopageBuys(userEntity.email) } } + function isOptInCodeValid(optInCode: LoginEmailOptIn) { const timeElapsed = Date.now() - new Date(optInCode.updatedAt).getTime() return timeElapsed <= CONFIG.EMAIL_CODE_VALID_TIME * 60 * 1000 } + +const emailCodeValidTime = (): { hours?: number; minutes: number } => { + if (CONFIG.EMAIL_CODE_VALID_TIME > 60) { + return { + hours: Math.floor(CONFIG.EMAIL_CODE_VALID_TIME / 60), + minutes: CONFIG.EMAIL_CODE_VALID_TIME % 60, + } + } + return { minutes: CONFIG.EMAIL_CODE_VALID_TIME } +} + +const printEmailCodeValidTime = (): string => { + const time = emailCodeValidTime() + const result = time.minutes > 0 ? `${time.minutes} minutes` : '' + if (time.hours) return `${time.hours} hours` + result !== '' ? ` and ${result}` : '' + return result +} From ca0d97c47cde3152aa5929658242f87619c9a686 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Wed, 23 Mar 2022 16:03:52 +0100 Subject: [PATCH 03/19] test printEmailCodeValidTime --- .../src/graphql/resolver/UserResolver.test.ts | 18 ++++++++++++++++++ backend/src/graphql/resolver/UserResolver.ts | 4 ++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/backend/src/graphql/resolver/UserResolver.test.ts b/backend/src/graphql/resolver/UserResolver.test.ts index f873fd694..9d78ecb6e 100644 --- a/backend/src/graphql/resolver/UserResolver.test.ts +++ b/backend/src/graphql/resolver/UserResolver.test.ts @@ -11,6 +11,7 @@ import { LoginEmailOptIn } from '@entity/LoginEmailOptIn' import { User } from '@entity/User' import CONFIG from '@/config' import { sendAccountActivationEmail } from '@/mailer/sendAccountActivationEmail' +import { printEmailCodeValidTime } from './UserResolver' // import { klicktippSignIn } from '@/apis/KlicktippController' @@ -412,3 +413,20 @@ describe('UserResolver', () => { }) }) }) + +describe('printEmailCodeValidTime', () => { + it('works with 10 minutes', () => { + CONFIG.EMAIL_CODE_VALID_TIME = 10 + expect(printEmailCodeValidTime()).toBe('10 minutes') + }) + + it('works with 1440 minutes', () => { + CONFIG.EMAIL_CODE_VALID_TIME = 1440 + expect(printEmailCodeValidTime()).toBe('24 hours') + }) + + it('works with 1410 minutes', () => { + CONFIG.EMAIL_CODE_VALID_TIME = 1410 + expect(printEmailCodeValidTime()).toBe('23 hours and 30 minutes') + }) +}) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index 9b4fa6fa1..e0aa06a7c 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -687,9 +687,9 @@ const emailCodeValidTime = (): { hours?: number; minutes: number } => { return { minutes: CONFIG.EMAIL_CODE_VALID_TIME } } -const printEmailCodeValidTime = (): string => { +export const printEmailCodeValidTime = (): string => { const time = emailCodeValidTime() const result = time.minutes > 0 ? `${time.minutes} minutes` : '' - if (time.hours) return `${time.hours} hours` + result !== '' ? ` and ${result}` : '' + if (time.hours) return `${time.hours} hours` + (result !== '' ? ` and ${result}` : '') return result } From 40520c6718cbc41ac10b9aa6510f007e67c0cad1 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Wed, 23 Mar 2022 16:11:19 +0100 Subject: [PATCH 04/19] regexp to check for error message --- frontend/src/pages/ResetPassword.vue | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/frontend/src/pages/ResetPassword.vue b/frontend/src/pages/ResetPassword.vue index 7532953ed..bf8664cef 100644 --- a/frontend/src/pages/ResetPassword.vue +++ b/frontend/src/pages/ResetPassword.vue @@ -104,7 +104,11 @@ export default { }) .catch((error) => { this.toastError(error.message) - if (error.message.includes('Code is older than 10 minutes')) + if ( + error.message.match( + /email was sent more than ([0-9]+ hours)?( and)?([0-9]+ minutes)? ago/, + ) + ) this.$router.push('/forgot-password/resetPassword') }) }, From b0300e5a084d004e64e72901b8e947245c24b5ba Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Wed, 23 Mar 2022 16:16:04 +0100 Subject: [PATCH 05/19] test regexp to catch error message --- frontend/src/pages/ResetPassword.spec.js | 8 ++++++-- frontend/src/pages/ResetPassword.vue | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/frontend/src/pages/ResetPassword.spec.js b/frontend/src/pages/ResetPassword.spec.js index f5d672c99..8f2d63791 100644 --- a/frontend/src/pages/ResetPassword.spec.js +++ b/frontend/src/pages/ResetPassword.spec.js @@ -149,13 +149,17 @@ describe('ResetPassword', () => { describe('server response with error code > 10min', () => { beforeEach(async () => { jest.clearAllMocks() - apolloMutationMock.mockRejectedValue({ message: '...Code is older than 10 minutes' }) + apolloMutationMock.mockRejectedValue({ + message: '...email was sent more than 23 hours and 10 minutes ago', + }) await wrapper.find('form').trigger('submit') await flushPromises() }) it('toasts an error message', () => { - expect(toastErrorSpy).toHaveBeenCalledWith('...Code is older than 10 minutes') + expect(toastErrorSpy).toHaveBeenCalledWith( + '...email was sent more than 23 hours and 10 minutes ago', + ) }) it('router pushes to /forgot-password/resetPassword', () => { diff --git a/frontend/src/pages/ResetPassword.vue b/frontend/src/pages/ResetPassword.vue index bf8664cef..02773e5e4 100644 --- a/frontend/src/pages/ResetPassword.vue +++ b/frontend/src/pages/ResetPassword.vue @@ -106,7 +106,7 @@ export default { this.toastError(error.message) if ( error.message.match( - /email was sent more than ([0-9]+ hours)?( and)?([0-9]+ minutes)? ago/, + /email was sent more than ([0-9]+ hours)?( and )?([0-9]+ minutes)? ago/, ) ) this.$router.push('/forgot-password/resetPassword') From 0c0ce1b579dc68a35bb1a927dc9df05844820a0e Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 14:05:23 +0100 Subject: [PATCH 06/19] add new env variable to define email optin request time delay --- backend/.env.dist | 3 ++- backend/src/config/index.ts | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/backend/.env.dist b/backend/.env.dist index 0555bf9f5..5e3a89f82 100644 --- a/backend/.env.dist +++ b/backend/.env.dist @@ -1,4 +1,4 @@ -CONFIG_VERSION=v1.2022-03-18 +CONFIG_VERSION=v2.2022-03-24 # Server PORT=4000 @@ -43,6 +43,7 @@ EMAIL_SMTP_PORT=587 EMAIL_LINK_VERIFICATION=http://localhost/checkEmail/{optin}{code} EMAIL_LINK_SETPASSWORD=http://localhost/reset/{code} EMAIL_CODE_VALID_TIME=1440 +EMAIL_CODE_REQUEST_TIME=10 # Webhook WEBHOOK_ELOPAGE_SECRET=secret \ No newline at end of file diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index 4e36a6910..158983d5c 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -14,7 +14,7 @@ const constants = { DECAY_START_TIME: new Date('2021-05-13 17:46:31'), // GMT+0 CONFIG_VERSION: { DEFAULT: 'DEFAULT', - EXPECTED: 'v1.2022-03-18', + EXPECTED: 'v2.2022-03-24', CURRENT: '', }, } @@ -73,6 +73,9 @@ const email = { EMAIL_CODE_VALID_TIME: process.env.EMAIL_CODE_VALID_TIME ? parseInt(process.env.EMAIL_CODE_VALID_TIME) || 1440 : 1440, + EMAIL_CODE_REQUEST_TIME: process.env.EMAIL_CODE_REQUEST_TIME + ? parseInt(process.env.EMAIL_CODE_REQUEST_TIME) || 10 + : 10, } const webhook = { From ac000296da69d3e348766cca8e9f0ed8b38bdb66 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 17:37:07 +0100 Subject: [PATCH 07/19] enums for optin types --- backend/src/graphql/enum/OptinType.ts | 11 +++++++++++ backend/src/graphql/resolver/UserResolver.ts | 18 +++++++++--------- 2 files changed, 20 insertions(+), 9 deletions(-) create mode 100644 backend/src/graphql/enum/OptinType.ts diff --git a/backend/src/graphql/enum/OptinType.ts b/backend/src/graphql/enum/OptinType.ts new file mode 100644 index 000000000..7e7edde93 --- /dev/null +++ b/backend/src/graphql/enum/OptinType.ts @@ -0,0 +1,11 @@ +import { registerEnumType } from 'type-graphql' + +export enum OptinType { + EMAIL_OPT_IN_REGISTER = 1, + EMAIL_OPT_IN_RESET_PASSWORD = 2, +} + +registerEnumType(OptinType, { + name: 'OptinType', // this one is mandatory + description: 'Type of the email optin', // this one is optional +}) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index c9060384a..a1d6d6e1d 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -15,6 +15,7 @@ import UpdateUserInfosArgs from '@arg/UpdateUserInfosArgs' import { klicktippNewsletterStateMiddleware } from '@/middleware/klicktippMiddleware' import { UserSettingRepository } from '@repository/UserSettingRepository' import { Setting } from '@enum/Setting' +import { OptinType } from '@enum/OptinType' import { LoginEmailOptIn } from '@entity/LoginEmailOptIn' import { sendResetPasswordEmail } from '@/mailer/sendResetPasswordEmail' import { sendAccountActivationEmail } from '@/mailer/sendAccountActivationEmail' @@ -24,9 +25,6 @@ import { ROLE_ADMIN } from '@/auth/ROLES' import { hasElopageBuys } from '@/util/hasElopageBuys' import { ServerUser } from '@entity/ServerUser' -const EMAIL_OPT_IN_RESET_PASSWORD = 2 -const EMAIL_OPT_IN_REGISTER = 1 - // eslint-disable-next-line @typescript-eslint/no-var-requires const sodium = require('sodium-native') // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -148,14 +146,16 @@ const SecretKeyCryptographyDecrypt = (encryptedMessage: Buffer, encryptionKey: B return message } + const createEmailOptIn = async ( loginUserId: number, queryRunner: QueryRunner, ): Promise => { let emailOptIn = await LoginEmailOptIn.findOne({ userId: loginUserId, - emailOptInTypeId: EMAIL_OPT_IN_REGISTER, + emailOptInTypeId: OptinType.EMAIL_OPT_IN_REGISTER, }) + if (emailOptIn) { if (isOptInCodeValid(emailOptIn)) { throw new Error(`email already sent less than ${printEmailCodeValidTime()} ago`) @@ -166,7 +166,7 @@ const createEmailOptIn = async ( emailOptIn = new LoginEmailOptIn() emailOptIn.verificationCode = random(64) emailOptIn.userId = loginUserId - emailOptIn.emailOptInTypeId = EMAIL_OPT_IN_REGISTER + emailOptIn.emailOptInTypeId = OptinType.EMAIL_OPT_IN_REGISTER } await queryRunner.manager.save(emailOptIn).catch((error) => { // eslint-disable-next-line no-console @@ -179,7 +179,7 @@ const createEmailOptIn = async ( const getOptInCode = async (loginUserId: number): Promise => { let optInCode = await LoginEmailOptIn.findOne({ userId: loginUserId, - emailOptInTypeId: EMAIL_OPT_IN_RESET_PASSWORD, + emailOptInTypeId: OptinType.EMAIL_OPT_IN_RESET_PASSWORD, }) // Check for `CONFIG.EMAIL_CODE_VALID_TIME` minute delay @@ -193,7 +193,7 @@ const getOptInCode = async (loginUserId: number): Promise => { optInCode = new LoginEmailOptIn() optInCode.verificationCode = random(64) optInCode.userId = loginUserId - optInCode.emailOptInTypeId = EMAIL_OPT_IN_RESET_PASSWORD + optInCode.emailOptInTypeId = OptinType.EMAIL_OPT_IN_RESET_PASSWORD } await LoginEmailOptIn.save(optInCode) return optInCode @@ -398,7 +398,7 @@ export class UserResolver { return new User(dbUser) } - // THis is used by the admin only - should we move it to the admin resolver? + // This is used by the admin only - should we move it to the admin resolver? @Authorized([RIGHTS.SEND_ACTIVATION_EMAIL]) @Mutation(() => Boolean) async sendActivationEmail(@Arg('email') email: string): Promise { @@ -553,7 +553,7 @@ export class UserResolver { // Sign into Klicktipp // TODO do we always signUp the user? How to handle things with old users? - if (optInCode.emailOptInTypeId === EMAIL_OPT_IN_REGISTER) { + if (optInCode.emailOptInTypeId === OptinType.EMAIL_OPT_IN_REGISTER) { try { await klicktippSignIn(user.email, user.language, user.firstName, user.lastName) } catch { From 8718fdee7b0d3c97d0510cea613c05684dba4a2b Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 17:38:03 +0100 Subject: [PATCH 08/19] add comentary to explain the meaning of the constants --- backend/src/config/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index 158983d5c..caedac08e 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -70,9 +70,11 @@ const email = { process.env.EMAIL_LINK_VERIFICATION || 'http://localhost/checkEmail/{optin}{code}', EMAIL_LINK_SETPASSWORD: process.env.EMAIL_LINK_SETPASSWORD || 'http://localhost/reset-password/{optin}', + // time in minutes a optin code is valid EMAIL_CODE_VALID_TIME: process.env.EMAIL_CODE_VALID_TIME ? parseInt(process.env.EMAIL_CODE_VALID_TIME) || 1440 : 1440, + // time in minutes that must pass to request a new optin code EMAIL_CODE_REQUEST_TIME: process.env.EMAIL_CODE_REQUEST_TIME ? parseInt(process.env.EMAIL_CODE_REQUEST_TIME) || 10 : 10, From 7cd920686db91f4a53ade117b0d23c21cc034a41 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 17:50:34 +0100 Subject: [PATCH 09/19] helper function to create a new email optin object. Use this in create user --- backend/src/graphql/resolver/UserResolver.ts | 23 +++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index a1d6d6e1d..579940c2b 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -147,12 +147,20 @@ const SecretKeyCryptographyDecrypt = (encryptedMessage: Buffer, encryptionKey: B return message } +const newEmailOptin = (userId: number): LoginEmailOptIn => { + const emailOptIn = new LoginEmailOptIn() + emailOptIn.verificationCode = random(64) + emailOptIn.userId = userId + emailOptIn.emailOptInTypeId = OptinType.EMAIL_OPT_IN_REGISTER + return emailOptIn +} + const createEmailOptIn = async ( - loginUserId: number, + userId: number, queryRunner: QueryRunner, ): Promise => { let emailOptIn = await LoginEmailOptIn.findOne({ - userId: loginUserId, + userId, emailOptInTypeId: OptinType.EMAIL_OPT_IN_REGISTER, }) @@ -165,7 +173,7 @@ const createEmailOptIn = async ( } else { emailOptIn = new LoginEmailOptIn() emailOptIn.verificationCode = random(64) - emailOptIn.userId = loginUserId + emailOptIn.userId = userId emailOptIn.emailOptInTypeId = OptinType.EMAIL_OPT_IN_REGISTER } await queryRunner.manager.save(emailOptIn).catch((error) => { @@ -363,9 +371,12 @@ export class UserResolver { throw new Error('error saving user') }) - // Store EmailOptIn in DB - // TODO: this has duplicate code with sendResetPasswordEmail - const emailOptIn = await createEmailOptIn(dbUser.id, queryRunner) + const emailOptIn = newEmailOptin(dbUser.id) + await queryRunner.manager.save(emailOptIn).catch((error) => { + // eslint-disable-next-line no-console + console.log('Error while saving emailOptIn', error) + throw new Error('error saving email opt in') + }) const activationLink = CONFIG.EMAIL_LINK_VERIFICATION.replace( /{optin}/g, From 965ab22bab4ded3acd1a3aa055af8df3389b4f4d Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 18:17:46 +0100 Subject: [PATCH 10/19] create helper functions for time management, rename some functions --- .../src/graphql/resolver/UserResolver.test.ts | 13 ++--- backend/src/graphql/resolver/UserResolver.ts | 53 ++++++++++++------- 2 files changed, 40 insertions(+), 26 deletions(-) diff --git a/backend/src/graphql/resolver/UserResolver.test.ts b/backend/src/graphql/resolver/UserResolver.test.ts index d98621246..726ecfb09 100644 --- a/backend/src/graphql/resolver/UserResolver.test.ts +++ b/backend/src/graphql/resolver/UserResolver.test.ts @@ -11,7 +11,7 @@ import { LoginEmailOptIn } from '@entity/LoginEmailOptIn' import { User } from '@entity/User' import CONFIG from '@/config' import { sendAccountActivationEmail } from '@/mailer/sendAccountActivationEmail' -import { printEmailCodeValidTime } from './UserResolver' +import { printTimeDuration } from './UserResolver' // import { klicktippSignIn } from '@/apis/KlicktippController' @@ -417,19 +417,16 @@ describe('UserResolver', () => { }) }) -describe('printEmailCodeValidTime', () => { +describe('printTimeDuration', () => { it('works with 10 minutes', () => { - CONFIG.EMAIL_CODE_VALID_TIME = 10 - expect(printEmailCodeValidTime()).toBe('10 minutes') + expect(printTimeDuration(10)).toBe('10 minutes') }) it('works with 1440 minutes', () => { - CONFIG.EMAIL_CODE_VALID_TIME = 1440 - expect(printEmailCodeValidTime()).toBe('24 hours') + expect(printTimeDuration(1440)).toBe('24 hours') }) it('works with 1410 minutes', () => { - CONFIG.EMAIL_CODE_VALID_TIME = 1410 - expect(printEmailCodeValidTime()).toBe('23 hours and 30 minutes') + expect(printTimeDuration(1410)).toBe('23 hours and 30 minutes') }) }) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index 579940c2b..c9f5b6564 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -165,8 +165,10 @@ const createEmailOptIn = async ( }) if (emailOptIn) { - if (isOptInCodeValid(emailOptIn)) { - throw new Error(`email already sent less than ${printEmailCodeValidTime()} ago`) + if (isOptinValid(emailOptIn)) { + throw new Error( + `email already sent less than ${printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} ago`, + ) } emailOptIn.updatedAt = new Date() emailOptIn.resendCount++ @@ -192,8 +194,10 @@ const getOptInCode = async (loginUserId: number): Promise => { // Check for `CONFIG.EMAIL_CODE_VALID_TIME` minute delay if (optInCode) { - if (isOptInCodeValid(optInCode)) { - throw new Error(`email already sent less than $(printEmailCodeValidTime()} minutes ago`) + if (isOptinValid(optInCode)) { + throw new Error( + `email already sent less than $(printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} minutes ago`, + ) } optInCode.updatedAt = new Date() optInCode.resendCount++ @@ -505,8 +509,10 @@ export class UserResolver { }) // Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes - if (!isOptInCodeValid(optInCode)) { - throw new Error(`email was sent more than ${printEmailCodeValidTime()} ago`) + if (!isOptinValid(optInCode)) { + throw new Error( + `email was sent more than ${printTimeDuration(CONFIG.EMAIL_CODE_VALID_TIME)} ago`, + ) } // load user @@ -584,8 +590,10 @@ export class UserResolver { async queryOptIn(@Arg('optIn') optIn: string): Promise { const optInCode = await LoginEmailOptIn.findOneOrFail({ verificationCode: optIn }) // Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes - if (!isOptInCodeValid(optInCode)) { - throw new Error(`email was sent more than $(printEmailCodeValidTime()} ago`) + if (!isOptinValid(optInCode)) { + throw new Error( + `email was sent more than $(printTimeDuration(CONFIG.EMAIL_CODE_VALID_TIME)} ago`, + ) } return true } @@ -692,23 +700,32 @@ export class UserResolver { } } -function isOptInCodeValid(optInCode: LoginEmailOptIn) { - const timeElapsed = Date.now() - new Date(optInCode.updatedAt).getTime() - return timeElapsed <= CONFIG.EMAIL_CODE_VALID_TIME * 60 * 1000 +const isTimeExpired = (optin: LoginEmailOptIn, duration: number): boolean => { + const timeElapsed = Date.now() - new Date(optin.updatedAt).getTime() + // time is given in minutes + return timeElapsed <= duration * 60 * 1000 } -const emailCodeValidTime = (): { hours?: number; minutes: number } => { - if (CONFIG.EMAIL_CODE_VALID_TIME > 60) { +const isOptinValid = (optin: LoginEmailOptIn): boolean => { + return isTimeExpired(optin, CONFIG.EMAIL_CODE_VALID_TIME) +} + +const canResendOptin = (optin: LoginEmailOptIn): boolean => { + return isTimeExpired(optin, CONFIG.EMAIL_CODE_REQUEST_TIME) +} + +const getTimeDurationObject = (time: number): { hours?: number; minutes: number } => { + if (time > 60) { return { - hours: Math.floor(CONFIG.EMAIL_CODE_VALID_TIME / 60), - minutes: CONFIG.EMAIL_CODE_VALID_TIME % 60, + hours: Math.floor(time / 60), + minutes: time % 60, } } - return { minutes: CONFIG.EMAIL_CODE_VALID_TIME } + return { minutes: time } } -export const printEmailCodeValidTime = (): string => { - const time = emailCodeValidTime() +export const printTimeDuration = (duration: number): string => { + const time = getTimeDurationObject(duration) const result = time.minutes > 0 ? `${time.minutes} minutes` : '' if (time.hours) return `${time.hours} hours` + (result !== '' ? ` and ${result}` : '') return result From 607805075c086ba3fe8153e0641337a22083a2af Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 18:33:07 +0100 Subject: [PATCH 11/19] refactor sendActivationEmail, get rid of getOptInCode function --- backend/src/graphql/resolver/UserResolver.ts | 46 ++++++++------------ 1 file changed, 19 insertions(+), 27 deletions(-) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index c9f5b6564..50bba974f 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -186,31 +186,6 @@ const createEmailOptIn = async ( return emailOptIn } -const getOptInCode = async (loginUserId: number): Promise => { - let optInCode = await LoginEmailOptIn.findOne({ - userId: loginUserId, - emailOptInTypeId: OptinType.EMAIL_OPT_IN_RESET_PASSWORD, - }) - - // Check for `CONFIG.EMAIL_CODE_VALID_TIME` minute delay - if (optInCode) { - if (isOptinValid(optInCode)) { - throw new Error( - `email already sent less than $(printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} minutes ago`, - ) - } - optInCode.updatedAt = new Date() - optInCode.resendCount++ - } else { - optInCode = new LoginEmailOptIn() - optInCode.verificationCode = random(64) - optInCode.userId = loginUserId - optInCode.emailOptInTypeId = OptinType.EMAIL_OPT_IN_RESET_PASSWORD - } - await LoginEmailOptIn.save(optInCode) - return optInCode -} - @Resolver() export class UserResolver { @Authorized([RIGHTS.VERIFY_LOGIN]) @@ -460,11 +435,28 @@ export class UserResolver { @Authorized([RIGHTS.SEND_RESET_PASSWORD_EMAIL]) @Query(() => Boolean) async sendResetPasswordEmail(@Arg('email') email: string): Promise { - // TODO: this has duplicate code with createUser email = email.trim().toLowerCase() const user = await DbUser.findOneOrFail({ email }) - const optInCode = await getOptInCode(user.id) + // can be both types: REGISTER and RESET_PASSWORD + let optInCode = await LoginEmailOptIn.findOne({ + userId: user.id, + }) + + if (optInCode) { + if (!canResendOptin(optInCode)) { + throw new Error( + `email already sent less than $(printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} minutes ago`, + ) + } + optInCode.updatedAt = new Date() + optInCode.resendCount++ + } else { + optInCode = newEmailOptin(user.id) + } + // now it is RESET_PASSWORD + optInCode.emailOptInTypeId = OptinType.EMAIL_OPT_IN_RESET_PASSWORD + await LoginEmailOptIn.save(optInCode) const link = CONFIG.EMAIL_LINK_SETPASSWORD.replace( /{optin}/g, From 1e3300ad5a2c276786089c25a5bc9993496e268b Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 18:38:24 +0100 Subject: [PATCH 12/19] use optIn as naming convention --- .../enum/{OptinType.ts => OptInType.ts} | 6 +-- backend/src/graphql/resolver/UserResolver.ts | 38 +++++++++---------- 2 files changed, 22 insertions(+), 22 deletions(-) rename backend/src/graphql/enum/{OptinType.ts => OptInType.ts} (64%) diff --git a/backend/src/graphql/enum/OptinType.ts b/backend/src/graphql/enum/OptInType.ts similarity index 64% rename from backend/src/graphql/enum/OptinType.ts rename to backend/src/graphql/enum/OptInType.ts index 7e7edde93..2dd2d07b0 100644 --- a/backend/src/graphql/enum/OptinType.ts +++ b/backend/src/graphql/enum/OptInType.ts @@ -1,11 +1,11 @@ import { registerEnumType } from 'type-graphql' -export enum OptinType { +export enum OptInType { EMAIL_OPT_IN_REGISTER = 1, EMAIL_OPT_IN_RESET_PASSWORD = 2, } -registerEnumType(OptinType, { - name: 'OptinType', // this one is mandatory +registerEnumType(OptInType, { + name: 'OptInType', // this one is mandatory description: 'Type of the email optin', // this one is optional }) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index 50bba974f..9f48049e1 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -15,7 +15,7 @@ import UpdateUserInfosArgs from '@arg/UpdateUserInfosArgs' import { klicktippNewsletterStateMiddleware } from '@/middleware/klicktippMiddleware' import { UserSettingRepository } from '@repository/UserSettingRepository' import { Setting } from '@enum/Setting' -import { OptinType } from '@enum/OptinType' +import { OptInType } from '@enum/OptInType' import { LoginEmailOptIn } from '@entity/LoginEmailOptIn' import { sendResetPasswordEmail } from '@/mailer/sendResetPasswordEmail' import { sendAccountActivationEmail } from '@/mailer/sendAccountActivationEmail' @@ -147,11 +147,11 @@ const SecretKeyCryptographyDecrypt = (encryptedMessage: Buffer, encryptionKey: B return message } -const newEmailOptin = (userId: number): LoginEmailOptIn => { +const newEmailOptIn = (userId: number): LoginEmailOptIn => { const emailOptIn = new LoginEmailOptIn() emailOptIn.verificationCode = random(64) emailOptIn.userId = userId - emailOptIn.emailOptInTypeId = OptinType.EMAIL_OPT_IN_REGISTER + emailOptIn.emailOptInTypeId = OptInType.EMAIL_OPT_IN_REGISTER return emailOptIn } @@ -161,11 +161,11 @@ const createEmailOptIn = async ( ): Promise => { let emailOptIn = await LoginEmailOptIn.findOne({ userId, - emailOptInTypeId: OptinType.EMAIL_OPT_IN_REGISTER, + emailOptInTypeId: OptInType.EMAIL_OPT_IN_REGISTER, }) if (emailOptIn) { - if (isOptinValid(emailOptIn)) { + if (isOptInValid(emailOptIn)) { throw new Error( `email already sent less than ${printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} ago`, ) @@ -176,7 +176,7 @@ const createEmailOptIn = async ( emailOptIn = new LoginEmailOptIn() emailOptIn.verificationCode = random(64) emailOptIn.userId = userId - emailOptIn.emailOptInTypeId = OptinType.EMAIL_OPT_IN_REGISTER + emailOptIn.emailOptInTypeId = OptInType.EMAIL_OPT_IN_REGISTER } await queryRunner.manager.save(emailOptIn).catch((error) => { // eslint-disable-next-line no-console @@ -350,7 +350,7 @@ export class UserResolver { throw new Error('error saving user') }) - const emailOptIn = newEmailOptin(dbUser.id) + const emailOptIn = newEmailOptIn(dbUser.id) await queryRunner.manager.save(emailOptIn).catch((error) => { // eslint-disable-next-line no-console console.log('Error while saving emailOptIn', error) @@ -444,7 +444,7 @@ export class UserResolver { }) if (optInCode) { - if (!canResendOptin(optInCode)) { + if (!canResendOptIn(optInCode)) { throw new Error( `email already sent less than $(printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} minutes ago`, ) @@ -452,10 +452,10 @@ export class UserResolver { optInCode.updatedAt = new Date() optInCode.resendCount++ } else { - optInCode = newEmailOptin(user.id) + optInCode = newEmailOptIn(user.id) } // now it is RESET_PASSWORD - optInCode.emailOptInTypeId = OptinType.EMAIL_OPT_IN_RESET_PASSWORD + optInCode.emailOptInTypeId = OptInType.EMAIL_OPT_IN_RESET_PASSWORD await LoginEmailOptIn.save(optInCode) const link = CONFIG.EMAIL_LINK_SETPASSWORD.replace( @@ -501,7 +501,7 @@ export class UserResolver { }) // Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes - if (!isOptinValid(optInCode)) { + if (!isOptInValid(optInCode)) { throw new Error( `email was sent more than ${printTimeDuration(CONFIG.EMAIL_CODE_VALID_TIME)} ago`, ) @@ -562,7 +562,7 @@ export class UserResolver { // Sign into Klicktipp // TODO do we always signUp the user? How to handle things with old users? - if (optInCode.emailOptInTypeId === OptinType.EMAIL_OPT_IN_REGISTER) { + if (optInCode.emailOptInTypeId === OptInType.EMAIL_OPT_IN_REGISTER) { try { await klicktippSignIn(user.email, user.language, user.firstName, user.lastName) } catch { @@ -582,7 +582,7 @@ export class UserResolver { async queryOptIn(@Arg('optIn') optIn: string): Promise { const optInCode = await LoginEmailOptIn.findOneOrFail({ verificationCode: optIn }) // Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes - if (!isOptinValid(optInCode)) { + if (!isOptInValid(optInCode)) { throw new Error( `email was sent more than $(printTimeDuration(CONFIG.EMAIL_CODE_VALID_TIME)} ago`, ) @@ -692,18 +692,18 @@ export class UserResolver { } } -const isTimeExpired = (optin: LoginEmailOptIn, duration: number): boolean => { - const timeElapsed = Date.now() - new Date(optin.updatedAt).getTime() +const isTimeExpired = (optIn: LoginEmailOptIn, duration: number): boolean => { + const timeElapsed = Date.now() - new Date(optIn.updatedAt).getTime() // time is given in minutes return timeElapsed <= duration * 60 * 1000 } -const isOptinValid = (optin: LoginEmailOptIn): boolean => { - return isTimeExpired(optin, CONFIG.EMAIL_CODE_VALID_TIME) +const isOptInValid = (optIn: LoginEmailOptIn): boolean => { + return isTimeExpired(optIn, CONFIG.EMAIL_CODE_VALID_TIME) } -const canResendOptin = (optin: LoginEmailOptIn): boolean => { - return isTimeExpired(optin, CONFIG.EMAIL_CODE_REQUEST_TIME) +const canResendOptIn = (optIn: LoginEmailOptIn): boolean => { + return isTimeExpired(optIn, CONFIG.EMAIL_CODE_REQUEST_TIME) } const getTimeDurationObject = (time: number): { hours?: number; minutes: number } => { From 9da2047e8c0899b3210bc7e255d5e3dbb5da00cc Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 19:14:59 +0100 Subject: [PATCH 13/19] move sendActivationEmail mutation from user to admin resolver --- backend/src/graphql/resolver/AdminResolver.ts | 36 ++++++ backend/src/graphql/resolver/UserResolver.ts | 106 ++++-------------- 2 files changed, 57 insertions(+), 85 deletions(-) diff --git a/backend/src/graphql/resolver/AdminResolver.ts b/backend/src/graphql/resolver/AdminResolver.ts index d98b38b7f..061c485c5 100644 --- a/backend/src/graphql/resolver/AdminResolver.ts +++ b/backend/src/graphql/resolver/AdminResolver.ts @@ -34,6 +34,8 @@ import { Decay } from '@model/Decay' import Paginated from '@arg/Paginated' import { Order } from '@enum/Order' import { communityUser } from '@/util/communityUser' +import { checkExistingOptInCode, activationLink } from './UserResolver' +import { sendAccountActivationEmail } from '@/mailer/sendAccountActivationEmail' // const EMAIL_OPT_IN_REGISTER = 1 // const EMAIL_OPT_UNKNOWN = 3 // elopage? @@ -369,6 +371,40 @@ export class AdminResolver { const user = await dbUser.findOneOrFail({ id: userId }) return userTransactions.map((t) => new Transaction(t, new User(user), communityUser)) } + + @Authorized([RIGHTS.SEND_ACTIVATION_EMAIL]) + @Mutation(() => Boolean) + async sendActivationEmail(@Arg('email') email: string): Promise { + email = email.trim().toLowerCase() + const user = await dbUser.findOneOrFail({ email: email }) + + // can be both types: REGISTER and RESET_PASSWORD + let optInCode = await LoginEmailOptIn.findOne({ + userId: user.id, + }) + + optInCode = checkExistingOptInCode(optInCode, user.id) + // keep the optin type (when newly created is is REGISTER) + await LoginEmailOptIn.save(optInCode) + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const emailSent = await sendAccountActivationEmail({ + link: activationLink(optInCode), + firstName: user.firstName, + lastName: user.lastName, + email, + }) + + /* uncomment this, when you need the activation link on the console + // In case EMails are disabled log the activation link for the user + if (!emailSent) { + // eslint-disable-next-line no-console + console.log(`Account confirmation link: ${activationLink}`) + } + */ + + return true + } } interface CreationMap { diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index 9f48049e1..7cce31eab 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -3,7 +3,7 @@ import fs from 'fs' import { Resolver, Query, Args, Arg, Authorized, Ctx, UseMiddleware, Mutation } from 'type-graphql' -import { getConnection, getCustomRepository, QueryRunner } from '@dbTools/typeorm' +import { getConnection, getCustomRepository } from '@dbTools/typeorm' import CONFIG from '@/config' import { User } from '@model/User' import { User as DbUser } from '@entity/User' @@ -155,35 +155,29 @@ const newEmailOptIn = (userId: number): LoginEmailOptIn => { return emailOptIn } -const createEmailOptIn = async ( +// needed by AdminResolver +// checks if given code exists and can be resent +// if optIn does not exits, it is created +export const checkExistingOptInCode = ( + optInCode: LoginEmailOptIn | undefined, userId: number, - queryRunner: QueryRunner, -): Promise => { - let emailOptIn = await LoginEmailOptIn.findOne({ - userId, - emailOptInTypeId: OptInType.EMAIL_OPT_IN_REGISTER, - }) - - if (emailOptIn) { - if (isOptInValid(emailOptIn)) { +): LoginEmailOptIn => { + if (optInCode) { + if (!canResendOptIn(optInCode)) { throw new Error( - `email already sent less than ${printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} ago`, + `email already sent less than $(printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} minutes ago`, ) } - emailOptIn.updatedAt = new Date() - emailOptIn.resendCount++ + optInCode.updatedAt = new Date() + optInCode.resendCount++ } else { - emailOptIn = new LoginEmailOptIn() - emailOptIn.verificationCode = random(64) - emailOptIn.userId = userId - emailOptIn.emailOptInTypeId = OptInType.EMAIL_OPT_IN_REGISTER + optInCode = newEmailOptIn(userId) } - await queryRunner.manager.save(emailOptIn).catch((error) => { - // eslint-disable-next-line no-console - console.log('Error while saving emailOptIn', error) - throw new Error('error saving email opt in') - }) - return emailOptIn + return optInCode +} + +export const activationLink = (optInCode: LoginEmailOptIn): string => { + return CONFIG.EMAIL_LINK_SETPASSWORD.replace(/{optin}/g, optInCode.verificationCode.toString()) } @Resolver() @@ -388,50 +382,6 @@ export class UserResolver { return new User(dbUser) } - // This is used by the admin only - should we move it to the admin resolver? - @Authorized([RIGHTS.SEND_ACTIVATION_EMAIL]) - @Mutation(() => Boolean) - async sendActivationEmail(@Arg('email') email: string): Promise { - email = email.trim().toLowerCase() - const user = await DbUser.findOneOrFail({ email: email }) - - const queryRunner = getConnection().createQueryRunner() - await queryRunner.connect() - await queryRunner.startTransaction('READ UNCOMMITTED') - - try { - const emailOptIn = await createEmailOptIn(user.id, queryRunner) - - const activationLink = CONFIG.EMAIL_LINK_VERIFICATION.replace( - /{optin}/g, - emailOptIn.verificationCode.toString(), - ) - - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const emailSent = await sendAccountActivationEmail({ - link: activationLink, - firstName: user.firstName, - lastName: user.lastName, - email, - }) - - /* uncomment this, when you need the activation link on the console - // In case EMails are disabled log the activation link for the user - if (!emailSent) { - // eslint-disable-next-line no-console - console.log(`Account confirmation link: ${activationLink}`) - } - */ - await queryRunner.commitTransaction() - } catch (e) { - await queryRunner.rollbackTransaction() - throw e - } finally { - await queryRunner.release() - } - return true - } - @Authorized([RIGHTS.SEND_RESET_PASSWORD_EMAIL]) @Query(() => Boolean) async sendResetPasswordEmail(@Arg('email') email: string): Promise { @@ -443,29 +393,14 @@ export class UserResolver { userId: user.id, }) - if (optInCode) { - if (!canResendOptIn(optInCode)) { - throw new Error( - `email already sent less than $(printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} minutes ago`, - ) - } - optInCode.updatedAt = new Date() - optInCode.resendCount++ - } else { - optInCode = newEmailOptIn(user.id) - } + optInCode = checkExistingOptInCode(optInCode, user.id) // now it is RESET_PASSWORD optInCode.emailOptInTypeId = OptInType.EMAIL_OPT_IN_RESET_PASSWORD await LoginEmailOptIn.save(optInCode) - const link = CONFIG.EMAIL_LINK_SETPASSWORD.replace( - /{optin}/g, - optInCode.verificationCode.toString(), - ) - // eslint-disable-next-line @typescript-eslint/no-unused-vars const emailSent = await sendResetPasswordEmail({ - link, + link: activationLink(optInCode), firstName: user.firstName, lastName: user.lastName, email, @@ -547,6 +482,7 @@ export class UserResolver { throw new Error('error saving user: ' + error) }) + // why do we delete the code? // Delete Code await queryRunner.manager.remove(optInCode).catch((error) => { throw new Error('error deleting code: ' + error) From 5456affb9c8db21a8b5a96dcf0355f3c2450770a Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Thu, 24 Mar 2022 19:27:32 +0100 Subject: [PATCH 14/19] fix logic (not canResendOptIn), fix error strings --- backend/src/graphql/resolver/UserResolver.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index 7cce31eab..7d465c213 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -165,7 +165,9 @@ export const checkExistingOptInCode = ( if (optInCode) { if (!canResendOptIn(optInCode)) { throw new Error( - `email already sent less than $(printTimeDuration(CONFIG.EMAIL_CODE_REQUEST_TIME)} minutes ago`, + `email already sent less than ${printTimeDuration( + CONFIG.EMAIL_CODE_REQUEST_TIME, + )} minutes ago`, ) } optInCode.updatedAt = new Date() @@ -520,7 +522,7 @@ export class UserResolver { // Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes if (!isOptInValid(optInCode)) { throw new Error( - `email was sent more than $(printTimeDuration(CONFIG.EMAIL_CODE_VALID_TIME)} ago`, + `email was sent more than ${printTimeDuration(CONFIG.EMAIL_CODE_VALID_TIME)} ago`, ) } return true @@ -639,7 +641,7 @@ const isOptInValid = (optIn: LoginEmailOptIn): boolean => { } const canResendOptIn = (optIn: LoginEmailOptIn): boolean => { - return isTimeExpired(optIn, CONFIG.EMAIL_CODE_REQUEST_TIME) + return !isTimeExpired(optIn, CONFIG.EMAIL_CODE_REQUEST_TIME) } const getTimeDurationObject = (time: number): { hours?: number; minutes: number } => { From cb902493018ff083bbff07d2fe4fbad687cc9b73 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Tue, 29 Mar 2022 00:50:50 +0200 Subject: [PATCH 15/19] rename function, add parameter for optinType, sort by updatedAt DESC --- backend/src/graphql/resolver/AdminResolver.ts | 9 ++++----- backend/src/graphql/resolver/UserResolver.ts | 14 ++++++++------ 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/backend/src/graphql/resolver/AdminResolver.ts b/backend/src/graphql/resolver/AdminResolver.ts index 061c485c5..7f966b275 100644 --- a/backend/src/graphql/resolver/AdminResolver.ts +++ b/backend/src/graphql/resolver/AdminResolver.ts @@ -34,7 +34,7 @@ import { Decay } from '@model/Decay' import Paginated from '@arg/Paginated' import { Order } from '@enum/Order' import { communityUser } from '@/util/communityUser' -import { checkExistingOptInCode, activationLink } from './UserResolver' +import { checkOptInCode, activationLink } from './UserResolver' import { sendAccountActivationEmail } from '@/mailer/sendAccountActivationEmail' // const EMAIL_OPT_IN_REGISTER = 1 @@ -380,12 +380,11 @@ export class AdminResolver { // can be both types: REGISTER and RESET_PASSWORD let optInCode = await LoginEmailOptIn.findOne({ - userId: user.id, + where: { userId: user.id }, + order: { updatedAt: 'DESC' }, }) - optInCode = checkExistingOptInCode(optInCode, user.id) - // keep the optin type (when newly created is is REGISTER) - await LoginEmailOptIn.save(optInCode) + optInCode = await checkOptInCode(optInCode, user.id) // eslint-disable-next-line @typescript-eslint/no-unused-vars const emailSent = await sendAccountActivationEmail({ diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index 7d465c213..81ca42d5c 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -158,10 +158,11 @@ const newEmailOptIn = (userId: number): LoginEmailOptIn => { // needed by AdminResolver // checks if given code exists and can be resent // if optIn does not exits, it is created -export const checkExistingOptInCode = ( +export const checkOptInCode = async ( optInCode: LoginEmailOptIn | undefined, userId: number, -): LoginEmailOptIn => { + optInType: OptInType = OptInType.EMAIL_OPT_IN_REGISTER, +): Promise => { if (optInCode) { if (!canResendOptIn(optInCode)) { throw new Error( @@ -175,6 +176,10 @@ export const checkExistingOptInCode = ( } else { optInCode = newEmailOptIn(userId) } + optInCode.emailOptInTypeId = optInType + await LoginEmailOptIn.save(optInCode).catch(() => { + throw new Error('Unable to save optin code.') + }) return optInCode } @@ -395,10 +400,7 @@ export class UserResolver { userId: user.id, }) - optInCode = checkExistingOptInCode(optInCode, user.id) - // now it is RESET_PASSWORD - optInCode.emailOptInTypeId = OptInType.EMAIL_OPT_IN_RESET_PASSWORD - await LoginEmailOptIn.save(optInCode) + optInCode = await checkOptInCode(optInCode, user.id, OptInType.EMAIL_OPT_IN_RESET_PASSWORD) // eslint-disable-next-line @typescript-eslint/no-unused-vars const emailSent = await sendResetPasswordEmail({ From 37e36e01af02a5b5dd8f1b52c7015efbdcec5c69 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Tue, 29 Mar 2022 00:51:44 +0200 Subject: [PATCH 16/19] do not remove optin code in DB after email verification --- backend/src/graphql/resolver/UserResolver.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/backend/src/graphql/resolver/UserResolver.ts b/backend/src/graphql/resolver/UserResolver.ts index 81ca42d5c..07cd90a23 100644 --- a/backend/src/graphql/resolver/UserResolver.ts +++ b/backend/src/graphql/resolver/UserResolver.ts @@ -486,12 +486,6 @@ export class UserResolver { throw new Error('error saving user: ' + error) }) - // why do we delete the code? - // Delete Code - await queryRunner.manager.remove(optInCode).catch((error) => { - throw new Error('error deleting code: ' + error) - }) - await queryRunner.commitTransaction() } catch (e) { await queryRunner.rollbackTransaction() From 8fd93ff8539bf404fe6c89d66b68df794ceba96e Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Tue, 29 Mar 2022 02:58:36 +0200 Subject: [PATCH 17/19] remove test for remove optin from DB after email verification --- backend/src/graphql/resolver/UserResolver.test.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/backend/src/graphql/resolver/UserResolver.test.ts b/backend/src/graphql/resolver/UserResolver.test.ts index 726ecfb09..c01cf2de9 100644 --- a/backend/src/graphql/resolver/UserResolver.test.ts +++ b/backend/src/graphql/resolver/UserResolver.test.ts @@ -221,10 +221,6 @@ describe('UserResolver', () => { expect(newUser[0].password).toEqual('3917921995996627700') }) - it('removes the optin', async () => { - await expect(LoginEmailOptIn.find()).resolves.toHaveLength(0) - }) - /* it('calls the klicktipp API', () => { expect(klicktippSignIn).toBeCalledWith( From 667b964d372c79e3afa1b6bd2292dd0a7e31844d Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Tue, 29 Mar 2022 02:59:25 +0200 Subject: [PATCH 18/19] coverage backend to 55% --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 18d1143db..ee602a343 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -528,7 +528,7 @@ jobs: report_name: Coverage Backend type: lcov result_path: ./backend/coverage/lcov.info - min_coverage: 54 + min_coverage: 55 token: ${{ github.token }} ########################################################################## From b3002027cd34869d8b8dfb271ca2943fe2652dc0 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Tue, 29 Mar 2022 19:38:12 +0200 Subject: [PATCH 19/19] new backend version in env dist --- deployment/bare_metal/.env.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/bare_metal/.env.dist b/deployment/bare_metal/.env.dist index 88dfff6f5..1cb78299a 100644 --- a/deployment/bare_metal/.env.dist +++ b/deployment/bare_metal/.env.dist @@ -18,7 +18,7 @@ WEBHOOK_GITHUB_SECRET=secret WEBHOOK_GITHUB_BRANCH=master # backend -BACKEND_CONFIG_VERSION=v1.2022-03-18 +BACKEND_CONFIG_VERSION=v2.2022-03-24 EMAIL=true EMAIL_USERNAME=peter@lustig.de