summaryrefslogtreecommitdiffstats
path: root/browser/extensions/screenshots/background/auth.js
blob: f6cfd0f9aaced05d726847dd056e20764b71a35f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/* globals log */
/* globals main, makeUuid, deviceInfo, analytics, catcher, buildSettings, communication */

"use strict";

this.auth = (function() {
  const exports = {};

  let registrationInfo;
  let initialized = false;
  let authHeader = null;
  let sentryPublicDSN = null;
  let abTests = {};
  let accountId = null;

  const fetchStoredInfo = catcher.watchPromise(
    browser.storage.local.get(["registrationInfo", "abTests"]).then((result) => {
      if (result.abTests) {
        abTests = result.abTests;
      }
      if (result.registrationInfo) {
        registrationInfo = result.registrationInfo;
      }
  }));

  function getRegistrationInfo() {
    if (!registrationInfo) {
      registrationInfo = generateRegistrationInfo();
      log.info("Generating new device authentication ID", registrationInfo);
      browser.storage.local.set({registrationInfo});
    }
    return registrationInfo;
  }

  exports.getDeviceId = function() {
    return registrationInfo && registrationInfo.deviceId;
  };

  function generateRegistrationInfo() {
    const info = {
      deviceId: `anon${makeUuid()}`,
      secret: makeUuid(),
      registered: false,
    };
    return info;
  }

  function register() {
    return new Promise((resolve, reject) => {
      const registerUrl = main.getBackend() + "/api/register";
      // TODO: replace xhr with Fetch #2261
      const req = new XMLHttpRequest();
      req.open("POST", registerUrl);
      req.setRequestHeader("content-type", "application/json");
      req.onload = catcher.watchFunction(() => {
        if (req.status === 200) {
          log.info("Registered login");
          initialized = true;
          saveAuthInfo(JSON.parse(req.responseText));
          resolve(true);
          analytics.sendEvent("registered");
        } else {
          analytics.sendEvent("register-failed", `bad-response-${req.status}`);
          log.warn("Error in response:", req.responseText);
          const exc = new Error("Bad response: " + req.status);
          exc.popupMessage = "LOGIN_ERROR";
          reject(exc);
        }
      });
      req.onerror = catcher.watchFunction(() => {
        analytics.sendEvent("register-failed", "connection-error");
        const exc = new Error("Error contacting server");
        exc.popupMessage = "LOGIN_CONNECTION_ERROR";
        reject(exc);
      });
      req.send(JSON.stringify({
        deviceId: registrationInfo.deviceId,
        secret: registrationInfo.secret,
        deviceInfo: JSON.stringify(deviceInfo()),
      }));
    });
  }

  function login(options) {
    const { ownershipCheck, noRegister } = options || {};
    return new Promise((resolve, reject) => {
      return fetchStoredInfo.then(() => {
        const registrationInfo = getRegistrationInfo();
        const loginUrl = main.getBackend() + "/api/login";
        // TODO: replace xhr with Fetch #2261
        const req = new XMLHttpRequest();
        req.open("POST", loginUrl);
        req.onload = catcher.watchFunction(() => {
          if (req.status === 404) {
            if (noRegister) {
              resolve(false);
            } else {
              resolve(register());
            }
          } else if (req.status >= 300) {
            log.warn("Error in response:", req.responseText);
            const exc = new Error("Could not log in: " + req.status);
            exc.popupMessage = "LOGIN_ERROR";
            analytics.sendEvent("login-failed", `bad-response-${req.status}`);
            reject(exc);
          } else if (req.status === 0) {
            const error = new Error("Could not log in, server unavailable");
            error.popupMessage = "LOGIN_CONNECTION_ERROR";
            analytics.sendEvent("login-failed", "connection-error");
            reject(error);
          } else {
            initialized = true;
            const jsonResponse = JSON.parse(req.responseText);
            log.info("Screenshots logged in");
            analytics.sendEvent("login");
            saveAuthInfo(jsonResponse);
            if (ownershipCheck) {
              resolve({isOwner: jsonResponse.isOwner});
            } else {
              resolve(true);
            }
          }
        });
        req.onerror = catcher.watchFunction(() => {
          analytics.sendEvent("login-failed", "connection-error");
          const exc = new Error("Connection failed");
          exc.url = loginUrl;
          exc.popupMessage = "CONNECTION_ERROR";
          reject(exc);
        });
        req.setRequestHeader("content-type", "application/json");
        req.send(JSON.stringify({
          deviceId: registrationInfo.deviceId,
          secret: registrationInfo.secret,
          deviceInfo: JSON.stringify(deviceInfo()),
          ownershipCheck,
        }));
      });
    });
  }

  function saveAuthInfo(responseJson) {
    accountId = responseJson.accountId;
    if (responseJson.sentryPublicDSN) {
      sentryPublicDSN = responseJson.sentryPublicDSN;
    }
    if (responseJson.authHeader) {
      authHeader = responseJson.authHeader;
      if (!registrationInfo.registered) {
        registrationInfo.registered = true;
        catcher.watchPromise(browser.storage.local.set({registrationInfo}));
      }
    }
    if (responseJson.abTests) {
      abTests = responseJson.abTests;
      catcher.watchPromise(browser.storage.local.set({abTests}));
    }
  }

  exports.maybeLogin = function() {
    if (!registrationInfo) {
      return Promise.resolve();
    }

    return exports.authHeaders();
  };

  exports.authHeaders = function() {
    let initPromise = Promise.resolve();
    if (!initialized) {
      initPromise = login();
    }
    return initPromise.then(() => {
      if (authHeader) {
        return {"x-screenshots-auth": authHeader};
      }
      log.warn("No auth header available");
      return {};
    });
  };

  exports.getSentryPublicDSN = function() {
    return sentryPublicDSN || buildSettings.defaultSentryDsn;
  };

  exports.getAbTests = function() {
    return abTests;
  };

  exports.isRegistered = function() {
    return registrationInfo && registrationInfo.registered;
  };

  communication.register("getAuthInfo", (sender, ownershipCheck) => {
    return fetchStoredInfo.then(() => {
      // If a device id was never generated, report back accordingly.
      if (!registrationInfo) {
        return null;
      }

      return exports.authHeaders().then((authHeaders) => {
        let info = registrationInfo;
        if (info.registered) {
          return login({ownershipCheck}).then((result) => {
            return {
              isOwner: result && result.isOwner,
              deviceId: registrationInfo.deviceId,
              accountId,
              authHeaders,
            };
          });
        }
        info = Object.assign({authHeaders}, info);
        return info;
      });
  });
});

  return exports;
})();