UNPKG

2.31 kBJavaScriptView Raw
1var passwordHash = require('password-hash')
2var shortid = require('shortid')
3var Promise = require('bluebird')
4
5function UsersRepository (reporter) {
6 var self = this
7 this.reporter = reporter
8
9 this.UserType = this.reporter.documentStore.registerEntityType('UserType', {
10 _id: {type: 'Edm.String', key: true},
11 shortid: {type: 'Edm.String'},
12 username: {type: 'Edm.String'},
13 password: {type: 'Edm.String'}
14 })
15
16 this.reporter.documentStore.registerEntitySet('users', {entityType: 'jsreport.UserType', humanReadableKey: 'shortid'})
17
18 this.reporter.initializeListeners.add('repository', function () {
19 var col = self.usersCollection = self.reporter.documentStore.collection('users')
20 col.beforeInsertListeners.add('users', function (doc) {
21 if (!doc.shortid) {
22 doc.shortid = shortid.generate()
23 }
24
25 delete doc.passwordVerification
26 doc.password = passwordHash.generate(doc.password)
27
28 return self.validate(doc)
29 })
30 })
31}
32
33UsersRepository.prototype.validate = function (user) {
34 return this.find(user.username).then(function (user) {
35 if (user) {
36 return Promise.reject(new Error('User already exists'))
37 }
38
39 return true
40 })
41}
42
43UsersRepository.prototype.authenticate = function (username, password) {
44 return this.usersCollection.find({username: username}).then(function (users) {
45 if (users.length !== 1 || !passwordHash.verify(password, users[0].password)) {
46 return null
47 }
48 return users[0]
49 })
50}
51
52UsersRepository.prototype.find = function (username) {
53 return this.usersCollection.find({username: username}).then(function (users) {
54 if (users.length !== 1) {
55 return null
56 }
57
58 return users[0]
59 })
60}
61
62UsersRepository.prototype.changePassword = function (currentUser, shortid, oldPassword, newPassword) {
63 var self = this
64 return this.usersCollection.find({shortid: shortid}).then(function (users) {
65 var user = users[0]
66 if (!currentUser.isAdmin && !passwordHash.verify(oldPassword, user.password)) {
67 return Promise.reject(new Error('Invalid password'))
68 }
69
70 return self.usersCollection.update({shortid: shortid}, {$set: {password: passwordHash.generate(newPassword)}})
71 })
72}
73module.exports = UsersRepository