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

mozilla / blurts-server / 45ba77d7-fd3c-4064-90eb-157d6aa10611

pending completion
45ba77d7-fd3c-4064-90eb-157d6aa10611

push

circleci

Robert Helmer
update the queue adr

282 of 1631 branches covered (17.29%)

Branch coverage included in aggregate %.

959 of 4375 relevant lines covered (21.92%)

3.65 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, deleteResolutionsWithEmail } from '../db/tables/subscribers.js'
17

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

21
import { getBreachesForEmail } from '../utils/hibp.js'
22
import { getSha1 } from '../utils/fxa.js'
23
import { generateToken } from '../utils/csrf.js'
24
import { RateLimitError, UnauthorizedError, UserInputError } from '../utils/error.js'
25

26
import { mainLayout } from '../views/mainLayout.js'
27
import { settings } from '../views/partials/settings.js'
28
import { getTemplate } from '../views/emails/email-2022.js'
29
import { verifyPartial } from '../views/emails/email-verify.js'
30

31
async function settingsPage (req, res) {
32
  /** @type {Array<import('../db/tables/email_addresses.js').EmailRow>} */
33
  const emails = await getUserEmails(req.session.user.id)
×
34
  // Add primary subscriber email to the list
35
  emails.push({
×
36
    email: req.session.user.primary_email,
37
    sha1: req.session.user.primary_sha1,
38
    primary: true,
39
    verified: true
40
  })
41

42
  const breachCounts = new Map()
×
43

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

50
  const {
51
    all_emails_to_primary: allEmailsToPrimary,
52
    fxa_profile_json: fxaProfile
53
  } = req.user
×
54

55
  const data = {
×
56
    allEmailsToPrimary,
57
    fxaProfile,
58
    partial: settings,
59
    emails,
60
    breachCounts,
61
    limit: AppConstants.MAX_NUM_ADDRESSES,
62
    csrfToken: generateToken(res),
63
    nonce: res.locals.nonce
64
  }
65

66
  res.send(mainLayout(data))
×
67
}
68

69
async function addEmail (req, res) {
70
  const sessionUser = req.user
×
71
  const email = req.body.email
×
72
  // Use the same regex as HTML5 email input type
73
  // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#basic_validation
74
  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])?)*$/
×
75
  const emailCount = 1 + (req.user.email_addresses?.length ?? 0) // primary + verified + unverified emails
×
76

77
  if (!email || !emailRegex.test(email)) {
×
78
    throw new UserInputError(getMessage('user-add-invalid-email'))
×
79
  }
80

81
  if (emailCount >= AppConstants.MAX_NUM_ADDRESSES) {
×
82
    throw new UserInputError(getMessage('user-add-too-many-emails'))
×
83
  }
84

85
  checkForDuplicateEmail(sessionUser, email)
×
86

87
  const unverifiedSubscriber = await addSubscriberUnverifiedEmailHash(
×
88
    req.session.user,
89
    email
90
  )
91

92
  await sendVerificationEmail(sessionUser, unverifiedSubscriber.id)
×
93

94
  return res.json({
×
95
    success: true,
96
    status: 200,
97
    newEmailCount: emailCount + 1,
98
    message: 'Sent the verification email'
99
  })
100
}
101

102
function checkForDuplicateEmail (sessionUser, email) {
103
  const emailLowerCase = email.toLowerCase()
×
104
  if (emailLowerCase === sessionUser.primary_email.toLowerCase()) {
×
105
    throw new UserInputError(getMessage('user-add-duplicate-email'))
×
106
  }
107

108
  for (const secondaryEmail of sessionUser.email_addresses) {
×
109
    if (emailLowerCase === secondaryEmail.email.toLowerCase()) {
×
110
      throw new UserInputError(getMessage('user-add-duplicate-email'))
×
111
    }
112
  }
113
}
114

115
async function removeEmail (req, res) {
116
  const emailId = req.body.emailId
×
117
  const sessionUser = req.user
×
118
  const existingEmail = await getEmailById(emailId)
×
119

120
  if (existingEmail?.subscriber_id !== sessionUser.id) {
×
121
    throw new UserInputError(getMessage('error-not-subscribed'))
×
122
  }
123

124
  removeOneSecondaryEmail(emailId)
×
125
  deleteResolutionsWithEmail(existingEmail.subscriber_id, existingEmail.email)
×
126
  res.redirect('/user/settings')
×
127
}
128

129
async function resendEmail (req, res) {
130
  const emailId = req.body.emailId
×
131
  const sessionUser = req.user
×
132
  const existingEmail = await getUserEmails(sessionUser.id)
×
133

134
  const filteredEmail = existingEmail.filter(
×
135
    (a) => a.email === emailId && a.subscriber_id === sessionUser.id
×
136
  )
137

138
  if (!filteredEmail) {
×
139
    throw new UnauthorizedError(getMessage('user-verify-token-error'))
×
140
  }
141

142
  await sendVerificationEmail(sessionUser, emailId)
×
143

144
  return res.json({
×
145
    success: true,
146
    status: 200,
147
    message: 'Sent the verification email'
148
  })
149
}
150

151
async function sendVerificationEmail (user, emailId) {
152
  try {
×
153
    const unverifiedEmailAddressRecord = await resetUnverifiedEmailAddress(
×
154
      emailId
155
    )
156
    const recipientEmail = unverifiedEmailAddressRecord.email
×
157
    const data = {
×
158
      recipientEmail,
159
      ctaHref: getVerificationUrl(unverifiedEmailAddressRecord),
160
      utmCampaign: 'email_verify',
161
      heading: getMessage('email-verify-heading'),
162
      subheading: getMessage('email-verify-subhead'),
163
      partial: { name: 'verify' }
164
    }
165
    await sendEmail(
×
166
      recipientEmail,
167
      getMessage('email-subject-verify'),
168
      getTemplate(data, verifyPartial)
169
    )
170
  } catch (err) {
171
    if (err.message === 'error-email-validation-pending') {
×
172
      throw new RateLimitError('Verification email recently sent, try again later')
×
173
    } else {
174
      throw err
×
175
    }
176
  }
177
}
178

179
async function verifyEmail (req, res) {
180
  const token = req.query.token
×
181
  await verifyEmailHash(token)
×
182

183
  return res.redirect('/user/settings')
×
184
}
185

186
async function updateCommunicationOptions (req, res) {
187
  const sessionUser = req.user
×
188
  // 0 = Send breach alerts to the email address found in brew breach.
189
  // 1 = Send all breach alerts to user's primary email address.
190
  const allEmailsToPrimary = Number(req.body.communicationOption) === 1
×
191
  const updatedSubscriber = await setAllEmailsToPrimary(
×
192
    sessionUser,
193
    allEmailsToPrimary
194
  )
195
  req.session.user = updatedSubscriber
×
196

197
  return res.json({
×
198
    success: true,
199
    status: 200,
200
    message: 'Communications options updated'
201
  })
202
}
203

204
export {
205
  settingsPage,
206
  resendEmail,
207
  addEmail,
208
  removeEmail,
209
  verifyEmail,
210
  updateCommunicationOptions
211
}
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

© 2025 Coveralls, Inc