summaryrefslogtreecommitdiffstats
path: root/services/sync/modules/userapi.js
blob: e906440bd1df2cab714196868835d581835c3093 (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/. */

"use strict";

this.EXPORTED_SYMBOLS = [
  "UserAPI10Client",
];

var {utils: Cu} = Components;

Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/rest.js");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/util.js");

/**
 * A generic client for the user API 1.0 service.
 *
 * http://docs.services.mozilla.com/reg/apis.html
 *
 * Instances are constructed with the base URI of the service.
 */
this.UserAPI10Client = function UserAPI10Client(baseURI) {
  this._log = Log.repository.getLogger("Sync.UserAPI");
  this._log.level = Log.Level[Svc.Prefs.get("log.logger.userapi")];

  this.baseURI = baseURI;
}
UserAPI10Client.prototype = {
  USER_CREATE_ERROR_CODES: {
    2: "Incorrect or missing captcha.",
    4: "User exists.",
    6: "JSON parse failure.",
    7: "Missing password field.",
    9: "Requested password not strong enough.",
    12: "No email address on file.",
  },

  /**
   * Determine whether a specified username exists.
   *
   * Callback receives the following arguments:
   *
   *   (Error) Describes error that occurred or null if request was
   *           successful.
   *   (boolean) True if user exists. False if not. null if there was an error.
   */
  usernameExists: function usernameExists(username, cb) {
    if (typeof(cb) != "function") {
      throw new Error("cb must be a function.");
    }

    let url = this.baseURI + username;
    let request = new RESTRequest(url);
    request.get(this._onUsername.bind(this, cb, request));
  },

  /**
   * Obtain the Weave (Sync) node for a specified user.
   *
   * The callback receives the following arguments:
   *
   *   (Error)  Describes error that occurred or null if request was successful.
   *   (string) Username request is for.
   *   (string) URL of user's node. If null and there is no error, no node could
   *            be assigned at the time of the request.
   */
  getWeaveNode: function getWeaveNode(username, password, cb) {
    if (typeof(cb) != "function") {
      throw new Error("cb must be a function.");
    }

    let request = this._getRequest(username, "/node/weave", password);
    request.get(this._onWeaveNode.bind(this, cb, request));
  },

  /**
   * Change a password for the specified user.
   *
   * @param username
   *        (string) The username whose password to change.
   * @param oldPassword
   *        (string) The old, current password.
   * @param newPassword
   *        (string) The new password to switch to.
   */
  changePassword: function changePassword(username, oldPassword, newPassword, cb) {
    let request = this._getRequest(username, "/password", oldPassword);
    request.onComplete = this._onChangePassword.bind(this, cb, request);
    request.post(CommonUtils.encodeUTF8(newPassword));
  },

  createAccount: function createAccount(email, password, captchaChallenge,
                                        captchaResponse, cb) {
    let username = IdentityManager.prototype.usernameFromAccount(email);
    let body = JSON.stringify({
      "email":             email,
      "password":          Utils.encodeUTF8(password),
      "captcha-challenge": captchaChallenge,
      "captcha-response":  captchaResponse
    });

    let url = this.baseURI + username;
    let request = new RESTRequest(url);

    if (this.adminSecret) {
      request.setHeader("X-Weave-Secret", this.adminSecret);
    }

    request.onComplete = this._onCreateAccount.bind(this, cb, request);
    request.put(body);
  },

  _getRequest: function _getRequest(username, path, password=null) {
    let url = this.baseURI + username + path;
    let request = new RESTRequest(url);

    if (password) {
      let up = username + ":" + password;
      request.setHeader("authorization", "Basic " + btoa(up));
    }

    return request;
  },

  _onUsername: function _onUsername(cb, request, error) {
    if (error) {
      cb(error, null);
      return;
    }

    let body = request.response.body;
    if (body == "0") {
      cb(null, false);
      return;
    } else if (body == "1") {
      cb(null, true);
      return;
    } else {
      cb(new Error("Unknown response from server: " + body), null);
      return;
    }
  },

  _onWeaveNode: function _onWeaveNode(cb, request, error) {
    if (error) {
      cb.network = true;
      cb(error, null);
      return;
    }

    let response = request.response;

    if (response.status == 200) {
      let body = response.body;
      if (body == "null") {
        cb(null, null);
        return;
      }

      cb(null, body);
      return;
    }

    error = new Error("Sync node retrieval failed.");
    switch (response.status) {
      case 400:
        error.denied = true;
        break;
      case 404:
        error.notFound = true;
        break;
      default:
        error.message = "Unexpected response code: " + response.status;
    }

    cb(error, null);
    return;
  },

  _onChangePassword: function _onChangePassword(cb, request, error) {
    this._log.info("Password change response received: " +
                   request.response.status);
    if (error) {
      cb(error);
      return;
    }

    let response = request.response;
    if (response.status != 200) {
      cb(new Error("Password changed failed: " + response.body));
      return;
    }

    cb(null);
  },

  _onCreateAccount: function _onCreateAccount(cb, request, error) {
    let response = request.response;

    this._log.info("Create account response: " + response.status + " " +
                   response.body);

    if (error) {
      cb(new Error("HTTP transport error."), null);
      return;
    }

    if (response.status == 200) {
      cb(null, response.body);
      return;
    }

    error = new Error("Could not create user.");
    error.body = response.body;

    cb(error, null);
    return;
  },
};
Object.freeze(UserAPI10Client.prototype);