summaryrefslogtreecommitdiffstats
path: root/etherpad/src/etherpad/pro/pro_accounts.js
blob: 98df6bb626b48d1f05c7c6295bcda7d9f8654553 (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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/**
 * Copyright 2009 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// library for pro accounts

import("funhtml.*");
import("sqlbase.sqlobj");
import("sqlbase.sqlcommon.inTransaction");
import("email.sendEmail");
import("cache_utils.syncedWithCache");
import("stringutils.*");

import("etherpad.globals.*");
import("etherpad.sessions");
import("etherpad.sessions.getSession");
import("etherpad.utils.*");
import("etherpad.pro.domains");
import("etherpad.control.pro.account_control");
import("etherpad.pro.pro_utils");
import("etherpad.pro.pro_ldap_support.*");
import("etherpad.pro.pro_quotas");
import("etherpad.pad.padusers");
import("etherpad.log");
import("etherpad.billing.team_billing");

import("process.*");
import("fastJSON")

jimport("org.mindrot.BCrypt");
jimport("java.lang.System.out.println");

function _dmesg(m) {
  if (!isProduction()) {
    println(m);
  }
}

function _computePasswordHash(p) {
  var pwh;
  pwh = BCrypt.hashpw(p, BCrypt.gensalt(10));
  return pwh;
}

function _withCache(name, fn) {
  return syncedWithCache('pro_accounts.'+name, fn);
}

//----------------------------------------------------------------
// validation
//----------------------------------------------------------------

function validateEmail(email) {
  if (!email) { return "Email is required."; }
  if (!isValidEmail(email)) { return "\""+email+"\" does not look like a valid email address."; }
  return null;
}

function validateFullName(name) {
  if (!name) { return "Full name is required."; }
  if (name.length < 2) { return "Full name must be at least 2 characters."; }
  return null;
}

function validatePassword(p) {
  if (!p) { return "Password is required."; }
  if (p.length < 6) { return "Passwords must be at least 6 characters."; }
  return null;
}

function validateEmailDomainPair(email, domainId) {
  // TODO: make sure the same email address cannot exist more than once within
  // the same domainid.
}

/* if domainId is null, then use domainId of current request. */
function createNewAccount(domainId, fullName, email, password, isAdmin, skipValidation) {
  if (!domainId) {
    domainId = domains.getRequestDomainId();
  }
  if (!skipValidation) {
    skipValidation = false;
  }
  email = trim(email);
  isAdmin = !!isAdmin; // convert to bool

  // validation
  if (!skipValidation) {
    var e;
    e = validateEmail(email); if (e) { throw Error(e); }
    e = validateFullName(fullName); if (e) { throw Error(e); }
    e = validatePassword(password); if (e) { throw Error(e); }
  }

  // xss normalization
  fullName = toHTML(fullName);

  // make sure account does not already exist on this domain.
  var ret = inTransaction(function() {
    var existingAccount = getAccountByEmail(email, domainId);
    if (existingAccount) {
      throw Error("There is already an account with that email address.");
    }
    // No existing account.  Proceed.
    var now = new Date();
    var account = {
      domainId: domainId,
      fullName: fullName,
      email: email,
      passwordHash: _computePasswordHash(password),
      createdDate: now,
      isAdmin: isAdmin
    };
    return sqlobj.insert('pro_accounts', account);
  });

  _withCache('does-domain-admin-exist', function(cache) {
    delete cache[domainId];
  });

  pro_quotas.updateAccountUsageCount(domainId);
  updateCachedActiveCount(domainId);

  if (ret) {
    log.custom('pro-accounts',
              {type: "account-created",
               accountId: ret,
               domainId: domainId,
               name: fullName,
               email: email,
               admin: isAdmin});
  }

  return ret;
}

function _checkAccess(account) {
  if (sessions.isAnEtherpadAdmin()) {
    return;
  }
  if (account.domainId != domains.getRequestDomainId()) {
    throw Error("access denied");
  }
}

function setPassword(account, newPass) {
  _checkAccess(account);
  var passHash = _computePasswordHash(newPass);
  sqlobj.update('pro_accounts', {id: account.id}, {passwordHash: passHash});
  markDirtySessionAccount(account.id);
}

function setTempPassword(account, tempPass) {
  _checkAccess(account);
  var tempPassHash = _computePasswordHash(tempPass);
  sqlobj.update('pro_accounts', {id: account.id}, {tempPassHash: tempPassHash});
  markDirtySessionAccount(account.id);
}

function setEmail(account, newEmail) {
  _checkAccess(account);
  sqlobj.update('pro_accounts', {id: account.id}, {email: newEmail});
  markDirtySessionAccount(account.id);
}

function setFullName(account, newName) {
  _checkAccess(account);
  sqlobj.update('pro_accounts', {id: account.id}, {fullName: newName});
  markDirtySessionAccount(account.id);
}

function setIsAdmin(account, newVal) {
  _checkAccess(account);
  sqlobj.update('pro_accounts', {id: account.id}, {isAdmin: newVal});
  markDirtySessionAccount(account.id);
}

function setDeleted(account) {
  _checkAccess(account);
  if (!isNumeric(account.id)) {
    throw new Error("Invalid account id: "+account.id);
  }
  sqlobj.update('pro_accounts', {id: account.id}, {isDeleted: true});
  markDirtySessionAccount(account.id);
  pro_quotas.updateAccountUsageCount(account.domainId);
  updateCachedActiveCount(account.domainId);

  log.custom('pro-accounts',
             {type: "account-deleted",
              accountId: account.id,
              domainId: account.domainId,
              name: account.fullName,
              email: account.email,
              admin: account.isAdmin,
              createdDate: account.createdDate.getTime()});
}

//----------------------------------------------------------------

function doesAdminExist() {
  var domainId = domains.getRequestDomainId();
  return _withCache('does-domain-admin-exist', function(cache) {
    if (cache[domainId] === undefined) {
      _dmesg("cache miss for doesAdminExist (domainId="+domainId+")");
      var admins = sqlobj.selectMulti('pro_accounts', {domainId: domainId, isAdmin: true}, {});
      cache[domainId] = (admins.length > 0);
    }
    return cache[domainId]
  });
}

function attemptSingleSignOn() {
  if(!appjet.config['etherpad.SSOScript']) return null;
  
  // pass request.cookies to a small user script
  var file = appjet.config['etherpad.SSOScript'];
      
  var cmd = exec(file);
  
  // note that this will block until script execution returns
  var result = cmd.write(fastJSON.stringify(request.cookies)).result();
  var val = false;
  
  // we try to parse the result as a JSON string, if not, return null.
  try {
    if(!!(val=fastJSON.parse(result))) {
      return val;
    }
  } catch(e) {}
  return null;
}

function getSessionProAccount() {
  if (sessions.isAnEtherpadAdmin()) {
    return getEtherpadAdminAccount();
  }
  var account = getSession().proAccount;
  if (!account) {
    return null;
  }
  if (account.isDeleted) {
    delete getSession().proAccount;
    return null;
  }
  return account;
}

function isAccountSignedIn() {
  if (getSessionProAccount()) {
    return true;
  } else {
    // if the user is not signed in, check to see if he should be signed in
    // by calling an external script.
    if(appjet.config['etherpad.SSOScript']) {
      var ssoResult = attemptSingleSignOn();
      if(ssoResult && ('email' in ssoResult)) {
        var user = getAccountByEmail(ssoResult['email']);
        if (!user) {
          var email = ssoResult['email'];
          var pass = ssoResult['password'] || "";
          var name = ssoResult['fullname'] || "unnamed";
          createNewAccount(null, name, email, pass, false, true);
          user = getAccountByEmail(email, null);
        }
        
        signInSession(user);
        return true;
      }
    }
    
    return false;
  }
}

function isAdminSignedIn() {
  return isAccountSignedIn() && getSessionProAccount().isAdmin;
}

function requireAccount(message) {
  if ((request.path == "/ep/account/sign-in") ||
      (request.path == "/ep/account/sign-out") ||
      (request.path == "/ep/account/guest-sign-in") ||
      (request.path == "/ep/account/guest-knock") ||
      (request.path == "/ep/account/forgot-password")) {
    return;
  }

  function checkSessionAccount() {
    if (!getSessionProAccount()) {
      if (message) {
        account_control.setSigninNotice(message);
      }
      response.redirect('/ep/account/sign-in?cont='+encodeURIComponent(request.url));
    }
  }

  checkSessionAccount();

  if (getSessionProAccount().domainId != domains.getRequestDomainId()) {
    // This should theoretically never happen unless the account is spoofing cookies / trying to
    // hack the site.
    pro_utils.renderFramedMessage("Permission denied.");
    response.stop();
  }
  // update dirty session account if necessary
  _withCache('dirty-session-accounts', function(cache) {
    var uid = getSessionProAccount().id;
    if (cache[uid]) {
      reloadSessionAccountData(uid);
      cache[uid] = false;
    }
  });

  // need to check again in case dirty update caused account to be marked
  // deleted.
  checkSessionAccount();
}

function requireAdminAccount() {
  requireAccount();
  if (!getSessionProAccount().isAdmin) {
    pro_utils.renderFramedMessage("Permission denied.");
    response.stop();
  }
}

/* returns undefined on success, error string otherise. */
function authenticateSignIn(email, password) {
  // blank passwords are not allowed to sign in.
  if (password == "") return "Please provide a password.";
  
  // If the email ends with our ldap suffix...
  var isLdapSuffix = getLDAP() && getLDAP().isLDAPSuffix(email);

  if(isLdapSuffix && !getLDAP()) {
    return "LDAP not yet configured. Please contact your system admininstrator.";
  }
  
  // if there is an error in the LDAP configuration, return the error message
  if(getLDAP() && getLDAP().error) {
    return getLDAP().error + " Please contact your system administrator.";
  }
  
  if(isLdapSuffix && getLDAP()) {
    var ldapuser = email.substr(0, email.indexOf(getLDAP().getLDAPSuffix()));
    var ldapResult = getLDAP().login(ldapuser, password);

    if (ldapResult.error == true) {
      return ldapResult.message + "";
    }

    var accountRecord = getAccountByEmail(email, null);

    // if this is the first time this user has logged in, create a user
    // for him/her
    if (!accountRecord) {
      // password to store in database -- a blank password means the user
      // cannot authenticate normally (e.g. must go through SSO or LDAP)
      var ldapPass = "";
      
      // create a new user (skipping validation of email/users/passes)
      createNewAccount(null, ldapResult.getFullName(), email, ldapPass, false, true);
      accountRecord = getAccountByEmail(email, null);
    }
    
    signInSession(accountRecord);
    return undefined; // success
  }
  
  var accountRecord = getAccountByEmail(email, null);
  if (!accountRecord) {
    return "Account not found: "+email;
  }

  if (BCrypt.checkpw(password, accountRecord.passwordHash) != true) {
    return "Incorrect password.  Please try again.";
  }

  signInSession(accountRecord);

  return undefined; // success
}

function signOut() {
  delete getSession().proAccount;
}

function authenticateTempSignIn(uid, tempPass) {
  var emsg = "That password reset link that is no longer valid.";

  var account = getAccountById(uid);
  if (!account) {
    return emsg+" (Account not found.)";
  }
  if (account.domainId != domains.getRequestDomainId()) {
    return emsg+" (Wrong domain.)";
  }
  if (!account.tempPassHash) {
    return emsg+" (Expired.)";
  }
  if (BCrypt.checkpw(tempPass, account.tempPassHash) != true) {
    return emsg+" (Bad temp pass.)";
  }

  signInSession(account);

  getSession().accountMessage = "Please choose a new password";
  getSession().changePass = true;

  response.redirect("/ep/account/");
}

function signInSession(account) {
  account.lastLoginDate = new Date();
  account.tempPassHash = null;
  sqlobj.updateSingle('pro_accounts', {id: account.id}, account);
  reloadSessionAccountData(account.id);
  padusers.notifySignIn();
}

function listAllDomainAccounts(domainId) {
  if (domainId === undefined) {
    domainId = domains.getRequestDomainId();
  }
  var records = sqlobj.selectMulti('pro_accounts',
    {domainId: domainId, isDeleted: false}, {});
  return records;
}

function listAllDomainAdmins(domainId) {
  if (domainId === undefined) {
    domainId = domains.getRequestDomainId();
  }
  var records = sqlobj.selectMulti('pro_accounts',
    {domainId: domainId, isDeleted: false, isAdmin: true},
    {});
  return records;
}

function getActiveCount(domainId) {
  var records = sqlobj.selectMulti('pro_accounts',
    {domainId: domainId, isDeleted: false}, {});
  return records.length;
}

/* getAccountById works for deleted and non-deleted accounts.
 * The assumption is that cases whewre you look up an account by ID, you
 * want the account info even if the account has been deleted.  For
 * example, when asking who created a pad.
 */
function getAccountById(accountId) {
  var r = sqlobj.selectSingle('pro_accounts', {id: accountId});
  if (r) {
    return r;
  } else {
    return undefined;
  }
}

/* getting an account by email only returns the account if it is
 * not deleted.  The assumption is that when you look up an account by
 * email address, you only want active accounts.  Furthermore, some
 * deleted accounts may match a given email, but only one non-deleted
 * account should ever match a single (email,domainId) pair.
 */
function getAccountByEmail(email, domainId) {
  if (!domainId) {
    domainId = domains.getRequestDomainId();
  }
  var r = sqlobj.selectSingle('pro_accounts', {domainId: domainId, email: email, isDeleted: false});
  if (r) {
    return r;
  } else {
    return undefined;
  }
}

function getFullNameById(id) {
  if (!id) {
    return null;
  }

  return _withCache('names-by-id', function(cache) {
    if (cache[id] === undefined) {
      _dmesg("cache miss for getFullNameById (accountId="+id+")");
      var r = getAccountById(id);
      if (r) {
        cache[id] = r.fullName;
      } else {
        cache[id] = false;
      }
    }
    if (cache[id]) {
      return cache[id];
    } else {
      return null;
    }
  });
}

function getTempSigninUrl(account, tempPass) {
  if(appjet.config.listenSecurePort != 0 || appjet.config.useHttpsUrls)
    return [
      'https://', httpsHost(pro_utils.getFullProHost()), '/ep/account/sign-in?',
      'uid=', account.id, '&tp=', tempPass
    ].join('');
  else
    return [
      'http://', httpHost(pro_utils.getFullProHost()), '/ep/account/sign-in?',
      'uid=', account.id, '&tp=', tempPass
    ].join('');
}


// TODO: this session account object storage / dirty cache is a
// ridiculous hack.  What we should really do is have a caching/access
// layer for accounts similar to accessPad() and accessProPadMeta(), and
// have that abstraction take care of caching and marking accounts as
// dirty.  This can be incorporated into getSessionProAccount(), and we
// should actually refactor that into accessSessionProAccount().

/* will force session data for this account to be updated next time that
 * account requests a page. */
function markDirtySessionAccount(uid) {
  var domainId = domains.getRequestDomainId();

  _withCache('dirty-session-accounts', function(cache) {
    cache[uid] = true;
  });
  _withCache('names-by-id', function(cache) {
    delete cache[uid];
  });
  _withCache('does-domain-admin-exist', function(cache) {
    delete cache[domainId];
  });
}

function reloadSessionAccountData(uid) {
  if (!uid) {
    uid = getSessionProAccount().id;
  }
  getSession().proAccount = getAccountById(uid);
}

function getAllAccountsWithEmail(email) {
  var accountRecords = sqlobj.selectMulti('pro_accounts', {email: email, isDeleted: false}, {});
  return accountRecords;
}

function getEtherpadAdminAccount() {
  return {
    id: 0,
    isAdmin: true,
    fullName: "ETHERPAD ADMIN",
    email: "support@pad.spline.inf.fu-berlin.de",
    domainId: domains.getRequestDomainId(),
    isDeleted: false
  };
}

function getCachedActiveCount(domainId) {
  return _withCache('user-counts.'+domainId, function(c) {
    if (!c.count) {
      c.count = getActiveCount(domainId);
    }
    return c.count;
  });
}

function updateCachedActiveCount(domainId) {
  _withCache('user-counts.'+domainId, function(c) {
    c.count = getActiveCount(domainId);
  });
}