Last active
August 20, 2019 15:35
-
-
Save weilu/10445007 to your computer and use it in GitHub Desktop.
Cloudant create user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cradle = require('cradle'); | |
var crypto = require('crypto'); | |
cradle.setup({ | |
host: 'foo.cloudant.com', | |
port: 80, | |
cache: false, | |
timeout: 5000 | |
}) | |
var conn = new (cradle.Connection)({ | |
secure: true, | |
auth: { username: "user", password: "pass" } | |
}) | |
var db = conn.database('_users') | |
function createUser(name, password, callback){ | |
db.get(name, function (err, doc) { | |
if(err && err.error === 'not_found'){ | |
var hashAndSalt = generatePasswordHash(password) | |
db.save("org.couchdb.user:" + name, { | |
name: name, | |
password_sha: hashAndSalt[0], | |
salt: hashAndSalt[1], | |
password_scheme: 'simple', | |
type: 'user' | |
}, callback) | |
} else if(err) { | |
callback(err) | |
} else { | |
callback({error: 'user_exists'}) | |
} | |
}) | |
} | |
function generatePasswordHash(password){ | |
var salt = crypto.randomBytes(16).toString('hex'); | |
var hash = crypto.createHash('sha1'); | |
hash.update(password + salt); | |
return [hash.digest('hex'), salt]; | |
} | |
createUser('alice', '123') | |
//$ curl -X POST https://foo.cloudant.com/_session -d 'name=alice&password=123' | |
// {"ok":true,"name":"alice","roles":[]} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome. Just turned this into a little npm package, cloudant-user. Very useful when creating a private npm registry/repository on Cloudant. Thanks for your work!