• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mozilla / blurts-server / #12108

pending completion
#12108

push

circleci

web-flow
MNTOR-1004 backend work for v2 settings (#2773)

* backend work for v2 settings MNTOR-1004

* chore: Convert confirmation email images to webp (#2799)

---------

Co-authored-by: Florian Zia <zia.florian@gmail.com>

282 of 1245 branches covered (22.65%)

Branch coverage included in aggregate %.

77 of 77 new or added lines in 4 files covered. (100.0%)

959 of 3372 relevant lines covered (28.44%)

2.31 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/controllers/settings.js
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4

5
import AppConstants from '../app-constants.js'
6

7
import {
8
  getUserEmails,
9
  resetUnverifiedEmailAddress,
10
  addSubscriberUnverifiedEmailHash,
11
  removeOneSecondaryEmail,
12
  getEmailById,
13
  verifyEmailHash
14
} from '../db/tables/email_addresses.js'
15

16
import { setAllEmailsToPrimary } from '../db/tables/subscribers.js'
17

18
import { fluentError, getMessage } from '../utils/fluent.js'
19
import { sendEmail, getVerificationUrl, getUnsubscribeUrl } from '../utils/email.js'
20

21
import { getBreachesForEmail } from '../utils/hibp.js'
22
import { generateToken } from '../utils/csrf.js'
23

24
import { mainLayout } from '../views/main.js'
25
import { settings } from '../views/partials/settings.js'
26
import { getTemplate } from '../views/email-2022.js'
27
import { verifyPartial } from '../views/partials/email-verify.js'
28

29
async function settingsPage (req, res) {
30
  const emails = await getUserEmails(req.session.user.id)
×
31
  // Add primary subscriber email to the list
32
  emails.push({
×
33
    email: req.session.user.primary_email,
34
    sha1: req.session.user.primary_sha1,
35
    primary: true,
36
    verified: true
37
  })
38

39
  const breachCounts = new Map()
×
40

41
  const allBreaches = req.app.locals.breaches
×
42
  for (const email of emails) {
×
43
    const breaches = await getBreachesForEmail(
×
44
      email.sha1,
45
      allBreaches,
46
      true,
47
      false
48
    )
49
    breachCounts.set(email.email, breaches?.length || 0)
×
50
  }
51

52
  const data = {
×
53
    fxaProfile: req.user.fxa_profile_json,
54
    partial: settings,
55
    emails,
56
    breachCounts,
57
    limit: AppConstants.MAX_NUM_ADDRESSES,
58
    csrfToken: generateToken(res)
59
  }
60

61
  res.send(mainLayout(data))
×
62
}
63

64
async function addEmail (req, res) {
65
  const sessionUser = req.user
×
66
  const email = req.body.email
×
67
  // Use the same regex as HTML5 email input type
68
  // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#basic_validation
69
  const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
×
70

71
  if (!email || !emailRegex.test(email)) {
×
72
    throw fluentError('user-add-invalid-email')
×
73
  }
74

75
  if (sessionUser.email_addresses.length >= AppConstants.MAX_NUM_ADDRESSES) {
×
76
    throw fluentError('user-add-too-many-emails')
×
77
  }
78

79
  checkForDuplicateEmail(sessionUser, email)
×
80

81
  const unverifiedSubscriber = await addSubscriberUnverifiedEmailHash(
×
82
    req.session.user,
83
    email
84
  )
85

86
  await sendVerificationEmail(unverifiedSubscriber.id)
×
87

88
  return res.json({
×
89
    success: true,
90
    status: 200,
91
    message: 'Sent the verification email'
92
  })
93
}
94

95
function checkForDuplicateEmail (sessionUser, email) {
96
  const emailLowerCase = email.toLowerCase()
×
97
  if (emailLowerCase === sessionUser.primary_email.toLowerCase()) {
×
98
    throw fluentError('user-add-duplicate-email')
×
99
  }
100

101
  for (const secondaryEmail of sessionUser.email_addresses) {
×
102
    if (emailLowerCase === secondaryEmail.email.toLowerCase()) {
×
103
      throw fluentError('user-add-duplicate-email')
×
104
    }
105
  }
106
}
107

108
async function removeEmail (req, res) {
109
  const emailId = req.body.emailId
×
110
  const sessionUser = req.user
×
111
  const existingEmail = await getEmailById(emailId)
×
112

113
  if (existingEmail.subscriber_id !== sessionUser.id) {
×
114
    throw fluentError('error-not-subscribed')
×
115
  }
116

117
  removeOneSecondaryEmail(emailId)
×
118
  res.redirect('/user/settings')
×
119
}
120

121
async function resendEmail (req, res) {
122
  const emailId = req.body.emailId
×
123
  const sessionUser = req.user
×
124
  const existingEmail = await getUserEmails(sessionUser.id)
×
125

126
  const filteredEmail = existingEmail.filter(
×
127
    (a) => a.email === emailId && a.subscriber_id === sessionUser.id
×
128
  )
129

130
  if (!filteredEmail) {
×
131
    throw fluentError('user-verify-token-error')
×
132
  }
133

134
  await sendVerificationEmail(emailId)
×
135

136
  return res.json({
×
137
    success: true,
138
    status: 200,
139
    message: 'Sent the verification email'
140
  })
141
}
142

143
async function sendVerificationEmail (emailId) {
144
  const unverifiedEmailAddressRecord = await resetUnverifiedEmailAddress(
×
145
    emailId
146
  )
147
  const recipientEmail = unverifiedEmailAddressRecord.email
×
148
  const data = {
×
149
    recipientEmail,
150
    ctaHref: getVerificationUrl(unverifiedEmailAddressRecord),
151
    utmCampaign: 'email_verify',
152
    unsubscribeUrl: getUnsubscribeUrl(
153
      unverifiedEmailAddressRecord,
154
      'account-verification-email'
155
    ),
156
    heading: getMessage('email-verify-heading'),
157
    subheading: getMessage('email-verify-subhead'),
158
    partial: { name: 'verify' }
159
  }
160
  await sendEmail(
×
161
    recipientEmail,
162
    getMessage('email-subject-verify'),
163
    getTemplate(data, verifyPartial(data))
164
  )
165
}
166

167
async function verifyEmail (req, res) {
168
  const token = req.query.token
×
169
  await verifyEmailHash(token)
×
170

171
  return res.redirect('/user/settings')
×
172
}
173

174
async function updateCommunicationOptions (req, res) {
175
  const sessionUser = req.user
×
176
  // 0 = Send breach alerts to the email address found in brew breach.
177
  // 1 = Send all breach alerts to user's primary email address.
178
  const allEmailsToPrimary = Number(req.body.communicationOption) === 1
×
179
  const updatedSubscriber = await setAllEmailsToPrimary(
×
180
    sessionUser,
181
    allEmailsToPrimary
182
  )
183
  req.session.user = updatedSubscriber
×
184

185
  return res.json({
×
186
    success: true,
187
    status: 200,
188
    message: 'Communications options updated'
189
  })
190
}
191

192
export {
193
  settingsPage,
194
  resendEmail,
195
  addEmail,
196
  removeEmail,
197
  verifyEmail,
198
  updateCommunicationOptions
199
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc