├── .eslintrc.json
├── .gitignore
├── .npmignore
├── .travis.yml
├── CHANGELOG.md
├── ISSUE_TEMPLATE.md
├── LICENSE
├── README.md
├── TESTING.md
├── bin
├── run-server.js
├── run-test.js
└── utils.js
├── bower.json
├── config
├── rollup.config.browser.cjs.js
├── rollup.config.browser.es.js
├── rollup.config.cjs.js
├── rollup.config.es.js
└── rollup.config.js
├── docs
├── admin_party.png
├── admin_party.xcf
├── api.md
├── blogger.png
├── blogger_ddoc.png
├── employee.png
├── logo.png
├── logo.svg
├── new_doc_button.png
├── recipes.md
├── sauce_labs.png
├── security_button.png
└── setup.md
├── package-lock.json
├── package.json
├── src
├── admins.js
├── authentication.js
├── index.js
├── users.js
└── utils.js
├── test
├── test-pouchdb.js
├── test-utils.js
├── test.admins.js
├── test.authentication.js
├── test.issue.109.js
├── test.issue.204.js
├── test.users.js
└── test.users.metadata.js
└── types
├── index.d.ts
├── tsconfig.json
├── tslint.json
└── type-tests.ts
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 |
3 | "extends": "eslint:recommended",
4 |
5 | "parserOptions": {
6 | "ecmaVersion": 6,
7 | "sourceType": "module"
8 | },
9 |
10 | "env": {
11 | "browser": true,
12 | "node": true,
13 | "mocha": true
14 | },
15 |
16 | "globals": {
17 | "Map": true,
18 | "Set": true,
19 | "chrome": true,
20 | "Promise": true,
21 | "Uint8Array": true,
22 | "ArrayBuffer": true,
23 | "FileReaderSync": true,
24 | "sqlitePlugin": true,
25 | "emit": true,
26 | "PouchDB": true,
27 | "should": true,
28 | "assert": true,
29 | "testUtils": true,
30 | "importScripts": true,
31 | "testCases": true
32 | },
33 |
34 | "rules": {
35 | "no-empty": 0,
36 | "no-console": 0,
37 | "semi": ["error", "always"],
38 | "curly": ["error", "all"],
39 | "space-unary-ops": ["error", {"words": true}],
40 | "space-before-function-paren": ["error", {"anonymous": "always", "named": "never"}],
41 | "max-len": ["error", 100, {"ignoreComments": true, "ignoreStrings": true, "ignoreRegExpLiterals": true}],
42 | "keyword-spacing": ["error"],
43 | "space-before-blocks": ["error"]
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .DS_Store
3 | *~
4 | coverage
5 | npm-debug.log
6 | test/test-bundle.js
7 | dist
8 | lib
9 | .idea
10 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .DS_Store
3 | *~
4 | coverage
5 | npm-debug.log
6 | test/test-bundle.js
7 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 |
3 | services:
4 | - docker
5 |
6 | node_js:
7 | - "6"
8 |
9 | sudo: false
10 |
11 | addons:
12 | jwt:
13 | # SAUCE_ACCESS_KEY
14 | - secure: PUcJWxBQJ/uGdDzcoI7PcASKJUGujmBRrwCylMHCaygxt2OSwHt7aMaa5phfAfDU/VWG+FAMruDajPsTztXichj94QUqhnTGHeFnv7V0DGJloZVGFz/svzbW2feeDq1enj2lkJUWEHxRIfV8tH7xDBHC16R/WV7g9UFa69GXSXg=
15 |
16 | before_install:
17 | # Install PhantomJS and cache it
18 | # See https://github.com/Medium/phantomjs#continuous-integration
19 | - "export PHANTOMJS_VERSION=2.1.1"
20 | - "export PATH=$PWD/travis_phantomjs/phantomjs-$PHANTOMJS_VERSION-linux-x86_64/bin:$PATH"
21 | - "if [ $(phantomjs --version) != $PHANTOMJS_VERSION ]; then rm -rf $PWD/travis_phantomjs; mkdir -p $PWD/travis_phantomjs; fi"
22 | - "if [ $(phantomjs --version) != $PHANTOMJS_VERSION ]; then wget https://github.com/Medium/phantomjs/releases/download/v$PHANTOMJS_VERSION/phantomjs-$PHANTOMJS_VERSION-linux-x86_64.tar.bz2 -O $PWD/travis_phantomjs/phantomjs-$PHANTOMJS_VERSION-linux-x86_64.tar.bz2; fi"
23 | - "if [ $(phantomjs --version) != $PHANTOMJS_VERSION ]; then tar -xvf $PWD/travis_phantomjs/phantomjs-$PHANTOMJS_VERSION-linux-x86_64.tar.bz2 -C $PWD/travis_phantomjs; fi"
24 | - "phantomjs --version"
25 |
26 | # package-lock.json was introduced in npm@5
27 | - npm install -g npm@5 # skip this if you are using node 9
28 | - npm install -g greenkeeper-lockfile@1
29 |
30 | before_script:
31 | # update package-lock.json
32 | - greenkeeper-lockfile-update
33 | # run linter before the tests
34 | - npm run lint
35 |
36 | after_script:
37 | # upload the updated package-lock.json
38 | - greenkeeper-lockfile-upload
39 |
40 | script: npm run $COMMAND
41 |
42 | env:
43 | global:
44 | - NPM_CONFIG_PROGRESS="false"
45 | - SAUCE_USERNAME=ptitjes
46 |
47 | matrix:
48 | - COMMAND=test-types
49 |
50 | - SERVER=couchdb:latest CLIENT=node COMMAND=test
51 | - SERVER=couchdb:latest CLIENT=phantom COMMAND=test
52 |
53 | - SERVER=couchdb:1.7.1 CLIENT=node COMMAND=test
54 | - SERVER=couchdb:1.7.1 CLIENT=phantom COMMAND=test
55 |
56 | - SERVER=pouchdb-server CLIENT=node COMMAND=test
57 | - SERVER=pouchdb-server CLIENT=phantom COMMAND=test
58 |
59 | - SERVER=couchdb:latest CLIENT=saucelabs:Chrome COMMAND=test
60 | - SERVER=couchdb:latest CLIENT=saucelabs:Firefox COMMAND=test
61 | - SERVER=couchdb:latest CLIENT=saucelabs:Safari COMMAND=test
62 | - SERVER=couchdb:latest CLIENT="saucelabs:Internet Explorer:10:Windows 8" COMMAND=test
63 | - SERVER=couchdb:latest CLIENT="saucelabs:Internet Explorer:11:Windows 10" COMMAND=test
64 |
65 | branches:
66 | only:
67 | - master
68 | - /^greenkeeper/.*$/
69 |
70 | cache:
71 | directories:
72 | - $HOME/.npm
73 | # See https://github.com/Medium/phantomjs#continuous-integration
74 | - travis_phantomjs
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 |
6 | ## [1.1.3](https://github.com/pouchdb-community/pouchdb-authentication/compare/v1.1.2...v1.1.3) (2018-05-19)
7 |
8 |
9 | ### Bug Fixes
10 |
11 | * **build:** publish browserified version ([46e883e](https://github.com/pouchdb-community/pouchdb-authentication/commit/46e883e))
12 |
13 |
14 |
15 |
16 | ## [1.1.2](https://github.com/pouchdb-community/pouchdb-authentication/compare/v1.1.1...v1.1.2) (2018-02-03)
17 |
18 |
19 | ### Bug Fixes
20 |
21 | * **package:** update url-join to version 4.0.0 ([fe89208](https://github.com/pouchdb-community/pouchdb-authentication/commit/fe89208))
22 | * **urls:** enable databases that are not hosted on domain root ([ac2e2b0](https://github.com/pouchdb-community/pouchdb-authentication/commit/ac2e2b0)), closes [#215](https://github.com/pouchdb-community/pouchdb-authentication/issues/215)
23 |
24 |
25 |
26 |
27 | ## [1.1.1](https://github.com/pouchdb-community/pouchdb-authentication/compare/v1.1.0...v1.1.1) (2018-01-20)
28 |
29 |
30 | ### Bug Fixes
31 |
32 | * **auth:** also use Basic Authentication information database opts ([8b1d191](https://github.com/pouchdb-community/pouchdb-authentication/commit/8b1d191)), closes [#204](https://github.com/pouchdb-community/pouchdb-authentication/issues/204)
33 | * **package:** update url-join to version 2.0.5 ([6a627d1](https://github.com/pouchdb-community/pouchdb-authentication/commit/6a627d1)), closes [#205](https://github.com/pouchdb-community/pouchdb-authentication/issues/205)
34 | * **package:** update url-join to version 3.0.0 ([d7b27ae](https://github.com/pouchdb-community/pouchdb-authentication/commit/d7b27ae))
35 |
36 |
37 |
38 |
39 | # [1.1.0](https://github.com/pouchdb-community/pouchdb-authentication/compare/v1.0.0...v1.1.0) (2017-12-25)
40 |
41 |
42 | ### Features
43 |
44 | * **types:** package typescript type declarations ([e59ad40](https://github.com/pouchdb-community/pouchdb-authentication/commit/e59ad40))
45 |
46 |
47 |
48 |
49 | # [1.0.0](https://github.com/pouchdb-community/pouchdb-authentication/compare/v0.5.5...v1.0.0) (2017-12-17)
50 |
51 |
52 | ### Bug Fixes
53 |
54 | * **ajax:** correctly handle Basic authentication ([19f547b](https://github.com/pouchdb-community/pouchdb-authentication/commit/19f547b)), closes [#109](https://github.com/pouchdb-community/pouchdb-authentication/issues/109)
55 | * **browser:** plugin registration bug introduced in ES6 move ([cd12d06](https://github.com/pouchdb-community/pouchdb-authentication/commit/cd12d06))
56 | * **nodejs:** correctly set ajax request's body for login ([5b61b00](https://github.com/pouchdb-community/pouchdb-authentication/commit/5b61b00)), closes [#127](https://github.com/pouchdb-community/pouchdb-authentication/issues/127) [#130](https://github.com/pouchdb-community/pouchdb-authentication/issues/130) [#141](https://github.com/pouchdb-community/pouchdb-authentication/issues/141)
57 | * **package:** update pouchdb to version ~6.4.0 ([f0c45b5](https://github.com/pouchdb-community/pouchdb-authentication/commit/f0c45b5))
58 | * **putUser:** ensure reserved words are enforced in metadata ([b1ea26a](https://github.com/pouchdb-community/pouchdb-authentication/commit/b1ea26a))
59 | * **urls:** replace base URL regex with url-parse ([7472135](https://github.com/pouchdb-community/pouchdb-authentication/commit/7472135)), closes [#150](https://github.com/pouchdb-community/pouchdb-authentication/issues/150) [#160](https://github.com/pouchdb-community/pouchdb-authentication/issues/160)
60 | * **urls:** respect DB prefix for base URL if set ([d600426](https://github.com/pouchdb-community/pouchdb-authentication/commit/d600426)), closes [#158](https://github.com/pouchdb-community/pouchdb-authentication/issues/158)
61 |
62 |
63 | ### Features
64 |
65 | * **admins:** add signUpAdmin and deleteAdmin ([cb8991d](https://github.com/pouchdb-community/pouchdb-authentication/commit/cb8991d))
66 | * **package:** move to ES6 with rollup build ([b420ad4](https://github.com/pouchdb-community/pouchdb-authentication/commit/b420ad4))
67 | * **putUser:** take roles in account ([7f44c9e](https://github.com/pouchdb-community/pouchdb-authentication/commit/7f44c9e)), closes [#114](https://github.com/pouchdb-community/pouchdb-authentication/issues/114)
68 | * **users:** add deleteUser ([8e187e7](https://github.com/pouchdb-community/pouchdb-authentication/commit/8e187e7))
69 |
70 |
71 | ### BREAKING CHANGES
72 |
73 | * **putUser:** In both signUp and putUser, '_id', '_rev', 'name',
74 | 'type', 'roles', 'password', 'password_scheme', 'iterations',
75 | 'derived_key', 'salt' are now all reserved words, and 'metadata' is
76 | not a reserved word anymore.
77 |
--------------------------------------------------------------------------------
/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
8 |
9 |
10 |
11 | ## Expected Behavior
12 |
13 |
14 |
15 | ## Current Behavior
16 |
17 |
18 |
19 | ## Possible Solution
20 |
21 |
22 |
23 | ## Steps to Reproduce (for bugs)
24 |
25 |
26 | 1.
27 | 2.
28 | 3.
29 | 4.
30 |
31 | ## Context
32 |
33 |
34 |
35 | ## Your Environment
36 |
37 | * Version of PouchDB Authentication:
38 | * Version of PouchDB:
39 | * Platform name and version:
40 | * Operating System and version:
41 | * Server:
42 | * Link to your project:
43 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | PouchDB Authentication
2 | =====
3 |
4 | [](https://travis-ci.org/pouchdb-community/pouchdb-authentication)
5 | [](https://greenkeeper.io/)
6 | [](https://www.npmjs.com/package/pouchdb-authentication)
7 |
8 |
9 |
10 | Easy user authentication for PouchDB/CouchDB.
11 |
12 | ```js
13 | var db = new PouchDB('http://mysite:5984/mydb', {skip_setup: true});
14 | db.logIn('batman', 'brucewayne').then(function (batman) {
15 | console.log("I'm Batman.");
16 | return db.logOut();
17 | });
18 | ```
19 |
20 |
21 | Overview
22 | ----------
23 |
24 | You know what's hard? **Security**. You know what makes security really easy? **CouchDB**.
25 |
26 | That's right, CouchDB is more than a database: it's also a RESTful web server with a built-in authentication framework. And it boasts some top-notch security features:
27 |
28 | * **salts and hashes** passwords automatically with [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2)
29 | * **stores a cookie** in the browser
30 | * **refreshes the cookie** every 10 minutes (default)
31 |
32 | And best of all, CouchDB does it with good ol'-fashioned HTTP. Just open up the network tab and watch the JSON fly back and forth.
33 |
34 | To get started, just install CouchDB, throw in [a little SSL](https://wiki.apache.org/couchdb/How_to_enable_SSL), and you've got everything you need for your site's authentication.
35 |
36 | ### Project status
37 |
38 | This plugin uses vanilla CouchDB. The goal is to give you a lightweight authentication API that doesn't require anything fancy – no additional server daemons, no third-party providers, just straight-up Pouch and Couch.
39 |
40 | So this is more of a reference implementation than an all-in-one solution. If there's a feature missing that you need, you will probably need to write a custom server (see the [CouchDB Authentication recipes][recipes] section for details).
41 |
42 | Since version 1.0.0, this plugin **does support Node.js**.
43 |
44 |
45 | Using PouchDB Authentication
46 | ------
47 |
48 | * [Setup](https://github.com/pouchdb-community/pouchdb-authentication/blob/master/docs/setup.md)
49 | * [API](https://github.com/pouchdb-community/pouchdb-authentication/blob/master/docs/api.md)
50 | * [CouchDB Authentication recipes][recipes]
51 |
52 |
53 | Changelog
54 | ------
55 |
56 | PouchDB Authentication follows [semantic versioning](http://semver.org/). To see a changelog with all PouchDB Authentication releases, check out the [Github releases page](https://github.com/pouchdb-community/pouchdb-authentication/releases).
57 |
58 |
59 | Contributing
60 | ------
61 |
62 | We use [standard-version](https://github.com/conventional-changelog/standard-version) for release versioning along with [Angular-style commit messages](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#commit) to automate the changelog generation. To help you make good commit messages, you are advised to install and use [commitizen](https://github.com/commitizen/cz-cli).
63 |
64 | PouchDB Authentication is heavily tested, so you'll also want to check out the [testing guide](https://github.com/pouchdb-community/pouchdb-authentication/blob/master/TESTING.md).
65 |
66 | [recipes]: https://github.com/pouchdb-community/pouchdb-authentication/blob/master/docs/recipes.md
67 |
68 | Big Thanks
69 | ------
70 |
71 | Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce labs homepage].
72 |
73 | ![sauce labs logo][]
74 |
75 | [sauce labs homepage]: https://saucelabs.com
76 | [sauce labs logo]: https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/master/docs/sauce_labs.png
77 |
--------------------------------------------------------------------------------
/TESTING.md:
--------------------------------------------------------------------------------
1 | Test this library
2 | ------
3 |
4 | First off, install the library's dependencies:
5 |
6 | ```
7 | npm install
8 | ```
9 |
10 | ### Using a self-managed CouchDB instance
11 |
12 | Your CouchDB instance must be accessible at `http://localhost:5984`. You can specify an alternative URL by setting a `SERVER_HOST` environment variable.
13 |
14 | Also remember that the CouchDB instance must be in [Admin Party](http://guide.couchdb.org/draft/security.html#party)! CORS is automatically enabled by the test script.
15 |
16 | #### To test in the browser (locally)
17 |
18 | ```bash
19 | CLIENT=local npm run test
20 | # or simply
21 | npm run test-local
22 | ```
23 |
24 | #### To test in PhantomJS
25 |
26 | ```bash
27 | CLIENT=phantom npm run test
28 | # or simply
29 | npm run test-phantom
30 | ```
31 |
32 | #### To test in NodeJS
33 |
34 | ```bash
35 | CLIENT=node npm run test
36 | # or simply
37 | npm run test-node
38 | ```
39 |
40 | ### Using a docker CouchDB instance
41 |
42 | First you need to install Docker, start the daemon service, and enable access permissions to `/var/run/docker.sock`. As an example, on Fedora Linux you would do as root:
43 |
44 | ```bash
45 | dnf install docker
46 | systemctl start docker
47 | chmod a+rw /var/run/docker.sock
48 | ```
49 |
50 | Then you can run the tests as user.
51 |
52 | #### Using the latest CouchDB 2.x
53 |
54 | ```bash
55 | SERVER=couchdb:2 CLIENT=local npm run test
56 | ```
57 |
58 | #### Using the latest CouchDB 1.x
59 |
60 | ```bash
61 | SERVER=couchdb:1 CLIENT=local npm run test
62 | ```
63 |
64 | #### Using PouchDB Server
65 |
66 | ```bash
67 | SERVER=pouchdb-server CLIENT=local npm run test
68 | ```
69 |
--------------------------------------------------------------------------------
/bin/run-server.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 | var utils = require('./utils');
3 |
4 | function runServer(serverName, runTests) {
5 |
6 | var tmp = serverName == null ? null : serverName.split(':');
7 | var server = serverName == null ? null : {
8 | name: tmp[0] || 'couchdb',
9 | version: tmp[1] || 'latest',
10 | };
11 |
12 | return Promise.resolve().then(function () {
13 | if (!server) {
14 | return {
15 | handlePromise: Promise.resolve(null),
16 | serverHost: process.env.SERVER_HOST || 'http://localhost:5984',
17 | };
18 | }
19 |
20 | // CouchDB
21 | if (server.name === 'couchdb') {
22 | var dockerImage = 'couchdb:' + server.version;
23 | return {
24 | handlePromise: utils.dockerRun(dockerImage, ['3000:5984']),
25 | serverHost: 'http://localhost:3000',
26 | };
27 | }
28 |
29 | // PouchDB Server
30 | else if (server.name === 'pouchdb-server') {
31 | return {
32 | handlePromise: utils.npmRunDaemon('pouchdb-server', ['--in-memory', '--port', '3000']),
33 | serverHost: 'http://localhost:3000',
34 | };
35 | }
36 |
37 | // Unknown
38 | throw new Error('Unknown SERVER \'' + server.name + '\'. Did you mean pouchdb-server?');
39 | }).then(function (result) {
40 | var handlePromise = result.handlePromise;
41 | var serverHost = result.serverHost;
42 |
43 | return handlePromise.then(function (handle) {
44 | return waitForCouch(serverHost)
45 | .then(function () {
46 | // To workaround pouchdb/add-cors-to-couchdb#24
47 | if (server && server.name !== 'pouchdb-server') {
48 | console.log('\nExecuting add-cors-to-couchdb');
49 | return utils.npmRun('add-cors-to-couchdb', [serverHost]);
50 | }
51 | }).then(function () {
52 | return runTests(serverHost);
53 | }).catch(function (exitCode) {
54 | if (typeof exitCode !== 'number') {
55 | console.error(exitCode);
56 | exitCode = 1;
57 | }
58 | return Promise.resolve().then(function () {
59 | if (handle) {
60 | return handle.destroy();
61 | }
62 | }).then(function () {
63 | process.exit(exitCode);
64 | });
65 | }).then(function () {
66 | if (handle) {
67 | return handle.destroy();
68 | }
69 | });
70 | });
71 | });
72 | }
73 |
74 | function waitForCouch(url) {
75 | return new Promise(function (resolve) {
76 | var interval = setInterval(function () {
77 | var request = http.request(url, function (res) {
78 | if (res.statusCode === 200) {
79 | clearInterval(interval);
80 | resolve();
81 | }
82 | });
83 | request.on('error', function () {
84 | console.info('Waiting for CouchDB on ' + url);
85 | });
86 | request.end();
87 | }, 1000);
88 | });
89 | }
90 |
91 | module.exports = runServer;
92 |
--------------------------------------------------------------------------------
/bin/run-test.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 | 'use strict';
3 |
4 | var utils = require('./utils');
5 | var runServer = require('./run-server');
6 |
7 | var server = process.env.SERVER;
8 | var client = process.env.CLIENT || 'phantom';
9 |
10 | runServer(server, function (serverHost) {
11 | return runTests(client, serverHost);
12 | });
13 |
14 | function runTests(client, serverHost) {
15 | if (client === 'node') {
16 | global.__testConfig__ = {
17 | serverHost: serverHost,
18 | };
19 |
20 | console.log('\nRunning mocha tests on Node.js');
21 | return utils.mochaRun({ui: 'bdd'}, 'test');
22 | } else {
23 | var options = buildKarmaConf(client, serverHost);
24 |
25 | // buildKarmaConf returns null if we can't run the tests
26 | // e.g. SauceLabs with no credentials on Travis
27 | if (!options) {
28 | return Promise.resolve();
29 | }
30 |
31 | return utils.karmaRun(options);
32 | }
33 | }
34 |
35 | function buildKarmaConf(client, serverHost) {
36 | // Karma base configuration
37 | var options = {
38 | basePath: '',
39 | frameworks: ['mocha', 'chai', 'browserify'],
40 | files: [
41 | 'test/**/*.js',
42 | ],
43 | preprocessors: {
44 | 'test/**/*.js': ['browserify'],
45 | },
46 | browserify: {
47 | debug: true,
48 | transform: ['brfs'],
49 | },
50 | port: 9876,
51 | colors: true,
52 | reporters: ['mocha'],
53 | concurrency: 1,
54 | singleRun: client !== 'local',
55 | client: {
56 | serverHost: serverHost,
57 | },
58 | };
59 |
60 | if (client === 'phantom') {
61 | options.browsers = ['PhantomJS'];
62 | options.phantomJsLauncher = {
63 | exitOnResourceError: true,
64 | };
65 | } else if (client === 'local') {
66 | options.browsers = [];
67 | } else {
68 | var tmp = (client || 'saucelabs:firefox').split(':');
69 | client = {
70 | runner: tmp[0] || 'saucelabs',
71 | browser: tmp[1] || 'firefox',
72 | version: tmp[2] || null, // Latest
73 | platform: tmp[3] || null,
74 | };
75 |
76 | if (client.runner === 'saucelabs') {
77 |
78 | // Standard SauceLabs configuration
79 | options.sauceLabs = {
80 | testName: 'pouchdb-authentication tests',
81 | connectOptions: {
82 | username: process.env.SAUCE_USERNAME,
83 | accessKey: process.env.SAUCE_ACCESS_KEY,
84 | tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER || 'tunnel-' + Date.now(),
85 | },
86 | };
87 | options.customLaunchers = {
88 | sl: {
89 | base: 'SauceLabs',
90 | browserName: client.browser,
91 | platform: client.platform,
92 | version: client.version,
93 | },
94 | };
95 | options.browsers = ['sl'];
96 | options.reporters.push('saucelabs');
97 |
98 | // Longer timeouts for SauceLabs
99 | options.captureTimeout = 2 * 60 * 1000;
100 | options.browserNoActivityTimeout = 30 * 60 * 1000;
101 | options.browserDisconnectTimeout = 30 * 60 * 1000;
102 |
103 | // To account for distance between SauceLabs and CouchDB at Travis
104 | options.client.mocha = {
105 | timeout: 30 * 60 * 1000,
106 | };
107 | }
108 | }
109 |
110 | return options;
111 | }
112 |
--------------------------------------------------------------------------------
/bin/utils.js:
--------------------------------------------------------------------------------
1 | var childProcess = require('child_process');
2 | var karma = require('karma');
3 | var Mocha = require('mocha');
4 | var fs = require('fs');
5 | var path = require('path');
6 |
7 | function npmRun(bin, args, stdio) {
8 | return run('node_modules/.bin/' + bin, args, stdio);
9 | }
10 |
11 | function npmRunDaemon(bin, args, stdio) {
12 | return runDaemon('node_modules/.bin/' + bin, args, stdio);
13 | }
14 |
15 | function mochaRun(options, testDir) {
16 | return new Promise(function (resolve, reject) {
17 | var mocha = new Mocha(options);
18 |
19 | fs.readdirSync(testDir).filter(function (file) {
20 | return file.substr(-3) === '.js';
21 | }).forEach(function (file) {
22 | mocha.addFile(path.join(testDir, file));
23 | });
24 |
25 | mocha.run(function (failures) {
26 | if (!failures) {
27 | resolve();
28 | } else {
29 | reject(failures);
30 | }
31 | });
32 | });
33 | }
34 |
35 | function karmaRun(options) {
36 | return new Promise(function (resolve, reject) {
37 | var server = new karma.Server(options, function (exitCode) {
38 | if (exitCode === 0) {
39 | resolve();
40 | } else {
41 | reject(exitCode);
42 | }
43 | });
44 | server.start();
45 | });
46 | }
47 |
48 | function dockerRun(image, ports) {
49 | var name = image.replace('/', '-').replace(':', '-') + '-' + Date.now();
50 |
51 | var args = [];
52 | args.push('run');
53 | ports.forEach(function (port) {
54 | args.push('-p', port);
55 | });
56 | args.push('--name', name, '-d', image);
57 |
58 | console.log('\nStarting docker image \'' + image + '\'');
59 | return run('docker', args, 'ignore').then(function () {
60 | return {
61 | destroy: function () {
62 | console.log('\nStopping docker container');
63 | return run('docker', ['stop', name]).then(function () {
64 | console.log('\nRemoving docker container');
65 | return run('docker', ['rm', name]);
66 | });
67 | },
68 | };
69 | });
70 | }
71 |
72 | function run(bin, args, stdio) {
73 | return new Promise(function (resolve, reject) {
74 | var cmd = bin + (args ? ' ' + args.join(' ') : '');
75 | console.log('> ' + cmd);
76 |
77 | var testProcess = childProcess.spawn(bin, args, {
78 | env: process.env,
79 | stdio: stdio || 'inherit',
80 | });
81 |
82 | testProcess.on('close', function (code) {
83 | if (code === 0) {
84 | resolve();
85 | } else {
86 | reject(code);
87 | }
88 | });
89 | });
90 | }
91 |
92 |
93 | function runDaemon(bin, args, stdio) {
94 | var cmd = bin + (args ? ' ' + args.join(' ') : '');
95 |
96 | var daemonProcess = childProcess.spawn(bin, args, {
97 | env: process.env,
98 | stdio: stdio || 'ignore',
99 | });
100 |
101 | console.log('\nStarting daemon');
102 | console.log('> ' + cmd);
103 | return Promise.resolve().then(function () {
104 | return {
105 | destroy: function () {
106 | console.log('\nStopping daemon');
107 | daemonProcess.kill();
108 | },
109 | };
110 | });
111 | }
112 |
113 | module.exports = {
114 | npmRun,
115 | npmRunDaemon,
116 | dockerRun,
117 | karmaRun,
118 | mochaRun,
119 | };
120 |
--------------------------------------------------------------------------------
/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "pouchdb-authentication",
3 | "description": "Easy authentication plugin for PouchDB/CouchDB",
4 | "main": "dist/pouchdb.authentication.js",
5 | "homepage": "https://github.com/nolanlawson/pouchdb-authentication",
6 | "authors": [
7 | "Nolan Lawson "
8 | ],
9 | "keywords": [
10 | "pouchdb",
11 | "couchdb",
12 | "authentication"
13 | ],
14 | "license": "Apache 2.0",
15 | "ignore": [
16 | "**/.*",
17 | "node_modules",
18 | "bower_components",
19 | "test",
20 | "tests"
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/config/rollup.config.browser.cjs.js:
--------------------------------------------------------------------------------
1 | import config from './rollup.config';
2 |
3 | export default config({
4 | format: 'cjs',
5 | dest: 'lib/index.browser.js',
6 | browser: true
7 | });
8 |
--------------------------------------------------------------------------------
/config/rollup.config.browser.es.js:
--------------------------------------------------------------------------------
1 | import config from './rollup.config';
2 |
3 | export default config({
4 | format: 'es',
5 | dest: 'lib/index.browser.es.js',
6 | browser: true
7 | });
8 |
--------------------------------------------------------------------------------
/config/rollup.config.cjs.js:
--------------------------------------------------------------------------------
1 | import config from './rollup.config';
2 |
3 | export default config({
4 | format: 'cjs',
5 | dest: 'lib/index.js',
6 | browser: false
7 | });
8 |
--------------------------------------------------------------------------------
/config/rollup.config.es.js:
--------------------------------------------------------------------------------
1 | import config from './rollup.config';
2 |
3 | export default config({
4 | format: 'es',
5 | dest: 'lib/index.es.js',
6 | browser: false
7 | });
8 |
--------------------------------------------------------------------------------
/config/rollup.config.js:
--------------------------------------------------------------------------------
1 | import buble from 'rollup-plugin-buble';
2 | import replace from 'rollup-plugin-replace';
3 |
4 | var external = Object.keys(require('../package.json').dependencies);
5 |
6 | export default config => {
7 | return {
8 | input: 'src/index.js',
9 | output: {
10 | format: config.format,
11 | file: config.dest
12 | },
13 | external: external,
14 | plugins: [
15 | buble(),
16 | replace({'process.browser': JSON.stringify(!!config.browser)})
17 | ]
18 | };
19 | };
20 |
--------------------------------------------------------------------------------
/docs/admin_party.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/admin_party.png
--------------------------------------------------------------------------------
/docs/admin_party.xcf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/admin_party.xcf
--------------------------------------------------------------------------------
/docs/api.md:
--------------------------------------------------------------------------------
1 | API
2 | -------
3 |
4 | * [db.signUp()](#dbsignupusername-password--options--callback)
5 | * [db.logIn()](#dbloginusername-password--options--callback)
6 | * [db.logOut()](#dblogoutcallback)
7 | * [db.getSession()](#dbgetsessionopts--callback)
8 | * [db.getUser()](#dbgetuserusername--opts-callback)
9 | * [db.putUser()](#dbputuserusername-opts--callback)
10 | * [db.deleteUser()](#dbdeleteuserusername-opts--callback)
11 | * [db.changePassword()](#user-content-dbchangepasswordusername-password--opts-callback)
12 | * [db.changeUsername()](#user-content-dbchangeusernameoldusername-newusername-opts-callback)
13 | * [db.signUpAdmin()](#dbsignupadminusername-password--options--callback)
14 | * [db.deleteAdmin()](#dbdeleteadminusername-opts--callback)
15 |
16 | Like PouchDB, every function takes a Node-style callback of the form `function(error, response)`. Or you can use promises:
17 |
18 | ```js
19 | db.doSomething(args).then(function (response){
20 | return db.doSomethingElse(args);
21 | }).then(function response) {
22 | // handle response
23 | }).catch(function (error) {
24 | // handle error
25 | });
26 | ```
27 |
28 | Every function also takes a set of `options`. Unless otherwise noted, the only available option is `ajax`, which corresponds to the standard PouchDB ajax options. (See [the PouchDB API](http://pouchdb.com/api.html) for details.) Currently the only ajax option is `ajax.cache`, which can be set to `true` to disable cache-busting on IE.
29 |
30 | #### db.signUp(username, password [, options] [, callback])
31 |
32 | Sign up a new user who doesn't exist yet. Throws an error if the user already exists or if the username is invalid, or if some network error occurred. CouchDB has some limitations on user names (e.g. they cannot contain the character `:`).
33 |
34 | ```js
35 | db.signUp('batman', 'brucewayne', function (err, response) {
36 | if (err) {
37 | if (err.name === 'conflict') {
38 | // "batman" already exists, choose another username
39 | } else if (err.name === 'forbidden') {
40 | // invalid username
41 | } else {
42 | // HTTP error, cosmic rays, etc.
43 | }
44 | }
45 | });
46 | ```
47 |
48 | ##### Example response:
49 |
50 | ```js
51 | {
52 | "ok":true,
53 | "id":"org.couchdb.user:batman",
54 | "rev":"1-575ed65bb40cbe90dc882ced8044a90f"
55 | }
56 | ```
57 |
58 | **Note:** Signing up does not automatically log in a user; you will need to call `db.logIn()` afterwards.
59 |
60 | ##### Options
61 |
62 | * **metadata** : Object of metadata you want to store with the username, e.g. an email address or any other info. Can be as deeply structured as you want.
63 |
64 | ##### Example:
65 |
66 | ```js
67 | db.signUp('robin', 'dickgrayson', {
68 | metadata : {
69 | email : 'robin@boywonder.com',
70 | birthday : '1932-03-27T00:00:00.000Z',
71 | likes : ['acrobatics', 'short pants', 'sidekickin\''],
72 | }
73 | }, function (err, response) {
74 | // etc.
75 | });
76 | ```
77 |
78 | Note that CouchDB does not enforce a password policy or a username policy, unless you add a security doc to the `_users` database.
79 |
80 | #### db.logIn(username, password [, options] [ callback])
81 |
82 | Log in an existing user. Throws an error if the user doesn't exist yet, the password is wrong, the HTTP server is unreachable, or a meteor struck your computer.
83 |
84 | ```js
85 | db.logIn('superman', 'clarkkent', function (err, response) {
86 | if (err) {
87 | if (err.name === 'unauthorized' || err.name === 'forbidden') {
88 | // name or password incorrect
89 | } else {
90 | // cosmic rays, a meteor, etc.
91 | }
92 | }
93 | });
94 | ```
95 |
96 | ##### Example response:
97 |
98 | ```js
99 | {"ok":true,"name":"david","roles":[]}
100 | ```
101 |
102 | #### db.logOut([callback])
103 |
104 | Logs out whichever user is currently logged in. If nobody's logged in, it does nothing and just returns `{"ok" : true}`.
105 |
106 | ##### Example:
107 |
108 | ```js
109 | db.logOut(function (err, response) {
110 | if (err) {
111 | // network error
112 | }
113 | })
114 | ```
115 |
116 | ##### Example response:
117 |
118 | ```js
119 | {"ok":true}
120 | ```
121 |
122 | #### db.getSession([opts] [, callback])
123 |
124 | Returns information about the current session. In other words, this tells you which user is currently logged in.
125 |
126 | ##### Example:
127 |
128 | ```js
129 | db.getSession(function (err, response) {
130 | if (err) {
131 | // network error
132 | } else if (!response.userCtx.name) {
133 | // nobody's logged in
134 | } else {
135 | // response.userCtx.name is the current user
136 | }
137 | });
138 | ```
139 |
140 | ##### Example response:
141 |
142 | ```js
143 | {
144 | "info": {
145 | "authenticated": "cookie",
146 | "authentication_db": "_users",
147 | "authentication_handlers": ["oauth", "cookie", "default"]
148 | },
149 | "ok": true,
150 | "userCtx": {
151 | "name": "batman",
152 | "roles": []
153 | }
154 | }
155 |
156 | ```
157 |
158 | **Note:** `getSession()` returns basic user information, like name and roles, but doesn't return metadata. If you need the metadata, use `getUser()`.
159 |
160 | #### db.getUser(username [, opts][, callback])
161 |
162 | Returns the user document associated with a username. (CouchDB, in a pleasing show of consistency, stores users as JSON documents in the special `_users` database.) This is the primary way to get metadata about a user.
163 |
164 | ##### Example:
165 |
166 | ```js
167 | db.getUser('aquaman', function (err, response) {
168 | if (err) {
169 | if (err.name === 'not_found') {
170 | // typo, or you don't have the privileges to see this user
171 | } else {
172 | // some other error
173 | }
174 | } else {
175 | // response is the user object
176 | }
177 | });
178 | ```
179 |
180 | ##### Example response:
181 |
182 | ```js
183 | {
184 | "_id": "org.couchdb.user:aquaman",
185 | "_rev": "1-60288b5b056a8af31e910bca2523ea6a",
186 | "derived_key": "05c3314f180faed646af3b77e637ffecf2e3fb93",
187 | "iterations": 10,
188 | "name": "aquaman",
189 | "password_scheme": "pbkdf2",
190 | "roles": [],
191 | "salt": "bce14111a559e00587f3e5f207e4a316",
192 | "type": "user"
193 | }
194 | ```
195 |
196 | **Note:** Only server admins or the user themselves can fetch user data. Otherwise you will get a 404 `not_found` error.
197 |
198 |
199 | #### db.putUser(username, opts [, callback])
200 |
201 | Update the metadata of a user.
202 |
203 | ```js
204 | db.putUser('robin', {
205 | metadata : {
206 | email : 'robin@boywonder.com',
207 | birthday : '1932-03-27T00:00:00.000Z',
208 | likes : ['acrobatics', 'short pants', 'sidekickin\''],
209 | }
210 | }, function (err, response) {
211 | // etc.
212 | });
213 | ```
214 |
215 | #### db.deleteUser(username, opts [, callback])
216 |
217 | Delete a user.
218 |
219 | ```js
220 | db.deleteUser('robin', function (err, response) {
221 | // etc.
222 | });
223 | ```
224 |
225 | #### db.changePassword(username, password [, opts][, callback])
226 |
227 | Set new `password` for user `username`.
228 |
229 | ##### Example:
230 |
231 | ```js
232 | db.changePassword('spiderman', 'will-remember', function(err, response) {
233 | if (err) {
234 | if (err.name === 'not_found') {
235 | // typo, or you don't have the privileges to see this user
236 | } else {
237 | // some other error
238 | }
239 | } else {
240 | // response is the user update response
241 | // {
242 | // "ok": true,
243 | // "id": "org.couchdb.user:spiderman",
244 | // "rev": "2-09310a62dcc7eea42bf3d4f67e8ff8c4"
245 | // }
246 | }
247 | })
248 | ```
249 |
250 | **Note:** Only server admins or the user themselves can change user data. Otherwise you will get a 404 `not_found` error.
251 |
252 | #### db.changeUsername(oldUsername, newUsername[, opts][, callback])
253 |
254 | Renames `oldUsername` to `newUsername`.
255 |
256 | ##### Example:
257 |
258 | ```js
259 | db.changeUsername('spiderman', 'batman', function(err) {
260 | if (err) {
261 | if (err.name === 'not_found') {
262 | // typo, or you don't have the privileges to see this user
263 | } else if (err.taken) {
264 | // auth error, make sure that 'batman' isn't already in DB
265 | } else {
266 | // some other error
267 | }
268 | } else {
269 | // succeeded
270 | }
271 | })
272 | ```
273 |
274 | **Note:** Only server admins change a username. Otherwise you will get a 404 `not_found` error.
275 |
276 | #### db.signUpAdmin(username, password [, options] [, callback])
277 |
278 | Sign up a new admin.
279 |
280 | ```js
281 | db.signUpAdmin('batman', 'brucewayne', function (err, response) {
282 | // etc.
283 | });
284 | ```
285 |
286 | #### db.deleteAdmin(username, opts [, callback])
287 |
288 | Delete an admin.
289 |
290 | ```js
291 | db.deleteAdmin('batman', function (err, response) {
292 | // etc.
293 | });
294 | ```
295 |
--------------------------------------------------------------------------------
/docs/blogger.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/blogger.png
--------------------------------------------------------------------------------
/docs/blogger_ddoc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/blogger_ddoc.png
--------------------------------------------------------------------------------
/docs/employee.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/employee.png
--------------------------------------------------------------------------------
/docs/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/logo.png
--------------------------------------------------------------------------------
/docs/logo.svg:
--------------------------------------------------------------------------------
1 |
18 |
--------------------------------------------------------------------------------
/docs/new_doc_button.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/new_doc_button.png
--------------------------------------------------------------------------------
/docs/recipes.md:
--------------------------------------------------------------------------------
1 | CouchDB authentication recipes
2 | ------------
3 |
4 | So you just installed CouchDB, but you're not sure how to set up the right user permissions? Look no further.
5 |
6 | ### First step: disable the Admin Party!
7 |
8 | When you first install CouchDB, it will be in the "Admin Party" mode, which means everyone is an admin. You'll want to disable this and create at least one admin user, so that random people can't mess with your CouchDB settings:
9 |
10 | ![Admin party][]
11 |
12 | Below is a list of recipes for common authentication use cases.
13 |
14 | * [Everybody can read and write everything](#everybody-can-read-and-write-everything)
15 | * [Everybody can read, only some can write (everything)](#everybody-can-read-only-some-can-write-everything)
16 | * [Everybody can read, only some can write (some things)](#everybody-can-read-only-some-can-write-some-things)
17 | * [Some people can read and write everything](#some-people-can-read-and-write-everything)
18 | * [Some people can read (some docs), some people can write (those same docs)](#some-people-can-read-some-docs-some-people-can-write-those-same-docs)
19 | * [Everybody has to be logged in to do anything](#everybody-has-to-be-logged-in-to-do-anything)
20 |
21 | ### Everybody can read and write everything
22 | * Example: a public wiki
23 |
24 | #### Howto
25 |
26 | Just create a new database; this is the default. It's very dangerous, though, since users can even overwite the history of a document. So you probably don't want it.
27 |
28 | ### Everybody can read, only some can write (everything)
29 | * Example: a blog
30 |
31 | #### Howto
32 |
33 | Create a new database, then add a *design doc* with a `validate_doc_update` function (see [the CouchDB docs](http://guide.couchdb.org/draft/validation.html) for details). This function will be called whenever a document is created, modified, or deleted. In it, we'll check that the user is either an admin or has the `'blogger'` role.
34 |
35 | The function looks like this:
36 |
37 | ```js
38 | function(newDoc, oldDoc, userCtx) {
39 | var role = "blogger";
40 | if (userCtx.roles.indexOf("_admin") === -1 && userCtx.roles.indexOf(role) === -1) {
41 | throw({forbidden : "Only users with role " + role + " or an admin can modify this database."});
42 | }
43 | }
44 | ```
45 |
46 | You can create the document like this:
47 |
48 | curl -X POST http://admin:password@localhost:5984/mydb \
49 | -H 'content-type:application/json' \
50 | -d $'{"_id":"_design/only_bloggers","validate_doc_update":"function (newDoc, oldDoc, userCtx) {\\nvar role = \\"blogger\\";\\nif (userCtx.roles.indexOf(\\"_admin\\") === -1 && userCtx.roles.indexOf(role) === -1) {\\nthrow({forbidden : \\"Only users with role \\" + role + \\" or an admin can modify this database.\\"});\\n}\\n}"}'
51 |
52 | In the above command, you will need to change **admin**/**password** (admin and password), **localhost:5984** (your Couch URL), **mydb** (your database), **only_bloggers** (name of the design doc, can be whatever you want), and **blogger** (name of the new role).
53 |
54 | You can also create the document in the Futon interface itself:
55 |
56 | ![New doc button][]
57 |
58 | ![Blogger DDoc][]
59 |
60 | From now on, you can give users the role `"blogger"`, so they can add/modify/remove documents. (Only admins can change someone's roles.)
61 |
62 | ![Blogger][]
63 |
64 | Admins can also modify documents, but they are the only ones who can change the security settings.
65 |
66 | Everyone else will get an error if they try to write (but not if they try to read).
67 |
68 | $ curl -X POST http://blogger1:blogger1@localhost:5984/mydb -H 'content-type:application/json' -d '{"some" : "doc"}'
69 | {"ok":true,"id":"ef24bec394e1a45f32ea917121002282","rev":"1-65c2325c1ab76e8279e6c2e3abc1da69"}
70 | $ curl -X POST http://foobar:foobar@localhost:5984/mydb -H 'content-type:application/json' -d '{"some" : "doc"}'
71 | {"error":"forbidden","reason":"Only users with role blogger or an admin can modify this database."}
72 |
73 | ### Everybody can read, only some can write (some things)
74 |
75 | * Example: Twitter
76 |
77 | In this example, all tweets are public, but everybody can only create/edit/delete their own tweets.
78 |
79 | Very similar to the above, we'll create a *design doc* with a `validate_doc_update` function, but this time we'll also ensure that every document contains a `user` field, and that the `user` field matches the name of the user who's modifying it:
80 |
81 | ```js
82 | function(newDoc, oldDoc, userCtx) {
83 | if (userCtx.roles.indexOf('_admin') === -1 && newDoc.user !== userCtx.name) {
84 | throw({forbidden : "doc.user must be the same as your username."});
85 | }
86 | }
87 |
88 | ```
89 |
90 | Here's a `curl` command you can use:
91 |
92 | curl -X POST http://admin:password@localhost:5984/mydb \
93 | -H 'content-type:application/json' \
94 | -d $'{"_id":"_design/only_correct_user","validate_doc_update":"function (newDoc, oldDoc, userCtx) {\\nif (userCtx.roles.indexOf(\'_admin\') === -1 && newDoc.user !== userCtx.name) {\\nthrow({forbidden : \\"doc.user must be the same as your username.\\"});\\n}\\n}"}'
95 |
96 | In the above command, you will need to change **admin**/**password** (admin and password), **localhost:5984** (your Couch URL), **mydb** (your database), and **only_correct_user** (name of the design doc, can be whatever you want).
97 |
98 | You can also use the Futon UI to do this. See the "blogger" example above for details.
99 |
100 | ### Some people can read and write everything
101 | * Example: a shared company wiki
102 |
103 | #### Howto
104 |
105 | Create a new database, then click the "Security" button:
106 |
107 | ![security button][]
108 |
109 | Set a new role as the read/write role. We'll call this one `"employee"`:
110 |
111 | ![employee][]
112 |
113 | In this scheme, only admins can change the security settings, but any user with the role `"employee"` can view or add/modify/delete documents. The database is not public; only valid users with the role `"employee"` can read from it.
114 |
115 | See the "blogger" example above for how to set roles.
116 |
117 | ### Some people can read (some docs), some people can write (those same docs)
118 |
119 | * Example: A private file locker
120 |
121 | #### Howto
122 |
123 | The standard practice for this is to set up **one database per user**. Don't be scared: databases are cheap, and Cloudant says [100k databases per account is not uncommon][cloudant-100k].
124 |
125 | Alternatively, if you have users who belong to multiple groups, and each group has a set of documents, then you should use a **one database per role** setup, with CouchDB's [roles system](http://docs.couchdb.org/en/latest/api/database/security.html?highlight=roles).
126 |
127 | Then, you just need to set the database to be read-only/write-only for people with the correct user name (or correct role), using the [`db/_security` API](http://docs.couchdb.org/en/latest/api/database/security.html). (See screenshots above for manual steps.)
128 |
129 | There are a few different ways to accomplish this, and unfortunately you can't do it with CouchDB alone (as of this writing). But here are a few different third-party options you can try:
130 |
131 | ### [couch_peruser configuration](http://docs.couchdb.org/en/2.1.0/config/couch-peruser.html)
132 |
133 | As of CouchDB 2.1, CouchDB supports couch_peruser configuration options.
134 |
135 | #### [CouchPerUser](https://github.com/etrepum/couchperuser)
136 |
137 | Native CouchDB Erlang plugin that automatically creates one database per user. The database name is just a hex-encoded hash of the user name, and it completely predictable.
138 |
139 | **Update!** This is now much easier to use, because there are [prebuilt Docker images](https://hub.docker.com/r/klaemo/couchdb/) containing the `CouchPerUser` plugin.
140 |
141 | #### [couchdb-dbperuser-provisioning](https://github.com/pegli/couchdb-dbperuser-provisioning)
142 |
143 | Node.js daemon to do the same as above.
144 |
145 | #### [CouchDB-Selfservice](https://github.com/ocasta/CouchDB-Selfservice)
146 |
147 | Python process that gives you a URL to use when registering users, and creates a database for that user on registration.
148 |
149 | #### [PHP-on-Couch](https://github.com/dready92/PHP-on-Couch)
150 |
151 | PHP library that provides some sugar over the CouchDB API, e.g. for admin stuff.
152 |
153 | #### [Hoodie](http://hood.ie)
154 |
155 | Batteries-included no-backend framework. Currently (as of January 2016) being [ported to use PouchDB](https://github.com/hoodiehq/hoodie-client-store).
156 |
157 | #### [PouchBase (deprecated)](https://github.com/pouchdb/pouchbase/) (formerly pouch.host)
158 |
159 | (Work in progress as of January 2015.) Hosted PouchDB Server with per-user read-write access.
160 |
161 | ### Everybody has to be logged in to do anything
162 |
163 | * Example: Medical healthcare records
164 |
165 | #### Howto
166 |
167 | The highest level of security offered by CouchDB. No requests *whatsoever* are allowed from unauthenticated users.
168 |
169 | First, ensure that at least one CouchDB user has been created (if you've [disabled admin party](#first-step-disable-the-admin-party), you'll already have at least one admin user). Next, if you're using CORS, ensure the `cors.headers` array contains `authorization` (this should already be set if you've followed [CouchDB setup][couchdb setup]). Finally, set `httpd.require_valid_user` to `true`.
170 |
171 | To prevent browser HTTP basic authentication modal dialogs of ye olde times, we have to be subtle in the way we use PouchDB. To prevent a rogue unauthenticated request to CouchDB (used to [check whether the remote DB exists][skipsetup]), pass `skip_setup: true` in Pouch's constructor options. Secondly, to authenticate the request against `_session`, add the HTTP basic authorization header to `db.login()`'s [AJAX options][api].
172 |
173 | Example usage:
174 |
175 | ```js
176 | var user = {
177 | name: 'admin',
178 | password: 'admin'
179 | };
180 |
181 | var pouchOpts = {
182 | skip_setup: true
183 | };
184 |
185 | var ajaxOpts = {
186 | ajax: {
187 | headers: {
188 | Authorization: 'Basic ' + window.btoa(user.name + ':' + user.password)
189 | }
190 | }
191 | };
192 |
193 | var db = new PouchDB('http://localhost:5984/test', pouchOpts);
194 |
195 | db.login(user.name, user.password, ajaxOpts).then(function() {
196 | return db.allDocs();
197 | }).then(function(docs) {
198 | console.log(docs);
199 | }).catch(function(error) {
200 | console.error(error);
201 | });
202 | ```
203 |
204 | [couchdb setup]: ../README.md#couchdb-setup
205 | [api]: ./api.md
206 |
207 | [admin party]: https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/master/docs/admin_party.png
208 | [blogger]: https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/master/docs/blogger.png
209 | [blogger ddoc]: https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/master/docs/blogger_ddoc.png
210 | [new doc button]: https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/master/docs/new_doc_button.png
211 | [security button]: https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/master/docs/security_button.png
212 | [employee]: https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/master/docs/employee.png
213 | [cloudant-100k]: https://mail-archives.apache.org/mod_mbox/couchdb-user/201401.mbox/%3C52CEB873.7080404@ironicdesign.com%3E
214 | [couchperuser-gist]: https://gist.github.com/nolanlawson/9676093
215 | [skipsetup]: https://github.com/pouchdb/pouchdb/blob/e78a30f8a548340335e28efb827cddfcd96d0482/lib/adapters/http.js#L157
216 |
--------------------------------------------------------------------------------
/docs/sauce_labs.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/sauce_labs.png
--------------------------------------------------------------------------------
/docs/security_button.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pouchdb-community/pouchdb-authentication/113bdd9d811ed679b7302850a3878da0c9420e66/docs/security_button.png
--------------------------------------------------------------------------------
/docs/setup.md:
--------------------------------------------------------------------------------
1 | Setup
2 | ---------
3 |
4 | ### Requirements
5 |
6 | - CouchDB v1.3.0+
7 | - PouchDB v2.0.0+
8 |
9 | ### PouchDB setup
10 |
11 | Bower:
12 |
13 | bower install pouchdb
14 | bower install pouchdb-authentication
15 |
16 | Browserify :
17 |
18 | npm install pouchdb --save
19 | npm install pouchdb-authentication --save
20 |
21 | ```javascript
22 | var PouchDB = require("pouchdb");
23 | PouchDB.plugin(require('pouchdb-authentication'));
24 | ```
25 |
26 | Static :
27 |
28 | Or, just grab the latest `pouchdb.authentication.min.js` from [the releases page](https://github.com/pouchdb-community/pouchdb-authentication/releases) and declare it after PouchDB:
29 |
30 | ```html
31 |
32 |
33 | ```
34 |
35 | ### CouchDB setup
36 |
37 | Install CouchDB:
38 |
39 | ```
40 | sudo apt-get install couchdb # debian, ubuntu, etc.
41 | brew install couchdb # mac
42 | ```
43 |
44 | Next, set up CORS so that PouchDB can access your CouchDB from any URL. For convenience we'll use [add-cors-to-couchdb](https://github.com/pouchdb/add-cors-to-couchdb).
45 |
46 | npm install -g add-cors-to-couchdb # may require sudo
47 | add-cors-to-couchdb #
48 |
49 |
50 | In a production environment, don't forget to set up [SSL](https://wiki.apache.org/couchdb/How_to_enable_SSL).
51 |
52 | ### PouchDB setup
53 |
54 | Create a `PouchDB` attached to an HTTP backend. This is the one you'll use for `pouchdb-authentication` stuff.
55 |
56 | ```js
57 | var db = new PouchDB('http://localhost:5984/mydb', {skip_setup: true});
58 | ```
59 |
60 | *(Note that the users are shared across the entire CouchDB instance, not just `mydb`. Also, the `skip_setup` is to prevent PouchDB from doing any HTTP requests to the server while we're not logged in, which would cause a modal authentication popup.)*
61 |
62 | Of course, you'll probably want to sync that database with a local one:
63 |
64 | ```js
65 | var local = new PouchDB('local_db');
66 | local.sync(db, {live: true, retry: true}).on('error', console.log.bind(console));
67 | ```
68 |
69 | But the `pouchdb-authentication` API will operate on your remote `PouchDB` object, not your local one.
70 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "pouchdb-authentication",
3 | "version": "1.1.3",
4 | "description": "PouchDB Authentication",
5 | "keywords": [
6 | "pouch",
7 | "pouchdb",
8 | "authentication",
9 | "couch",
10 | "couchdb"
11 | ],
12 | "bugs": {
13 | "url": "https://github.com/pouchdb-community/pouchdb-authentication/issues"
14 | },
15 | "license": "Apache-2.0",
16 | "author": {
17 | "name": "Nolan Lawson",
18 | "email": "nolan@nolanlawson.com",
19 | "url": "https://nolanlawson.com/"
20 | },
21 | "contributors": [
22 | {
23 | "name": "Didier Villevalois",
24 | "email": "ptitjes@free.fr"
25 | }
26 | ],
27 | "files": [
28 | "dist",
29 | "lib",
30 | "types/index.d.ts"
31 | ],
32 | "main": "lib/index.js",
33 | "jsnext:main": "lib/index.es.js",
34 | "module": "lib/index.es.js",
35 | "types": "types/index.d.ts",
36 | "repository": {
37 | "type": "git",
38 | "url": "git@github.com:pouchdb-community/pouchdb-authentication.git"
39 | },
40 | "scripts": {
41 | "clean": "rimraf lib dist && mkdirp lib dist",
42 | "rollup-cjs": "rollup -c config/rollup.config.cjs.js && rollup -c config/rollup.config.browser.cjs.js",
43 | "rollup-es": "rollup -c config/rollup.config.es.js && rollup -c config/rollup.config.browser.es.js",
44 | "rollup": "npm-run-all --parallel rollup-cjs rollup-es",
45 | "browserify": "browserify -t brfs -p bundle-collapser/plugin -s PouchAuthentication lib/index.browser.js > dist/pouchdb.authentication.js",
46 | "minify": "uglifyjs -mc < dist/pouchdb.authentication.js > dist/pouchdb.authentication.min.js",
47 | "build": "npm-run-all clean rollup browserify minify",
48 | "prepublishOnly": "npm run build",
49 | "lint": "eslint bin/ src/ test/",
50 | "dev": "npm run test-local",
51 | "test": "npm run rollup-cjs && node bin/run-test.js",
52 | "test-local": "CLIENT=local npm run test",
53 | "test-node": "CLIENT=node npm run test",
54 | "test-phantom": "CLIENT=phantom npm run test",
55 | "test-types": "tsc --noEmit -p types",
56 | "release": "standard-version"
57 | },
58 | "dependencies": {
59 | "inherits": "2.0.3",
60 | "pouchdb-utils": "~7.0.0",
61 | "pouchdb-fetch": "^7.0.0"
62 | },
63 | "devDependencies": {
64 | "@types/pouchdb-core": "^7.0.2",
65 | "add-cors-to-couchdb": "0.0.6",
66 | "brfs": "^1.4.3",
67 | "browserify": "^16.1.0",
68 | "bundle-collapser": "^1.3.0",
69 | "chai": "3.5.0",
70 | "chai-as-promised": "5.3.0",
71 | "eslint": "^4.6.1",
72 | "istanbul": "^0.4.5",
73 | "karma": "^2.0.0",
74 | "karma-browserify": "^5.1.2",
75 | "karma-chai": "^0.1.0",
76 | "karma-mocha": "^1.3.0",
77 | "karma-mocha-reporter": "^2.2.5",
78 | "karma-phantomjs-launcher": "^1.0.4",
79 | "karma-sauce-launcher": "^1.2.0",
80 | "mkdirp": "^0.5.1",
81 | "mocha": "^5.0.0",
82 | "npm-run-all": "^3.1.2",
83 | "pouchdb-browser": "^7.0.0",
84 | "pouchdb-node": "^7.0.0",
85 | "pouchdb-server": "^4.0.0",
86 | "promise-polyfill": "^8.1.0",
87 | "rimraf": "^2.5.4",
88 | "rollup": "^0.57.1",
89 | "rollup-plugin-buble": "^0.19.2",
90 | "rollup-plugin-commonjs": "^9.1.0",
91 | "rollup-plugin-inject": "^2.0.0",
92 | "rollup-plugin-node-resolve": "^3.0.0",
93 | "rollup-plugin-replace": "^2.0.0",
94 | "standard-version": "^4.2.0",
95 | "typescript": "^2.6.2",
96 | "uglify-js": "^3.1.9",
97 | "watchify": "^3.9.0",
98 | "whatwg-fetch": "^3.0.0"
99 | },
100 | "// greenkeeper": [
101 | "// chai-as-promised is pinned because of breaking changes in 6.0.0 which make phantomjs crash"
102 | ],
103 | "greenkeeper": {
104 | "ignore": [
105 | "chai-as-promised"
106 | ]
107 | },
108 | "standard-version": {
109 | "scripts": {
110 | "postbump": "git checkout -- bower.json"
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/src/admins.js:
--------------------------------------------------------------------------------
1 | import { AuthError, getConfigUrl, fetchJSON, toCallback } from './utils';
2 |
3 | import { assign } from 'pouchdb-utils';
4 |
5 | var getMembership = toCallback(function (opts) {
6 | var db = this;
7 | if (typeof opts === 'undefined') {
8 | opts = {};
9 | }
10 |
11 | var path = '/_membership';
12 | var ajaxOpts = assign({
13 | method: 'GET',
14 | }, opts.ajax || {});
15 | return fetchJSON(db.fetch, path, ajaxOpts);
16 | });
17 |
18 | var getNodeName = function (db, opts) {
19 | return db.getMembership(opts).then(
20 | membership => {
21 | // Some couchdb-2.x-like server
22 | return membership.all_nodes[0];
23 | },
24 | error => {
25 | if (error.error !== 'illegal_database_name') {
26 | throw error;
27 | } else {
28 | // Some couchdb-1.x-like server
29 | return undefined;
30 | }
31 | }
32 | );
33 | };
34 |
35 | var signUpAdmin = toCallback(function (username, password, opts) {
36 | var db = this;
37 | if (typeof opts === 'undefined') {
38 | opts = {};
39 | }
40 | if (['http', 'https'].indexOf(db.type()) === -1) {
41 | return Promise.reject(new AuthError('This plugin only works for the http/https adapter. ' +
42 | 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
43 | } else if (!username) {
44 | return Promise.reject(new AuthError('You must provide a username'));
45 | } else if (!password) {
46 | return Promise.reject(new AuthError('You must provide a password'));
47 | }
48 |
49 | return getNodeName(db, opts).then(nodeName => {
50 | var configUrl = getConfigUrl(nodeName);
51 | var url = (opts.configUrl || configUrl) + '/admins/' + encodeURIComponent(username);
52 | var ajaxOpts = assign({
53 | method: 'PUT',
54 | body: password
55 | }, opts.ajax || {});
56 | return fetchJSON(db.fetch, url, ajaxOpts);
57 | });
58 | });
59 |
60 | var deleteAdmin = toCallback(function (username, opts) {
61 | var db = this;
62 | if (typeof opts === 'undefined') {
63 | opts = {};
64 | }
65 | if (['http', 'https'].indexOf(db.type()) === -1) {
66 | return Promise.reject(new AuthError('This plugin only works for the http/https adapter. ' +
67 | 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
68 | } else if (!username) {
69 | return Promise.reject(new AuthError('You must provide a username'));
70 | }
71 |
72 | return getNodeName(db, opts).then(nodeName => {
73 | var configUrl = getConfigUrl(nodeName);
74 | var url = (opts.configUrl || configUrl) + '/admins/' + encodeURIComponent(username);
75 | var ajaxOpts = assign({
76 | method: 'DELETE',
77 | processData: false
78 | }, opts.ajax || {});
79 | return fetchJSON(db.fetch, url, ajaxOpts);
80 | });
81 | });
82 |
83 | export { getMembership, deleteAdmin, signUpAdmin };
84 |
--------------------------------------------------------------------------------
/src/authentication.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import { AuthError, fetchJSON, toCallback } from './utils';
4 | import { assign } from 'pouchdb-utils';
5 |
6 | var sessionPath = '/_session';
7 |
8 | var logIn = toCallback(function (username, password, opts) {
9 | var db = this;
10 | if (typeof opts === 'undefined') {
11 | opts = {};
12 | }
13 | if (['http', 'https'].indexOf(db.type()) === -1) {
14 | return Promise.reject(new AuthError('this plugin only works for the http/https adapter'));
15 | }
16 |
17 | if (!username) {
18 | return Promise.reject(new AuthError('you must provide a username'));
19 | } else if (!password) {
20 | return Promise.reject(new AuthError('you must provide a password'));
21 | }
22 |
23 | var path = sessionPath;
24 | var ajaxOpts = assign({
25 | method: 'POST',
26 | body: {name: username, password: password},
27 | }, opts.ajax || {});
28 | return fetchJSON(db.fetch, path, ajaxOpts);
29 | });
30 |
31 | var logOut = toCallback(function (opts) {
32 | var db = this;
33 | if (typeof opts === 'undefined') {
34 | opts = {};
35 | }
36 |
37 | var path = sessionPath;
38 | var ajaxOpts = assign({
39 | method: 'DELETE'
40 | }, opts.ajax || {});
41 | return fetchJSON(db.fetch, path, ajaxOpts);
42 | });
43 |
44 | var getSession = toCallback(function (opts) {
45 | var db = this;
46 | if (typeof opts === 'undefined') {
47 | opts = {};
48 | }
49 |
50 | var path = sessionPath;
51 | var ajaxOpts = assign({
52 | method: 'GET'
53 | }, opts.ajax || {});
54 | return fetchJSON(db.fetch, path, ajaxOpts);
55 | });
56 |
57 | export { logIn, logOut, getSession };
58 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import { deleteAdmin, getMembership, signUpAdmin } from "./admins";
4 | import { getSession, logIn, logOut } from "./authentication";
5 | import {
6 | changePassword,
7 | changeUsername,
8 | deleteUser,
9 | getUser,
10 | putUser,
11 | signUp,
12 | } from "./users";
13 |
14 | var plugin = {};
15 |
16 | plugin.login = logIn;
17 | plugin.logIn = logIn;
18 | plugin.logout = logOut;
19 | plugin.logOut = logOut;
20 | plugin.getSession = getSession;
21 |
22 | plugin.getMembership = getMembership;
23 | plugin.signUpAdmin = signUpAdmin;
24 | plugin.deleteAdmin = deleteAdmin;
25 |
26 | plugin.signup = signUp;
27 | plugin.signUp = signUp;
28 | plugin.getUser = getUser;
29 | plugin.putUser = putUser;
30 | plugin.deleteUser = deleteUser;
31 | plugin.changePassword = changePassword;
32 | plugin.changeUsername = changeUsername;
33 |
34 | if (typeof window !== 'undefined' && window.PouchDB) {
35 | window.PouchDB.plugin(plugin);
36 | }
37 |
38 | export default plugin;
39 |
--------------------------------------------------------------------------------
/src/users.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import { AuthError, fetchJSON, toCallback } from './utils';
4 | import { assign, clone } from 'pouchdb-utils';
5 |
6 | var usersPath = '/_users';
7 |
8 | function updateUser(db, user, opts) {
9 | var reservedWords = [
10 | '_id',
11 | '_rev',
12 | 'name',
13 | 'type',
14 | 'roles',
15 | 'password',
16 | 'password_scheme',
17 | 'iterations',
18 | 'derived_key',
19 | 'salt',
20 | ];
21 |
22 | if (opts.metadata) {
23 | for (var key in opts.metadata) {
24 | if (opts.metadata.hasOwnProperty(key) && reservedWords.indexOf(key) !== -1) {
25 | return Promise.reject(new AuthError('cannot use reserved word in metadata: "' + key + '"'));
26 | }
27 | }
28 | user = assign(user, opts.metadata);
29 | }
30 |
31 | if (opts.roles) {
32 | user = assign(user, {roles: opts.roles});
33 | }
34 | var path = usersPath + '/' + encodeURIComponent(user._id);
35 | var ajaxOpts = assign({
36 | method: 'PUT',
37 | body: user
38 | }, opts.ajax || {});
39 |
40 | return fetchJSON(db.fetch, path, ajaxOpts);
41 | }
42 |
43 | var signUp = toCallback(function (username, password, opts) {
44 | var db = this;
45 | if (typeof opts === 'undefined') {
46 | opts = {};
47 | }
48 | if (['http', 'https'].indexOf(db.type()) === -1) {
49 | return Promise.reject(new AuthError('This plugin only works for the http/https adapter. ' +
50 | 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
51 | } else if (!username) {
52 | return Promise.reject(new AuthError('You must provide a username'));
53 | } else if (!password) {
54 | return Promise.reject(new AuthError('You must provide a password'));
55 | }
56 |
57 | var userId = 'org.couchdb.user:' + username;
58 | var user = {
59 | name: username,
60 | password: password,
61 | roles: [],
62 | type: 'user',
63 | _id: userId,
64 | };
65 |
66 | return updateUser(db, user, opts);
67 | });
68 |
69 | var getUser = toCallback(function (username, opts) {
70 | var db = this;
71 | if (typeof opts === 'undefined') {
72 | opts = {};
73 | }
74 | if (!username) {
75 | return Promise.reject(new AuthError('you must provide a username'));
76 | }
77 |
78 | var path = usersPath + '/' + encodeURIComponent('org.couchdb.user:' + username);
79 | var ajaxOpts = assign({
80 | method: 'GET'
81 | }, opts.ajax || {});
82 | return fetchJSON(db.fetch, path, ajaxOpts).then(x => { console.log(x); return x});
83 | });
84 |
85 | var putUser = toCallback(function (username, opts) {
86 | var db = this;
87 | if (typeof opts === 'undefined') {
88 | opts = {};
89 | }
90 | if (['http', 'https'].indexOf(db.type()) === -1) {
91 | return Promise.reject(new AuthError('This plugin only works for the http/https adapter. ' +
92 | 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
93 | } else if (!username) {
94 | return Promise.reject(new AuthError('You must provide a username'));
95 | }
96 |
97 | return db.getUser(username, opts).then(user => updateUser(db, user, opts));
98 | });
99 |
100 | var deleteUser = toCallback(function (username, opts) {
101 | var db = this;
102 | if (typeof opts === 'undefined') {
103 | opts = {};
104 | }
105 | if (['http', 'https'].indexOf(db.type()) === -1) {
106 | return Promise.reject(new AuthError('This plugin only works for the http/https adapter. ' +
107 | 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
108 | } else if (!username) {
109 | return Promise.reject(new AuthError('You must provide a username'));
110 | }
111 |
112 | return db.getUser(username, opts).then(user => {
113 | var path = usersPath + '/' + encodeURIComponent(user._id) + '?rev=' + user._rev;
114 | var ajaxOpts = assign({
115 | method: 'DELETE'
116 | }, opts.ajax || {});
117 | return fetchJSON(db.fetch, path, ajaxOpts);
118 | });
119 | });
120 |
121 | var changePassword = toCallback(function (username, password, opts) {
122 | var db = this;
123 | if (typeof opts === 'undefined') {
124 | opts = {};
125 | }
126 | if (['http', 'https'].indexOf(db.type()) === -1) {
127 | return Promise.reject(new AuthError('This plugin only works for the http/https adapter. ' +
128 | 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
129 | } else if (!username) {
130 | return Promise.reject(new AuthError('You must provide a username'));
131 | } else if (!password) {
132 | return Promise.reject(new AuthError('You must provide a password'));
133 | }
134 | return db.getUser(username, opts).then(user => {
135 | user.password = password;
136 | var path = usersPath + '/' + encodeURIComponent(user._id);
137 | var ajaxOpts = assign({
138 | method: 'PUT',
139 | body: user,
140 | }, opts.ajax || {});
141 |
142 | return fetchJSON(db.fetch, path, ajaxOpts);
143 | });
144 | });
145 |
146 | var changeUsername = toCallback(function (oldUsername, newUsername, opts) {
147 | var db = this;
148 | var USERNAME_PREFIX = 'org.couchdb.user:';
149 | var updateUser = function (user, opts) {
150 | var path = usersPath + '/' + encodeURIComponent(user._id);
151 | var updateOpts = assign({
152 | method: 'PUT',
153 | body: user
154 | }, opts.ajax);
155 | return fetchJSON(db.fetch, path, updateOpts);
156 | };
157 | if (typeof opts === 'undefined') {
158 | opts = {};
159 | }
160 | opts.ajax = opts.ajax || {};
161 | if (['http', 'https'].indexOf(db.type()) === -1) {
162 | return Promise.reject(new AuthError('This plugin only works for the http/https adapter. ' +
163 | 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
164 | }
165 | if (!newUsername) {
166 | return Promise.reject(new AuthError('You must provide a new username'));
167 | }
168 | if (!oldUsername) {
169 | return Promise.reject(new AuthError('You must provide a username to rename'));
170 | }
171 |
172 | return db.getUser(newUsername, opts)
173 | .then(function () {
174 | var error = new AuthError('user already exists');
175 | error.taken = true;
176 | throw error;
177 | }, function () {
178 | return db.getUser(oldUsername, opts);
179 | })
180 | .then(function (user) {
181 | var newUser = clone(user);
182 | delete newUser._rev;
183 | newUser._id = USERNAME_PREFIX + newUsername;
184 | newUser.name = newUsername;
185 | newUser.roles = opts.roles || user.roles || {};
186 | return updateUser(newUser, opts).then(function () {
187 | user._deleted = true;
188 | return updateUser(user, opts);
189 | });
190 | });
191 | });
192 |
193 | export {
194 | signUp,
195 | getUser,
196 | putUser,
197 | deleteUser,
198 | changePassword,
199 | changeUsername,
200 | };
201 |
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import inherits from 'inherits';
4 | import { Headers } from 'pouchdb-fetch';
5 |
6 |
7 | function getConfigUrl(nodeName) {
8 | return (nodeName ? '/_node/' + nodeName : '') + '/_config';
9 | }
10 |
11 | function wrapError(err) {
12 | if (err.name === 'unknown_error') {
13 | err.message = (err.message || '') +
14 | ' Unknown error! Did you remember to enable CORS?';
15 | }
16 | throw err;
17 | }
18 |
19 | // Wrapper around the fetch API to send and receive JSON objects
20 | // Similar to fetchJSON in pouchdb-adapter-http, but both functions are private.
21 | // Consider extracting them to a common library.
22 | function fetchJSON(dbFetch, path, options) {
23 | options = options || {}
24 |
25 | if (options.body) {
26 | options.body = JSON.stringify(options.body);
27 | }
28 |
29 | options.headers = options.headers || new Headers();
30 | options.headers.set('Content-Type', 'application/json');
31 | options.headers.set('Accept', 'application/json');
32 |
33 | return dbFetch(path, options).then(response => {
34 | if (response.ok) {
35 | return response.json();
36 | } else {
37 | return response.json().then(responseError => {
38 | throw responseError;
39 | });
40 | }
41 | }).catch(wrapError);
42 | }
43 |
44 | // toCallback takes a function that returns a promise,
45 | // and returns a function that can be used with a callback as the last argument,
46 | // but still retains the ability to be used without a callback and return a promise.
47 | // (Roughly speaking, the opposite of `toPromise` from pouchdb-utils,
48 | // but more suited for `fetch`, that returns a promise by default.)
49 | function toCallback(func) {
50 | return function (...args) {
51 | if (typeof args[-1] === 'function') {
52 | var callback = args[-1];
53 | return func.apply(this, args.slice(0, -2)).then(
54 | res => callback(null, res),
55 | err => callback(err)
56 | );
57 | } else {
58 | return func.apply(this, args);
59 | }
60 | };
61 | }
62 |
63 | function AuthError(message) {
64 | this.status = 400;
65 | this.name = 'authentication_error';
66 | this.message = message;
67 | this.error = true;
68 | try {
69 | Error.captureStackTrace(this, AuthError);
70 | } catch (e) {}
71 | }
72 |
73 | inherits(AuthError, Error);
74 |
75 | export {
76 | AuthError,
77 | getConfigUrl,
78 | fetchJSON,
79 | toCallback
80 | };
81 |
--------------------------------------------------------------------------------
/test/test-pouchdb.js:
--------------------------------------------------------------------------------
1 | if (typeof window !== 'undefined') {
2 | // polyfill PhantomJS
3 | require('whatwg-fetch');
4 | if (!window.Promise) {
5 | window.Promise = require('promise-polyfill');
6 | }
7 |
8 | module.exports = require('pouchdb-browser');
9 | } else {
10 | module.exports = require('pouchdb-node');
11 | }
12 |
--------------------------------------------------------------------------------
/test/test-utils.js:
--------------------------------------------------------------------------------
1 | var PouchDB = require('./test-pouchdb');
2 |
3 | var getConfig = function () {
4 | return typeof window !== 'undefined' ? window.__karma__.config : global.__testConfig__;
5 | }
6 |
7 | module.exports.getConfig = getConfig;
8 |
9 | module.exports.ensureUsersDatabaseExists = function () {
10 | var usersDb = new PouchDB(getConfig().serverHost + '/_users');
11 | return usersDb.info();
12 | };
13 |
14 | module.exports.deleteUsers = function (users) {
15 | var usersDb = new PouchDB(getConfig().serverHost + '/_users');
16 | return usersDb.allDocs({
17 | include_docs: true,
18 | keys: users.map(function (user) {
19 | return 'org.couchdb.user:' + user;
20 | }),
21 | }).then(function (res) {
22 | var rows = res.rows.filter(function (row) {
23 | return row.doc;
24 | });
25 | var docs = rows.map(function (row) {
26 | row.doc._deleted = true;
27 | return row.doc;
28 | });
29 | return usersDb.bulkDocs({docs: docs});
30 | });
31 | };
32 |
--------------------------------------------------------------------------------
/test/test.admins.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var PouchDB = require('./test-pouchdb');
4 | var Authentication = require('../lib');
5 | PouchDB.plugin(Authentication);
6 |
7 | var utils = require('./test-utils');
8 | var chai = require('chai');
9 | var should = chai.should();
10 |
11 | var serverHost = utils.getConfig().serverHost;
12 |
13 | describe('admins', function () {
14 |
15 | var dbHost = serverHost;
16 | var dbName = dbHost + '/testdb';
17 |
18 | var db;
19 |
20 | beforeEach(function () {
21 | db = new PouchDB(dbName);
22 | return utils.ensureUsersDatabaseExists();
23 | });
24 |
25 | afterEach(function () {
26 | return db.logOut().then(function () {
27 | return db.destroy();
28 | });
29 | });
30 |
31 | it('Create and delete admin', function () {
32 | return testCreateDeleteAdmin({});
33 | });
34 |
35 | it('Create and delete admin with config url', function () {
36 | return db.getMembership().then(function (membership) {
37 | // Some couchdb-2.x-like server
38 | return membership.all_nodes[0];
39 | }).catch(function () {
40 | // Some couchdb-1.x-like server
41 | return undefined;
42 | }).then(function (nodeName) {
43 | var opts = {
44 | configUrl: (nodeName ? '/_node/' + nodeName : '') + '/_config',
45 | };
46 |
47 | return testCreateDeleteAdmin(opts);
48 | });
49 | });
50 |
51 | function testCreateDeleteAdmin(opts) {
52 | return db.signUpAdmin('anna', 'secret', opts).then(function (res) {
53 | should.exist(res);
54 |
55 | return db.logIn('anna', 'secret').then(function (res) {
56 | res.ok.should.equal(true);
57 |
58 | return db.deleteAdmin('anna', opts).then(function (res) {
59 | should.exist(res);
60 |
61 | return db.logOut().then(function () {
62 | return db.logIn('anna', 'secret').then(function () {
63 | should.fail('shouldn\'t have worked');
64 | }, function (err) {
65 | should.exist(err);
66 | err.error.should.equal('unauthorized');
67 | err.reason.should.equal('Name or password is incorrect.');
68 | });
69 | });
70 | });
71 | });
72 | });
73 | }
74 | });
75 |
--------------------------------------------------------------------------------
/test/test.authentication.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var PouchDB = require('./test-pouchdb');
4 | var Authentication = require('../lib');
5 | PouchDB.plugin(Authentication);
6 |
7 | var utils = require('./test-utils');
8 | var chai = require('chai');
9 | var should = chai.should();
10 |
11 | var serverHost = utils.getConfig().serverHost;
12 |
13 | describe('authentication', function () {
14 |
15 | var dbName = serverHost + '/testdb';
16 | var users = ['aquaman'];
17 |
18 | var db;
19 |
20 | beforeEach(function () {
21 | db = new PouchDB(dbName);
22 | return utils.ensureUsersDatabaseExists();
23 | });
24 |
25 | afterEach(function () {
26 | return db.logout().then(function () {
27 | return db.destroy().then(function () {
28 | // remove the fake users, hopefully we're in the admin party
29 | return utils.deleteUsers(users);
30 | });
31 | });
32 | });
33 |
34 | it('Test login/logout', function () {
35 | return db.signup('aquaman', 'sleeps_with_fishes').then(function () {
36 | return db.getSession();
37 | }).then(function (res) {
38 | should.equal(res.userCtx.name, null);
39 | return db.login('aquaman', 'sleeps_with_fishes');
40 | }).then(function (res) {
41 | res.ok.should.equal(true);
42 | return db.getSession();
43 | }).then(function (res) {
44 | res.userCtx.name.should.equal('aquaman');
45 | return db.logout();
46 | }).then(function () {
47 | return db.getSession();
48 | }).then(function (res) {
49 | should.equal(res.userCtx.name, null);
50 | });
51 | });
52 | });
53 |
--------------------------------------------------------------------------------
/test/test.issue.109.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var PouchDB = require('./test-pouchdb');
4 | var Authentication = require('../lib');
5 | PouchDB.plugin(Authentication);
6 |
7 | var utils = require('./test-utils');
8 | var chai = require('chai');
9 | chai.should();
10 |
11 | var serverHost = utils.getConfig().serverHost;
12 |
13 | describe('issue-109', function () {
14 |
15 | var dbName = serverHost + '/testdb';
16 |
17 | var db;
18 |
19 | beforeEach(function () {
20 | db = new PouchDB(dbName);
21 | return utils.ensureUsersDatabaseExists().then(function () {
22 | return db.signUpAdmin('anna', 'secret');
23 | }).then(function () {
24 | return db.signUp('spiderman', 'will-forget');
25 | });
26 | });
27 |
28 | afterEach(function () {
29 | return db.logIn('anna', 'secret').then(function () {
30 | return db.deleteUser('spiderman');
31 | }).then(function () {
32 | return db.deleteAdmin('anna');
33 | }).then(function () {
34 | return db.logOut();
35 | }).then(function () {
36 | return db.destroy();
37 | });
38 | });
39 |
40 | it('Test admin change user password with cookie authentication', function () {
41 | return db.logIn('anna', 'secret').then(function () {
42 | return db.changePassword('spiderman', 'will-remember');
43 | }).then(function (res) {
44 | res.ok.should.equal(true);
45 | }).then(function () {
46 | return db.logIn('spiderman', 'will-remember');
47 | }).then(function (res) {
48 | res.ok.should.equal(true);
49 | }).then(function () {
50 | return db.logOut();
51 | });
52 | });
53 |
54 | it('Test admin change user password with basic authentication', function () {
55 | var dbNameWithAuth = dbName.replace('http://', 'http://anna:secret@');
56 | var dbWithBasicAuth = new PouchDB(dbNameWithAuth, {skip_setup: true});
57 | return dbWithBasicAuth.changePassword('spiderman', 'will-remember').then(function (res) {
58 | res.ok.should.equal(true);
59 | }).then(function () {
60 | return db.logIn('spiderman', 'will-remember');
61 | }).then(function (res) {
62 | res.ok.should.equal(true);
63 | }).then(function () {
64 | return db.logOut();
65 | });
66 | });
67 | });
68 |
--------------------------------------------------------------------------------
/test/test.issue.204.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var PouchDB = require('./test-pouchdb');
4 | var Authentication = require('../lib');
5 | PouchDB.plugin(Authentication);
6 |
7 | var utils = require('./test-utils');
8 | var chai = require('chai');
9 | chai.should();
10 |
11 | var serverHost = utils.getConfig().serverHost;
12 |
13 | describe('issue-204', function () {
14 |
15 | var dbName = serverHost + '/testdb';
16 |
17 | var db;
18 |
19 | beforeEach(function () {
20 | db = new PouchDB(dbName);
21 | return utils.ensureUsersDatabaseExists().then(function () {
22 | return db.signUpAdmin('anna', 'secret');
23 | }).then(function () {
24 | return db.signup('spiderman', 'will-remember');
25 | });
26 | });
27 |
28 | afterEach(function () {
29 | return db.logIn('anna', 'secret').then(function () {
30 | return db.deleteUser('spiderman');
31 | }).then(function () {
32 | return db.deleteAdmin('anna');
33 | }).then(function () {
34 | return db.logOut();
35 | }).then(function () {
36 | return db.destroy();
37 | });
38 | });
39 |
40 | function testGetUser(db) {
41 | return db.getUser('spiderman').then(function (res) {
42 | res.name.should.equal('spiderman');
43 | });
44 | }
45 |
46 | it('Test get user with basic authentication through URL', function () {
47 | var dbNameWithAuth = dbName.replace('http://', 'http://spiderman:will-remember@');
48 | var dbWithBasicAuth = new PouchDB(dbNameWithAuth, {skip_setup: true});
49 | return testGetUser(dbWithBasicAuth);
50 | });
51 |
52 | it('Test get user with basic authentication through PouchDB opts', function () {
53 | var dbWithBasicAuth = new PouchDB(dbName, {
54 | skip_setup: true,
55 | auth: {
56 | username: 'spiderman',
57 | password: 'will-remember',
58 | },
59 | });
60 | return testGetUser(dbWithBasicAuth);
61 | });
62 | });
63 |
--------------------------------------------------------------------------------
/test/test.users.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var PouchDB = require('./test-pouchdb');
4 | var Authentication = require('../lib');
5 | PouchDB.plugin(Authentication);
6 |
7 | var utils = require('./test-utils');
8 | var chai = require('chai');
9 | var should = chai.should();
10 |
11 | var serverHost = utils.getConfig().serverHost;
12 |
13 | describe('users', function () {
14 |
15 | var dbName = serverHost + '/testdb';
16 | var users = ['batman', 'superman', 'green_lantern', 'robin', 'aquaman', 'spiderman'];
17 |
18 | var db;
19 |
20 | beforeEach(function () {
21 | db = new PouchDB(dbName);
22 | return utils.ensureUsersDatabaseExists();
23 | });
24 |
25 | afterEach(function () {
26 | return db.logout().then(function () {
27 | return db.destroy().then(function () {
28 | // remove the fake users, hopefully we're in the admin party
29 | return utils.deleteUsers(users);
30 | });
31 | });
32 | });
33 |
34 | it('Test signup', function () {
35 | return db.signup('batman', 'brucewayne').then(function (res) {
36 | res.ok.should.equal(true);
37 | res.id.should.equal('org.couchdb.user:batman');
38 | });
39 | });
40 |
41 | it('Test signup conflict', function () {
42 | return db.signup('superman', 'clarkkent').then(function (res) {
43 | res.ok.should.equal(true);
44 | return db.signup('superman', 'notclarkkent').then(function (res) {
45 | should.not.exist(res);
46 | }).catch(function (err) {
47 | err.error.should.equal('conflict');
48 | });
49 | });
50 | });
51 |
52 | it('Test bad signup args', function () {
53 | return db.signup().catch(function (err) {
54 | should.exist(err);
55 | });
56 | });
57 |
58 | it('Test bad signup args 2', function () {
59 | return db.signup('green_lantern').catch(function (err) {
60 | should.exist(err);
61 | });
62 | });
63 |
64 | it('Test that admin can change roles', function () {
65 | var roles = ['sidekick'];
66 | var newRoles = ['superhero', 'villain'];
67 | return db.signup('robin', 'dickgrayson', {roles: roles}).then(function (res) {
68 | res.ok.should.equal(true);
69 | return db.getUser('robin');
70 | }).then(function (user) {
71 | user.roles.should.deep.equal(roles);
72 | }).then(function () {
73 | return db.putUser('robin', {roles: newRoles});
74 | }).then(function (res) {
75 | res.ok.should.equal(true);
76 | return db.getUser('robin');
77 | }).then(function (user) {
78 | user.roles.should.deep.equal(newRoles);
79 | }).catch(function (err) {
80 | should.not.exist(err);
81 | });
82 | });
83 |
84 | it('Test that user cannot change roles', function () {
85 | var roles = ['sidekick'];
86 | var newRoles = ['superhero', 'villain'];
87 | // We can't test for initial roles as we are in admin party
88 | // Let us have faith in CouchDB
89 | return db.signup('robin', 'dickgrayson', {roles: roles}).then(function (res) {
90 | res.ok.should.equal(true);
91 | return db.login('robin', 'dickgrayson');
92 | }).then(function () {
93 | return db.getUser('robin');
94 | }).then(function (user) {
95 | user.roles.should.deep.equal(roles);
96 | }).then(function () {
97 | return db.putUser('robin', {roles: newRoles});
98 | }).then(function (res) {
99 | res.ok.should.not.equal(true);
100 | return db.getUser('robin').then(function (user) {
101 | user.roles.should.deep.equal(roles);
102 | });
103 | }).catch(function (err) {
104 | should.exist(err);
105 | });
106 | });
107 |
108 | it('Test wrong user for getUser', function () {
109 | return db.signup('robin', 'dickgrayson').then(function () {
110 | return db.signup('aquaman', 'sleeps_with_fishes');
111 | }).then(function () {
112 | return db.login('robin', 'dickgrayson');
113 | }).then(function () {
114 | return db.getUser('robin');
115 | }).then(function (res) {
116 | res.name.should.equal('robin');
117 | return db.getUser('aquaman').then(function (res) {
118 | should.not.exist(res);
119 | }).catch(function (err) {
120 | should.exist(err);
121 | return db.login('aquaman', 'sleeps_with_fishes').then(function () {
122 | return db.getUser('aquaman').then(function (res) {
123 | res.name.should.equal('aquaman');
124 | return db.getSession();
125 | }).then(function (res) {
126 | res.userCtx.name.should.equal('aquaman');
127 | return db.getUser('robin').then(function (res) {
128 | should.not.exist(res);
129 | }).catch(function (err) {
130 | should.exist(err);
131 | });
132 | });
133 | });
134 | });
135 | });
136 | });
137 |
138 | it('Test delete user', function () {
139 | return db.signup('robin', 'dickgrayson').then(function () {
140 | return db.getUser('robin');
141 | }).then(function (res) {
142 | res.name.should.equal('robin');
143 | }).then(function () {
144 | return db.deleteUser('robin');
145 | }).then(function (res) {
146 | res.ok.should.equal(true);
147 | }).then(function () {
148 | return db.getUser('robin');
149 | }).then(function () {
150 | throw new Error('shouldn\'t have found user');
151 | }, function (err) {
152 | should.exist(err);
153 | err.error.should.equal('not_found');
154 | err.reason.should.be.oneOf(['missing', 'deleted']);
155 | });
156 | });
157 |
158 | it('Test change password', function () {
159 | return db.signup('spiderman', 'will-forget').then(function () {
160 | return db.changePassword('spiderman', 'will-remember').then(function (res) {
161 | res.ok.should.equal(true);
162 | }).then(function () {
163 | return db.login('spiderman', 'will-remember');
164 | }).then(function (res) {
165 | res.ok.should.equal(true);
166 | });
167 | });
168 | });
169 |
170 | it('Test change username', function () {
171 | return db.signup('spiderman', 'will-forget').then(function () {
172 | return db.changeUsername('spiderman', 'batman').then(function () {
173 | return db.login('batman', 'will-forget');
174 | }).then(function (res) {
175 | res.ok.should.equal(true);
176 | });
177 | });
178 | });
179 |
180 | it('Shouldn\'t change username if new username already exists', function () {
181 | return db.signup('spiderman', 'will-forget').then(function () {
182 | return db.signup('batman', 'will-remember');
183 | }).then(function () {
184 | return db.changeUsername('spiderman', 'batman');
185 | }).then(function () {
186 | throw new Error('shouldn\'t have worked');
187 | }, function (err) {
188 | should.exist(err);
189 | });
190 | });
191 | });
192 |
--------------------------------------------------------------------------------
/test/test.users.metadata.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var PouchDB = require('./test-pouchdb');
4 | var Authentication = require('../lib');
5 | PouchDB.plugin(Authentication);
6 |
7 | var utils = require('./test-utils');
8 | var chai = require('chai');
9 | var should = chai.should();
10 |
11 | var serverHost = utils.getConfig().serverHost;
12 |
13 | describe('users.metadata', function () {
14 |
15 | var dbName = serverHost + '/testdb';
16 | var users = ['robin'];
17 |
18 | var db;
19 |
20 | beforeEach(function () {
21 | db = new PouchDB(dbName);
22 | return utils.ensureUsersDatabaseExists();
23 | });
24 |
25 | afterEach(function () {
26 | return db.logout().then(function () {
27 | return db.destroy().then(function () {
28 | // remove the fake users, hopefully we're in the admin party
29 | return utils.deleteUsers(users);
30 | });
31 | });
32 | });
33 |
34 | it('Test metadata', function () {
35 | var metadata = {alias: 'boywonder', profession: 'acrobat'};
36 | var opts = {metadata: metadata};
37 | return db.signup('robin', 'dickgrayson', opts).then(function (res) {
38 | res.ok.should.equal(true);
39 | return db.login('robin', 'dickgrayson');
40 | }).then(function () {
41 | return db.getUser('robin');
42 | }).then(function (user) {
43 | user.name.should.equal('robin');
44 | user.alias.should.equal('boywonder');
45 | user.profession.should.equal('acrobat');
46 | });
47 | });
48 |
49 | it('Test changing metadata', function () {
50 | var metadata = {alias: 'boywonder', profession: 'acrobat'};
51 | var newMetadata = {alias: 'rednowyob', profession: 'taborca'};
52 | var opts = {metadata: metadata};
53 | return db.signup('robin', 'dickgrayson', opts).then(function (res) {
54 | res.ok.should.equal(true);
55 | return db.login('robin', 'dickgrayson');
56 | }).then(function () {
57 | return db.getUser('robin');
58 | }).then(function (user) {
59 | user.name.should.equal('robin');
60 | user.alias.should.equal('boywonder');
61 | user.profession.should.equal('acrobat');
62 | }).then(function () {
63 | return db.putUser('robin', {metadata: newMetadata});
64 | }).then(function () {
65 | return db.getUser('robin');
66 | }).then(function (user) {
67 | user.name.should.equal('robin');
68 | user.alias.should.equal('rednowyob');
69 | user.profession.should.equal('taborca');
70 | });
71 | });
72 |
73 | var reservedWords = [
74 | '_id',
75 | '_rev',
76 | 'name',
77 | 'type',
78 | 'roles',
79 | 'password',
80 | 'password_scheme',
81 | 'iterations',
82 | 'derived_key',
83 | 'salt'
84 | ];
85 |
86 | reservedWords.forEach(function (key) {
87 | it('Test changing metadata using reserved word "' + key + '"', function () {
88 | return db.signup('robin', 'dickgrayson').then(function (res) {
89 | res.ok.should.equal(true);
90 | return db.login('robin', 'dickgrayson');
91 | }).then(function () {
92 | return db.getUser('robin').then(function (user) {
93 | var metadata = {};
94 | metadata[key] = 'test';
95 | return db.putUser('robin', {metadata: metadata}).then(function (res) {
96 | res.ok.should.not.equal(true);
97 | }).catch(function (err) {
98 | should.exist(err);
99 | err.status.should.equal(400);
100 | err.name.should.equal('authentication_error');
101 | err.message.should.equal('cannot use reserved word in metadata: "' + key + '"');
102 | err.error.should.equal(true);
103 |
104 | if (key === 'password') {
105 | return db.login('robin', 'dickgrayson').then(function (res) {
106 | res.ok.should.equal(true);
107 | }).catch(function (err) {
108 | should.not.exist(err);
109 | });
110 | } else {
111 | return db.getUser('robin').then(function (changedUser) {
112 | changedUser[key].should.deep.equal(user[key]);
113 | }).catch(function (err) {
114 | should.not.exist(err);
115 | });
116 | }
117 | });
118 | });
119 | });
120 | });
121 | });
122 |
123 | it('Test changing metadata using non-reserved word "metadata"', function () {
124 | var metadata = {test: 'test'};
125 | return db.signup('robin', 'dickgrayson').then(function (res) {
126 | res.ok.should.equal(true);
127 | return db.login('robin', 'dickgrayson');
128 | }).then(function () {
129 | return db.putUser('robin', {metadata: {metadata: metadata}});
130 | }).then(function (res) {
131 | res.ok.should.equal(true);
132 | return db.getUser('robin');
133 | }).then(function (changedUser) {
134 | changedUser.metadata.should.deep.equal(metadata);
135 | }).catch(function (err) {
136 | should.not.exist(err);
137 | });
138 | });
139 | });
140 |
--------------------------------------------------------------------------------
/types/index.d.ts:
--------------------------------------------------------------------------------
1 | // Type definitions for pouchdb-authentication 1.0
2 | // Project: https://pouchdb.com/
3 | // Definitions by: Didier Villevalois
4 | // Definitions: https://github.com/pouchdb-community/pouchdb-authentication
5 | // TypeScript Version: 2.3
6 |
7 | ///
8 |
9 | // TODO: Fixing this lint error will require a large refactor
10 | /* tslint:disable:no-single-declare-module */
11 |
12 | declare namespace PouchDB {
13 | namespace Authentication {
14 |
15 | interface UserContext {
16 | name: string;
17 | roles?: string[];
18 | }
19 |
20 | interface User extends UserContext {
21 | }
22 |
23 | interface LoginResponse extends Core.BasicResponse, UserContext {
24 | }
25 |
26 | interface SessionResponse extends Core.BasicResponse {
27 | info: {
28 | authenticated: string;
29 | authentication_db: string;
30 | authentication_handlers: string[];
31 | };
32 | userCtx: UserContext;
33 | }
34 |
35 | interface PutUserOptions extends Core.Options {
36 | metadata?: any;
37 | roles?: string[];
38 | }
39 | }
40 |
41 | interface Database {
42 | /**
43 | * Log in an existing user.
44 | * Throws an error if the user doesn't exist yet, the password is wrong, the HTTP server is unreachable, or a meteor struck your computer.
45 | */
46 | logIn(username: string, password: string,
47 | callback: Core.Callback): void;
48 |
49 | logIn(username: string, password: string,
50 | options: Core.Options,
51 | callback: Core.Callback): void;
52 |
53 | logIn(username: string, password: string,
54 | options?: Core.Options): Promise;
55 |
56 | /**
57 | * Logs out whichever user is currently logged in.
58 | * If nobody's logged in, it does nothing and just returns `{"ok" : true}`.
59 | */
60 | logOut(callback: Core.Callback): void;
61 |
62 | logOut(): Promise;
63 |
64 | /**
65 | * Returns information about the current session.
66 | * In other words, this tells you which user is currently logged in.
67 | */
68 | getSession(callback: Core.Callback): void;
69 |
70 | getSession(): Promise;
71 |
72 | /**
73 | * Sign up a new user who doesn't exist yet.
74 | * Throws an error if the user already exists or if the username is invalid, or if some network error occurred.
75 | * CouchDB has some limitations on user names (e.g. they cannot contain the character `:`).
76 | */
77 | signUp(username: string, password: string,
78 | callback: Core.Callback): void;
79 |
80 | signUp(username: string, password: string,
81 | options: Authentication.PutUserOptions,
82 | callback: Core.Callback): void;
83 |
84 | signUp(username: string, password: string,
85 | options?: Authentication.PutUserOptions): Promise;
86 |
87 | /**
88 | * Returns the user document associated with a username.
89 | * (CouchDB, in a pleasing show of consistency, stores users as JSON documents in the special `_users` database.)
90 | * This is the primary way to get metadata about a user.
91 | */
92 | getUser(username: string,
93 | callback: Core.Callback & Core.GetMeta>): void;
94 |
95 | getUser(username: string,
96 | options: PouchDB.Core.Options,
97 | callback: Core.Callback & Core.GetMeta>): void;
98 |
99 | getUser(username: string,
100 | options?: PouchDB.Core.Options): Promise & Core.GetMeta>;
101 |
102 | /**
103 | * Update the metadata of a user.
104 | */
105 | putUser(username: string,
106 | callback: Core.Callback): void;
107 |
108 | putUser(username: string, options: Authentication.PutUserOptions,
109 | callback: Core.Callback): void;
110 |
111 | putUser(username: string, options?: Authentication.PutUserOptions): Promise;
112 |
113 | /**
114 | * Delete a user.
115 | */
116 | deleteUser(username: string,
117 | callback: Core.Callback): void;
118 |
119 | deleteUser(username: string,
120 | options: Core.Options,
121 | callback: Core.Callback): void;
122 |
123 | deleteUser(username: string,
124 | options?: Core.Options): Promise;
125 |
126 | /**
127 | * Set new `password` for user `username`.
128 | */
129 | changePassword(username: string, password: string,
130 | callback: Core.Callback): void;
131 |
132 | changePassword(username: string, password: string,
133 | options: Core.Options,
134 | callback: Core.Callback): void;
135 |
136 | changePassword(username: string, password: string,
137 | options?: Core.Options): Promise;
138 |
139 | /**
140 | * Renames `oldUsername` to `newUsername`.
141 | */
142 | changeUsername(oldUsername: string, newUsername: string,
143 | callback: Core.Callback): void;
144 |
145 | changeUsername(oldUsername: string, newUsername: string,
146 | options: Core.Options,
147 | callback: Core.Callback): void;
148 |
149 | changeUsername(oldUsername: string, newUsername: string,
150 | options?: Core.Options): Promise;
151 |
152 | /**
153 | * Sign up a new admin.
154 | */
155 | signUpAdmin(username: string, password: string,
156 | callback: Core.Callback): void;
157 |
158 | signUpAdmin(username: string, password: string,
159 | options: Authentication.PutUserOptions,
160 | callback: Core.Callback): void;
161 |
162 | signUpAdmin(username: string, password: string,
163 | options?: Authentication.PutUserOptions): Promise;
164 |
165 | /**
166 | * Delete an admin.
167 | */
168 | deleteAdmin(username: string,
169 | callback: Core.Callback): void;
170 |
171 | deleteAdmin(username: string, options: Core.Options,
172 | callback: Core.Callback): void;
173 |
174 | deleteAdmin(username: string, options?: Core.Options): Promise;
175 | }
176 | }
177 |
178 | declare module 'pouchdb-authentication' {
179 | const plugin: PouchDB.Plugin;
180 | export = plugin;
181 | }
182 |
--------------------------------------------------------------------------------
/types/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "lib": [
5 | "es6",
6 | "dom"
7 | ],
8 | "noImplicitAny": true,
9 | "noImplicitThis": true,
10 | "strictNullChecks": true,
11 | "strictFunctionTypes": true,
12 | "baseUrl": "../",
13 | "moduleResolution": "node",
14 | "types": [],
15 | "noEmit": true,
16 | "forceConsistentCasingInFileNames": true
17 | },
18 | "files": [
19 | "index.d.ts",
20 | "type-tests.ts"
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/types/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "dtslint/dt.json",
3 | "rules": {
4 | "no-declare-current-package": false,
5 | "no-any-union": false
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/types/type-tests.ts:
--------------------------------------------------------------------------------
1 | function testAuthentication() {
2 | const db = new PouchDB<{ foo: number }>();
3 |
4 | db.logIn('username', 'password');
5 |
6 | db.logOut();
7 |
8 | db.getSession();
9 |
10 | db.signUp('username', 'password', {
11 | roles: ['role1', 'role2'], metadata: { anyStuff: 'whatever' },
12 | });
13 |
14 | db.putUser('username', {
15 | roles: ['role1', 'role2'], metadata: { anyStuff: 'whatever' },
16 | });
17 |
18 | db.getUser('username');
19 |
20 | db.deleteUser('username');
21 |
22 | db.changePassword('username', 'password');
23 |
24 | db.changeUsername('oldUsername', 'newUsername');
25 |
26 | db.signUpAdmin('username', 'password');
27 |
28 | db.deleteAdmin('username');
29 | }
30 |
--------------------------------------------------------------------------------