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

mozilla / blurts-server / #13412

pending completion
#13412

push

circleci

Vinnl
Add unique page titles

282 of 1792 branches covered (15.74%)

Branch coverage included in aggregate %.

959 of 4671 relevant lines covered (20.53%)

1.71 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 '../appConstants.js'
6

7
import {
8
  getUserEmails,
9
  resetUnverifiedEmailAddress,
10
  addSubscriberUnverifiedEmailHash,
11
  removeOneSecondaryEmail,
12
  getEmailById,
13
  verifyEmailHash
14
} from '../db/tables/emailAddresses.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/email2022.js'
30
import { verifyPartial } from '../views/emails/emailVerify.js'
31

32
async function settingsPage (req, res) {
33
  /** @type {Array<import('../db/tables/emailAddresses.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
    meta: {
65
      title: getMessage('settings-meta-title')
66
    }
67
  }
68

69
  res.send(mainLayout(data))
×
70
}
71

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

77
  if (validatedEmail === null) {
×
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, validatedEmail.email)
×
86

87
  const unverifiedSubscriber = await addSubscriberUnverifiedEmailHash(
×
88
    req.session.user,
89
    validatedEmail.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