-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
71 lines (61 loc) · 1.96 KB
/
index.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
/* global emit */ // couchdb globals
/**
* Users plugin
* Manages accounts and user dbs
*/
var _ = require('lodash')
var async = require('async')
/**
* Adds a database to the pool of task event sources
* Makes sure it only happens once per database
* Maybe move the dedupe logic to hoodie-plugins-manager
*/
module.exports = function (hoodie, callback) {
var userChange = _.partial(require('./lib/user-change'), hoodie)
hoodie.account.on('user:change', userChange)
hoodie.account.on('user_anonymous:change', userChange)
hoodie.account.on('$passwordReset:change', _.partial(require('./lib/password-reset'), hoodie))
async.series([
async.apply(exports.createIndex, hoodie, 'by-name', 'name'),
async.apply(exports.createIndex, hoodie, 'by-created-at', 'doc.createdAt')
], function (err) {
if (err) return callback(err)
/**
* Loops through all user accounts and runs them through
* the new user procedure. For most users that will mean
* that their user database will be added as a listener
* to the event system.
*/
// bootstrap existing users
hoodie.account.findAll(function (error, accounts) {
if (error) {
console.log('hoodie-plugin-users: can’t bootstrap existing accounts')
return callback(error)
}
accounts.forEach(userChange)
callback()
})
})
}
exports.createIndex = function (hoodie, name, toEmit, callback) {
var usersDb = hoodie.database('_users')
var mapReduce = {
map: function (doc) {
var name = doc.name.split('/')[1]
var state
if (doc.roles.indexOf('error') !== -1) {
state = 'error'
} else {
state = doc.roles.indexOf('confirmed') === -1 ? 'unconfirmed' : 'confirmed'
}
var result = {
id: doc.id,
name: name,
createdAt: doc.createdAt,
state: state
}
emit(toEmit, result)
}.toString().replace('toEmit', toEmit)
}
usersDb.addIndex(name, mapReduce, callback)
}