({ request, user, match, session, isRunningLocally }: RequestHandlerParams)
| 41 | } |
| 42 | |
| 43 | async function post({ request, user, match, session, isRunningLocally }: RequestHandlerParams): Promise<Response> { |
| 44 | const isExpensesAppEnabled = await AppConfig.isAppEnabled('expenses'); |
| 45 | const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail; |
| 46 | const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled(); |
| 47 | const isCalendarAppEnabled = await AppConfig.isAppEnabled('calendar'); |
| 48 | |
| 49 | let action: Action = 'change-email'; |
| 50 | let errorTitle = ''; |
| 51 | let errorMessage = ''; |
| 52 | let successTitle = ''; |
| 53 | let successMessage = ''; |
| 54 | |
| 55 | const formData = await request.clone().formData(); |
| 56 | |
| 57 | try { |
| 58 | action = getFormDataField(formData, 'action') as Action; |
| 59 | |
| 60 | if (action !== 'change-email' && action !== 'verify-change-email') { |
| 61 | formData.set('email', user!.email); |
| 62 | } |
| 63 | |
| 64 | if ((action === 'change-email' || action === 'verify-change-email')) { |
| 65 | const email = getFormDataField(formData, 'email'); |
| 66 | |
| 67 | if (!validateEmail(email)) { |
| 68 | throw new Error(`Invalid email.`); |
| 69 | } |
| 70 | |
| 71 | if (email === user!.email) { |
| 72 | throw new Error(`New email is the same as the current email.`); |
| 73 | } |
| 74 | |
| 75 | const matchingUser = await UserModel.getByEmail(email); |
| 76 | |
| 77 | if (matchingUser) { |
| 78 | throw new Error('Email is already in use.'); |
| 79 | } |
| 80 | |
| 81 | if (action === 'change-email' && (await AppConfig.isEmailVerificationEnabled())) { |
| 82 | const verificationCode = await VerificationCodeModel.create(user!, email, 'email'); |
| 83 | |
| 84 | await EmailModel.sendVerificationEmail(email, verificationCode); |
| 85 | |
| 86 | successTitle = 'Verify your email!'; |
| 87 | successMessage = 'You have received a code in your new email. Use it to verify it here.'; |
| 88 | } else { |
| 89 | if (await AppConfig.isEmailVerificationEnabled()) { |
| 90 | const code = getFormDataField(formData, 'verification-code'); |
| 91 | |
| 92 | await VerificationCodeModel.validate(user!, email, code, 'email'); |
| 93 | } |
| 94 | |
| 95 | user!.email = email; |
| 96 | |
| 97 | await UserModel.update(user!); |
| 98 | |
| 99 | successTitle = 'Email updated!'; |
| 100 | successMessage = 'Email updated successfully.'; |
nothing calls this directly
no test coverage detected