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

mozilla / blurts-server / #13280

pending completion
#13280

push

circleci

jswinarton
more

282 of 1635 branches covered (17.25%)

Branch coverage included in aggregate %.

10 of 10 new or added lines in 2 files covered. (100.0%)

959 of 4395 relevant lines covered (21.82%)

1.82 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 '../app-constants.js'
9
import {
10
  getSubscriberByEmail,
11
  removeFxAData,
12
  updateFxAData
13
} from '../db/tables/subscribers.js'
14
import { addSubscriber } from '../db/tables/email_addresses.js'
15

16
import { getTemplate } from '../views/emails/email-2022.js'
17
import {
18
  signupReportEmailPartial
19
} from '../views/emails/email-signup-report.js'
20

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

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

37

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

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

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

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

58
  res.redirect(url)
×
59
}
60

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

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

72
  const fxaUser = await client.code.getToken(req.originalUrl, {
×
73
    state: req.session.state
74
  })
75
  // Clear the session.state to clean up and avoid any replays
76
  req.session.state = null
×
77
  log.debug('fxa-confirmed-fxaUser', fxaUser)
×
78

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
 * TODO docstring
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 (!FXA_SUBSCRIPTION_ENABLED) {
×
176
    res.sendStatus(404);
×
177
  }
178

179
  if (
×
180
    isSubscribed(req.user)) {
181
    res.redirect("/user/breaches")
×
182
  }
183

184
  const subscribeUrl = `${FXA_SUBSCRIPTION_URL}/${FXA_SUBSCRIPTION_PRODUCT_ID}?plan=${FXA_SUBSCRIPTION_PLAN_ID}`
×
185
  console.log(subscribeUrl)
×
186

187
  res.redirect(subscribeUrl)
×
188
}
189

190
/**
191
 * TODO docstring
192
 *
193
 * @param {object} req The express request object
194
 * @param {object} res The express response object
195
 */
196
async function premiumConfirmed (_req, res) {
197
  if (!FXA_SUBSCRIPTION_ENABLED) {
×
198
    res.sendStatus(404);
×
199
  }
200

201
  // TODO confirm that the subscription now exists on the FxA user and update
202
  // the database
203
  res.redirect("/user/breaches")
×
204
}
205

206
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