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

mozilla / blurts-server / #13198

pending completion
#13198

push

circleci

Vinnl
Allow scanning for exposures without logging in

Co-authored-by: Robert Helmer <rhelmer@mozilla.com>

282 of 1653 branches covered (17.06%)

Branch coverage included in aggregate %.

107 of 107 new or added lines in 9 files covered. (100.0%)

959 of 4482 relevant lines covered (21.4%)

1.78 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 { validateEmailAddress } from '../utils/emailAddress.js'
24
import { generateToken } from '../utils/csrf.js'
25
import { RateLimitError, UnauthorizedError, UserInputError } from '../utils/error.js'
26

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

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

43
  const breachCounts = new Map()
×
44

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

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

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

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

70
async function addEmail (req, res) {
71
  const sessionUser = req.user
×
72
  const emailCount = 1 + (req.user.email_addresses?.length ?? 0) // primary + verified + unverified emails
×
73
  const validatedEmail = validateEmailAddress(req.body.email)
×
74

75
  if (validatedEmail === null) {
×
76
    throw new UserInputError(getMessage('user-add-invalid-email'))
×
77
  }
78

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

83
  checkForDuplicateEmail(sessionUser, validatedEmail.email)
×
84

85
  const unverifiedSubscriber = await addSubscriberUnverifiedEmailHash(
×
86
    req.session.user,
87
    validatedEmail.email
88
  )
89

90
  await sendVerificationEmail(sessionUser, unverifiedSubscriber.id)
×
91

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

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

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

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

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

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

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

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

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

140
  await sendVerificationEmail(sessionUser, emailId)
×
141

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

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

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

181
  return res.redirect('/user/settings')
×
182
}
183

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

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

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