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

mozilla / blurts-server / #13299

pending completion
#13299

push

circleci

jswinarton
more

282 of 1691 branches covered (16.68%)

Branch coverage included in aggregate %.

11 of 11 new or added lines in 3 files covered. (100.0%)

959 of 4570 relevant lines covered (20.98%)

1.75 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_ENABLED,
32
  FXA_SUBSCRIPTION_PLAN_ID,
33
  FXA_SUBSCRIPTION_PRODUCT_ID,
34
  FXA_SUBSCRIPTION_URL,
35
  SERVER_URL
36
} = AppConstants
×
37

38

39
const log = mozlog('controllers.auth')
×
40

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

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

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

59
  res.redirect(url)
×
60
}
61

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

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

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

83
  const existingUser = await getSubscriberByEmail(email)
×
84
  req.session.user = existingUser
×
85

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

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

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

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

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

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

134
    await sendEmail(data.recipientEmail, subject, emailTemplate)
×
135

136
    req.session.user = verifiedSubscriber
×
137

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

144
  res.redirect(returnURL.pathname + returnURL.search)
×
145
}
146

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

157
  // delete oauth session info in database
158
  await removeFxAData(subscriber)
×
159

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

167

168
/**
169
 * Controller that initiates the premium upgrade flow.
170
 *
171
 * Redirects to subplat. If the user is already subscribed, they are redirected
172
 * back to the dashboard.
173
 *
174
 * @param {object} req The express request object
175
 * @param {object} res The express response object
176
 */
177
async function premiumUpgrade (req, res) {
178
  if (!FXA_SUBSCRIPTION_ENABLED) {
×
179
    return res.sendStatus(404)
×
180
  }
181

182
  if (
×
183
    isSubscribed(req.user.fxa_profile_json)) {
184
    return res.redirect("/user/breaches")
×
185
  }
186

187
  const subscribeUrl = `${FXA_SUBSCRIPTION_URL}/${FXA_SUBSCRIPTION_PRODUCT_ID}?plan=${FXA_SUBSCRIPTION_PLAN_ID}`
×
188
  console.log(subscribeUrl)
×
189

190
  res.redirect(subscribeUrl)
×
191
}
192

193
/**
194
 * Controller that completes the premium upgrade flow.
195
 *
196
 * TODO add a more complete description of what is happening here
197
 *
198
 * @param {object} req The express request object
199
 * @param {object} res The express response object
200
 */
201
async function premiumConfirmed (req, res) {
202
  if (!FXA_SUBSCRIPTION_ENABLED) {
×
203
    return res.sendStatus(404)
×
204
  }
205

206
  // TODO check that the logged in user is the same as the email in the
207
  // queryparam?
208
  const fxaProfileData = await getProfileData(req.user.fxa_access_token)
×
209
  await updateFxAProfileData(user, fxaProfileData)
×
210

211
  res.redirect("/user/breaches")
×
212
}
213

214
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