-
Notifications
You must be signed in to change notification settings - Fork 303
/
account-manager.js
604 lines (536 loc) · 17.2 KB
/
account-manager.js
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
593
594
595
596
597
598
599
600
601
602
603
604
'use strict'
/* eslint-disable node/no-deprecated-api */
const url = require('url')
const rdf = require('rdflib')
const ns = require('solid-namespace')(rdf)
const defaults = require('../../config/defaults')
const UserAccount = require('./user-account')
const AccountTemplate = require('./account-template')
const debug = require('./../debug').accounts
const DEFAULT_PROFILE_CONTENT_TYPE = 'text/turtle'
const DEFAULT_ADMIN_USERNAME = 'admin'
/**
* Manages account creation (determining whether accounts exist, creating
* directory structures for new accounts, saving credentials).
*
* @class AccountManager
*/
class AccountManager {
/**
* @constructor
* @param [options={}] {Object}
* @param [options.authMethod] {string} Primary authentication method (e.g. 'oidc')
* @param [options.emailService] {EmailService}
* @param [options.tokenService] {TokenService}
* @param [options.host] {SolidHost}
* @param [options.multiuser=false] {boolean} (argv.multiuser) Is the server running
* in multiuser mode (users can sign up for accounts) or single user
* (such as a personal website).
* @param [options.store] {LDP}
* @param [options.pathCard] {string}
* @param [options.suffixURI] {string}
* @param [options.accountTemplatePath] {string} Path to the account template
* directory (will be used as a template for default containers, etc, when
* creating new accounts).
*/
constructor (options = {}) {
if (!options.host) {
throw Error('AccountManager requires a host instance')
}
this.host = options.host
this.emailService = options.emailService
this.tokenService = options.tokenService
this.authMethod = options.authMethod || defaults.auth
this.multiuser = options.multiuser || false
this.store = options.store
this.pathCard = options.pathCard || 'profile/card'
this.suffixURI = options.suffixURI || '#me'
this.accountTemplatePath = options.accountTemplatePath || './default-templates/new-account/'
}
/**
* Factory method for new account manager creation. Usage:
*
* ```
* let options = { host, multiuser, store }
* let accountManager = AccountManager.from(options)
* ```
*
* @param [options={}] {Object} See the `constructor()` docstring.
*
* @return {AccountManager}
*/
static from (options) {
return new AccountManager(options)
}
/**
* Tests whether an account already exists for a given username.
* Usage:
*
* ```
* accountManager.accountExists('alice')
* .then(exists => {
* console.log('answer: ', exists)
* })
* ```
* @param accountName {string} Account username, e.g. 'alice'
*
* @return {Promise<boolean>}
*/
accountExists (accountName) {
let accountUri
let cardPath
try {
accountUri = this.accountUriFor(accountName)
accountUri = url.parse(accountUri).hostname
cardPath = url.resolve('/', this.pathCard)
} catch (err) {
return Promise.reject(err)
}
return this.accountUriExists(accountUri, cardPath)
}
/**
* Tests whether a given account URI (e.g. 'https://alice.example.com/')
* already exists on the server.
*
* @param accountUri {string}
* @param accountResource {string}
*
* @return {Promise<boolean>}
*/
async accountUriExists (accountUri, accountResource = '/') {
try {
return await this.store.exists(accountUri, accountResource)
} catch (err) {
return false
}
}
/**
* Constructs a directory path for a given account (used for account creation).
* Usage:
*
* ```
* // If solid-server was launched with '/accounts/' as the root directory
* // and serverUri: 'https://example.com'
*
* accountManager.accountDirFor('alice') // -> '/accounts/alice.example.com'
* ```
*
* @param accountName {string}
*
* @return {string}
*/
accountDirFor (accountName) {
const { hostname } = url.parse(this.accountUriFor(accountName))
return this.store.resourceMapper.resolveFilePath(hostname)
}
/**
* Composes an account URI for a given account name.
* Usage (given a host with serverUri of 'https://example.com'):
*
* ```
* // in multi user mode:
* acctMgr.accountUriFor('alice')
* // -> 'https://alice.example.com'
*
* // in single user mode:
* acctMgr.accountUriFor()
* // -> 'https://example.com'
* ```
*
* @param [accountName] {string}
*
* @throws {Error} If `this.host` has not been initialized with serverUri,
* or if in multiuser mode and accountName is not provided.
* @return {string}
*/
accountUriFor (accountName) {
const accountUri = this.multiuser
? this.host.accountUriFor(accountName)
: this.host.serverUri // single user mode
return accountUri
}
/**
* Composes a WebID (uri with hash fragment) for a given account name.
* Usage:
*
* ```
* // in multi user mode:
* acctMgr.accountWebIdFor('alice')
* // -> 'https://alice.example.com/profile/card#me'
*
* // in single user mode:
* acctMgr.accountWebIdFor()
* // -> 'https://example.com/profile/card#me'
* ```
*
* @param [accountName] {string}
*
* @throws {Error} via accountUriFor()
*
* @return {string|null}
*/
accountWebIdFor (accountName) {
const accountUri = this.accountUriFor(accountName)
const webIdUri = url.parse(url.resolve(accountUri, this.pathCard))
webIdUri.hash = this.suffixURI
return webIdUri.format()
}
/**
* Returns the root .acl URI for a given user account (the account recovery
* email is stored there).
*
* @param userAccount {UserAccount}
*
* @throws {Error} via accountUriFor()
*
* @return {string} Root .acl URI
*/
rootAclFor (userAccount) {
const accountUri = this.accountUriFor(userAccount.username)
return url.resolve(accountUri, this.store.suffixAcl)
}
/**
* Adds a newly generated WebID-TLS certificate to the user's profile graph.
*
* @param certificate {WebIdTlsCertificate}
* @param userAccount {UserAccount}
*
* @return {Promise<Graph>}
*/
addCertKeyToProfile (certificate, userAccount) {
if (!certificate) {
throw new TypeError('Cannot add empty certificate to user profile')
}
return this.getProfileGraphFor(userAccount)
.then(profileGraph => {
return this.addCertKeyToGraph(certificate, profileGraph)
})
.then(profileGraph => {
return this.saveProfileGraph(profileGraph, userAccount)
})
}
/**
* Returns a parsed WebID Profile graph for a given user account.
*
* @param userAccount {UserAccount}
* @param [contentType] {string} Content type of the profile to parse
*
* @throws {Error} If the user account's WebID is missing
* @throws {Error} HTTP 404 error (via `getGraph()`) if the profile resource
* is not found
*
* @return {Promise<Graph>}
*/
getProfileGraphFor (userAccount, contentType = DEFAULT_PROFILE_CONTENT_TYPE) {
const webId = userAccount.webId
if (!webId) {
const error = new Error('Cannot fetch profile graph, missing WebId URI')
error.status = 400
return Promise.reject(error)
}
const uri = userAccount.profileUri
return this.store.getGraph(uri, contentType)
.catch(error => {
error.message = `Error retrieving profile graph ${uri}: ` + error.message
throw error
})
}
/**
* Serializes and saves a given graph to the user's WebID Profile (and returns
* the original graph object, as it was before serialization).
*
* @param profileGraph {Graph}
* @param userAccount {UserAccount}
* @param [contentType] {string}
*
* @return {Promise<Graph>}
*/
saveProfileGraph (profileGraph, userAccount, contentType = DEFAULT_PROFILE_CONTENT_TYPE) {
const webId = userAccount.webId
if (!webId) {
const error = new Error('Cannot save profile graph, missing WebId URI')
error.status = 400
return Promise.reject(error)
}
const uri = userAccount.profileUri
return this.store.putGraph(profileGraph, uri, contentType)
}
/**
* Adds the certificate's Public Key related triples to a user's profile graph.
*
* @param certificate {WebIdTlsCertificate}
* @param graph {Graph} Parsed WebID Profile graph
*
* @return {Graph}
*/
addCertKeyToGraph (certificate, graph) {
const webId = rdf.namedNode(certificate.webId)
const key = rdf.namedNode(certificate.keyUri)
const timeCreated = rdf.literal(certificate.date.toISOString(), ns.xsd('dateTime'))
const modulus = rdf.literal(certificate.modulus, ns.xsd('hexBinary'))
const exponent = rdf.literal(certificate.exponent, ns.xsd('int'))
const title = rdf.literal('Created by solid-server')
const label = rdf.literal(certificate.commonName)
graph.add(webId, ns.cert('key'), key)
graph.add(key, ns.rdf('type'), ns.cert('RSAPublicKey'))
graph.add(key, ns.dct('title'), title)
graph.add(key, ns.rdfs('label'), label)
graph.add(key, ns.dct('created'), timeCreated)
graph.add(key, ns.cert('modulus'), modulus)
graph.add(key, ns.cert('exponent'), exponent)
return graph
}
/**
* Creates and returns a `UserAccount` instance from submitted user data
* (typically something like `req.body`, from a signup form).
*
* @param userData {Object} Options hashmap, like `req.body`.
* Either a `username` or a `webid` property is required.
*
* @param [userData.username] {string}
* @param [uesrData.webid] {string}
*
* @param [userData.email] {string}
* @param [userData.name] {string}
*
* @throws {Error} (via `accountWebIdFor()`) If in multiuser mode and no
* username passed
*
* @return {UserAccount}
*/
userAccountFrom (userData) {
const userConfig = {
username: userData.username,
email: userData.email,
name: userData.name,
externalWebId: userData.externalWebId,
localAccountId: userData.localAccountId,
webId: userData.webid || userData.webId || userData.externalWebId,
idp: this.host.serverUri
}
if (userConfig.username) {
userConfig.username = userConfig.username.toLowerCase()
}
try {
userConfig.webId = userConfig.webId || this.accountWebIdFor(userConfig.username)
} catch (err) {
if (err.message === 'Cannot construct uri for blank account name') {
throw new Error('Username or web id is required')
} else {
throw err
}
}
if (userConfig.username) {
if (userConfig.externalWebId && !userConfig.localAccountId) {
// External Web ID exists, derive the local account id from username
userConfig.localAccountId = this.accountWebIdFor(userConfig.username)
.split('//')[1] // drop the https://
}
} else { // no username - derive it from web id
if (userConfig.externalWebId) {
userConfig.username = userConfig.externalWebId
// TODO find oidcIssuer from externalWebId
// removed from idp https://github.com/solid/node-solid-server/pull/1566
} else {
userConfig.username = this.usernameFromWebId(userConfig.webId)
}
}
return UserAccount.from(userConfig)
}
usernameFromWebId (webId) {
if (!this.multiuser) {
return DEFAULT_ADMIN_USERNAME
}
const profileUrl = url.parse(webId)
const hostname = profileUrl.hostname
return hostname.split('.')[0]
}
/**
* Creates a user account storage folder (from a default account template).
*
* @param userAccount {UserAccount}
*
* @return {Promise}
*/
createAccountFor (userAccount) {
const template = AccountTemplate.for(userAccount)
const templatePath = this.accountTemplatePath
const accountDir = this.accountDirFor(userAccount.username)
debug(`Creating account folder for ${userAccount.webId} at ${accountDir}`)
return AccountTemplate.copyTemplateDir(templatePath, accountDir)
.then(() => {
return template.processAccount(accountDir)
})
}
/**
* Generates an expiring one-time-use token for password reset purposes
* (the user's Web ID is saved in the token service).
*
* @param userAccount {UserAccount}
*
* @return {string} Generated token
*/
generateResetToken (userAccount) {
return this.tokenService.generate('reset-password', { webId: userAccount.webId })
}
/**
* Generates an expiring one-time-use token for password reset purposes
* (the user's Web ID is saved in the token service).
*
* @param userAccount {UserAccount}
*
* @return {string} Generated token
*/
generateDeleteToken (userAccount) {
return this.tokenService.generate('delete-account', {
webId: userAccount.webId,
email: userAccount.email
})
}
/**
* Validates that a token exists and is not expired, and returns the saved
* token contents, or throws an error if invalid.
* Does not consume / clear the token.
*
* @param token {string}
*
* @throws {Error} If missing or invalid token
*
* @return {Object|false} Saved token data object if verified, false otherwise
*/
validateDeleteToken (token) {
const tokenValue = this.tokenService.verify('delete-account', token)
if (!tokenValue) {
throw new Error('Invalid or expired delete account token')
}
return tokenValue
}
/**
* Validates that a token exists and is not expired, and returns the saved
* token contents, or throws an error if invalid.
* Does not consume / clear the token.
*
* @param token {string}
*
* @throws {Error} If missing or invalid token
*
* @return {Object|false} Saved token data object if verified, false otherwise
*/
validateResetToken (token) {
const tokenValue = this.tokenService.verify('reset-password', token)
if (!tokenValue) {
throw new Error('Invalid or expired reset token')
}
return tokenValue
}
/**
* Returns a password reset URL (to be emailed to the user upon request)
*
* @param token {string} One-time-use expiring token, via the TokenService
* @param returnToUrl {string}
*
* @return {string}
*/
passwordResetUrl (token, returnToUrl) {
let resetUrl = url.resolve(this.host.serverUri,
`/account/password/change?token=${token}`)
if (returnToUrl) {
resetUrl += `&returnToUrl=${returnToUrl}`
}
return resetUrl
}
/**
* Returns a password reset URL (to be emailed to the user upon request)
*
* @param token {string} One-time-use expiring token, via the TokenService
* @param returnToUrl {string}
*
* @return {string}
*/
getAccountDeleteUrl (token) {
return url.resolve(this.host.serverUri, `/account/delete/confirm?token=${token}`)
}
/**
* Parses and returns an account recovery email stored in a user's root .acl
*
* @param userAccount {UserAccount}
*
* @return {Promise<string|undefined>}
*/
loadAccountRecoveryEmail (userAccount) {
return Promise.resolve()
.then(() => {
const rootAclUri = this.rootAclFor(userAccount)
return this.store.getGraph(rootAclUri)
})
.then(rootAclGraph => {
const matches = rootAclGraph.match(null, ns.acl('agent'))
let recoveryMailto = matches.find(agent => {
return agent.object.value.startsWith('mailto:')
})
if (recoveryMailto) {
recoveryMailto = recoveryMailto.object.value.replace('mailto:', '')
}
return recoveryMailto
})
}
verifyEmailDependencies (userAccount) {
if (!this.emailService) {
throw new Error('Email service is not set up')
}
if (userAccount && !userAccount.email) {
throw new Error('Account recovery email has not been provided')
}
}
sendDeleteAccountEmail (userAccount) {
return Promise.resolve()
.then(() => this.verifyEmailDependencies(userAccount))
.then(() => this.generateDeleteToken(userAccount))
.then(resetToken => {
const deleteUrl = this.getAccountDeleteUrl(resetToken)
const emailData = {
to: userAccount.email,
webId: userAccount.webId,
deleteUrl: deleteUrl
}
return this.emailService.sendWithTemplate('delete-account', emailData)
})
}
sendPasswordResetEmail (userAccount, returnToUrl) {
return Promise.resolve()
.then(() => this.verifyEmailDependencies(userAccount))
.then(() => this.generateResetToken(userAccount))
.then(resetToken => {
const resetUrl = this.passwordResetUrl(resetToken, returnToUrl)
const emailData = {
to: userAccount.email,
webId: userAccount.webId,
resetUrl
}
return this.emailService.sendWithTemplate('reset-password', emailData)
})
}
/**
* Sends a Welcome email (on new user signup).
*
* @param newUser {UserAccount}
* @param newUser.email {string}
* @param newUser.webId {string}
* @param newUser.name {string}
*
* @return {Promise}
*/
sendWelcomeEmail (newUser) {
const emailService = this.emailService
if (!emailService || !newUser.email) {
return Promise.resolve(null)
}
const emailData = {
to: newUser.email,
webid: newUser.webId,
name: newUser.displayName
}
return emailService.sendWithTemplate('welcome', emailData)
}
}
module.exports = AccountManager