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

mozilla / blurts-server / #13410

pending completion
#13410

push

circleci

jswinarton
more

282 of 1784 branches covered (15.81%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

959 of 4694 relevant lines covered (20.43%)

1.7 hits per line

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

0.0
/src/controllers/auth.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 { URL } from 'url'
6
import { randomBytes } from 'crypto'
7

8
import AppConstants from '../appConstants.js'
9
import {
10
  getSubscriberByEmail,
11
  removeFxAData,
12
  updateFxAData,
13
  updateFxAProfileData
14
} from '../db/tables/subscribers.js'
15
import { addSubscriber } from '../db/tables/emailAddresses.js'
16

17
import { getTemplate } from '../views/emails/email2022.js'
18
import {
19
  signupReportEmailPartial
20
} from '../views/emails/emailSignupReport.js'
21

22
import { getBreachesForEmail } from '../utils/hibp.js'
23
import { getMessage } from '../utils/fluent.js'
24
import { getProfileData, FxAOAuthClient, getSha1 } from '../utils/fxa.js'
25
import { getEmailCtaHref, sendEmail } from '../utils/email.js'
26
import { isSubscribed } from '../utils/subscriber.js'
27
import { UnauthorizedError } from '../utils/error.js'
28
import mozlog from '../utils/log.js'
29

30
const {
31
  FXA_SUBSCRIPTION_PLAN_ID,
32
  FXA_SUBSCRIPTION_PRODUCT_ID,
33
  FXA_SUBSCRIPTION_URL,
34
  SERVER_URL
35
} = AppConstants
×
36

37
const log = mozlog('controllers.auth')
×
38

39
function init (req, res, next, client = FxAOAuthClient) {
×
40
  // Set a random state string in a cookie so that we can verify
41
  // the user when they're redirected back to us after auth.
42
  const state = randomBytes(40).toString('hex')
×
43
  req.session.state = state
×
44
  const url = new URL(client.code.getUri({ state }))
×
45
  const fxaParams = new URL(req.url, SERVER_URL)
×
46

47
  req.session.utmContents = {}
×
48
  url.searchParams.append('prompt', 'login')
×
49
  url.searchParams.append('max_age', 0)
×
50
  url.searchParams.append('access_type', 'offline')
×
51
  url.searchParams.append('action', 'email')
×
52

53
  for (const param of fxaParams.searchParams.keys()) {
×
54
    url.searchParams.append(param, fxaParams.searchParams.get(param))
×
55
  }
56

57
  res.redirect(url)
×
58
}
59

60
async function confirmed (req, res, next, client = FxAOAuthClient) {
×
61
  if (!req.session.state) {
×
62
    log.error('oauth-invalid-session', 'req.session.state missing')
×
63
    throw new UnauthorizedError(getMessage('oauth-invalid-session'))
×
64
  }
65

66
  if (req.session.state !== req.query.state) {
×
67
    log.error('oauth-invalid-session', 'req.session does not match req.query')
×
68
    throw new UnauthorizedError(getMessage('oauth-invalid-session'))
×
69
  }
70

71
  const fxaUser = await client.code.getToken(req.originalUrl, {
×
72
    state: req.session.state
73
  })
74
  // Clear the session.state to clean up and avoid any replays
75
  req.session.state = null
×
76
  log.debug('fxa-confirmed-fxaUser', fxaUser)
×
77
  const fxaProfileData = await getProfileData(fxaUser.accessToken)
×
78
  log.debug('fxa-confirmed-profile-data', fxaProfileData)
×
79
  const email = JSON.parse(fxaProfileData).email
×
80

81
  const existingUser = await getSubscriberByEmail(email)
×
82
  req.session.user = existingUser
×
83

84
  const returnURL = new URL('user/breaches', SERVER_URL)
×
85
  const originalURL = new URL(req.originalUrl, SERVER_URL)
×
86

87
  for (const [key, value] of originalURL.searchParams.entries()) {
×
88
    if (key.startsWith('utm_')) returnURL.searchParams.append(key, value)
×
89
  }
90

91
  // Check if user is signing up or signing in,
92
  // then add new users to db and send email.
93
  if (!existingUser) {
×
94
    // req.session.newUser determines whether or not we show `fxa_new_user_bar`
95
    // in template
96
    req.session.newUser = true
×
97
    const signupLanguage = req.locale
×
98
    const verifiedSubscriber = await addSubscriber(
×
99
      email,
100
      signupLanguage,
101
      fxaUser.accessToken,
102
      fxaUser.refreshToken,
103
      fxaProfileData
104
    )
105

106
    // Get breaches for email the user signed-up with
107
    const allBreaches = req.app.locals.breaches
×
108
    const unsafeBreachesForEmail = await getBreachesForEmail(
×
109
      getSha1(email),
110
      allBreaches,
111
      true
112
    )
113

114
    // Send report email
115
    const utmCampaignId = 'report'
×
116
    const subject = unsafeBreachesForEmail?.length
×
117
      ? getMessage('email-subject-found-breaches')
118
      : getMessage('email-subject-no-breaches')
119

120
    const data = {
×
121
      breachedEmail: email,
122
      breachLogos: req.app.locals.breachLogoMap,
123
      ctaHref: getEmailCtaHref(utmCampaignId, 'dashboard-cta'),
124
      heading: getMessage('email-breach-summary'),
125
      recipientEmail: email,
126
      subscriberId: verifiedSubscriber,
127
      unsafeBreachesForEmail,
128
      utmCampaign: utmCampaignId
129
    }
130
    const emailTemplate = getTemplate(data, signupReportEmailPartial)
×
131

132
    await sendEmail(data.recipientEmail, subject, emailTemplate)
×
133

134
    req.session.user = verifiedSubscriber
×
135

136
    return res.redirect(returnURL.pathname + returnURL.search)
×
137
  }
138
  // Update existing user's FxA data
139
  const { accessToken, refreshToken } = fxaUser
×
140
  await updateFxAData(existingUser, accessToken, refreshToken, fxaProfileData)
×
141

142
  res.redirect(returnURL.pathname + returnURL.search)
×
143
}
144

145
/**
146
 * Controller to trigger a logout for user
147
 *
148
 * @param {object} req Contains session.user
149
 * @param {object} res Redirects to homepage
150
 */
151
async function logout (req, res) {
152
  const subscriber = req.session?.user
×
153
  log.info('logout', subscriber?.primary_email)
×
154

155
  // delete oauth session info in database
156
  await removeFxAData(subscriber)
×
157

158
  // clear session cache
159
  req.session.destroy(s => {
×
160
    delete req.session
×
161
    res.redirect('/')
×
162
  })
163
}
164

165
/**
166
 * Controller that initiates the premium upgrade flow.
167
 *
168
 * Redirects to subplat. If the user is already subscribed, they are redirected
169
 * back to the dashboard.
170
 *
171
 * @param {object} req The express request object
172
 * @param {object} res The express response object
173
 */
174
async function premiumUpgrade (req, res) {
175
  if (
×
176
    isSubscribed(req.user.fxa_profile_json)) {
177
    return res.redirect('/user/breaches')
×
178
  }
179

180
  const subscribeUrl = `${FXA_SUBSCRIPTION_URL}/${FXA_SUBSCRIPTION_PRODUCT_ID}?plan=${FXA_SUBSCRIPTION_PLAN_ID}`
×
181

182
  res.redirect(subscribeUrl)
×
183
}
184

185
/**
186
 * Controller that completes the premium upgrade flow.
187
 *
188
 * Pulls down updated profile data from FxA (which should now contain a
189
 * subscription) and redirects the user back to the dashboard.
190
 *
191
 * @param {object} req The express request object
192
 * @param {object} res The express response object
193
 */
194
async function premiumConfirmed (req, res) {
195
  const fxaProfileData = JSON.parse(await getProfileData(req.user.fxa_access_token))
×
196

197
  if (req.query.email !== fxaProfileData.email) {
×
198
    throw new Error('Email address returned by FxA does not match profile')
×
199
  }
200

201
  await updateFxAProfileData(req.user, fxaProfileData)
×
202

203
  if (!isSubscribed(fxaProfileData)) {
×
204
    throw new Error('Cannot find subscription from FxA')
×
205
  }
206

207
  res.redirect('/user/breaches')
×
208
}
209

210
export { init, confirmed, logout, premiumUpgrade, premiumConfirmed }
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