Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Last active July 22, 2022 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BananaAcid/f3ad078c69ea55aeb5467eba8c334d15 to your computer and use it in GitHub Desktop.
Save BananaAcid/f3ad078c69ea55aeb5467eba8c334d15 to your computer and use it in GitHub Desktop.
couchDB - putSecurity() and getSecurity() using fetch #PouchDB
/**
Access CouchDB to get and update a security object using fetch
(does it directly, no pouchdb or alike needed. PouchDB CAN get a _security object but not set it).
Usage:
let con = 'http://admin:adminpw@localhost:5984/user-numberone';
let secDoc = await getSecurity(con);
secDoc.members = ['user_to_add'];
await putSecurity(con, secDoc);
@author Nabil Redmann <repo@bananaacid.de>
@license ISC
*/
/**
* putSecurity
* saves a new security object
*
* Note: .pathname is the DB-name
*
* @param {{username:string,password:string,protocol:string,host:string,pathname:string}|string} dbConStringOrObject the conenction object to use
* @param {{admins:{names?:string[],roles?:string[]},members:{names?:string[],roles?:string[]}}} secDoc the security object to save
* @returns {Promise<boolean>}
**/
async function putSecurity(dbConStringOrObject, secDoc) {
let a;
if (typeof dbConStringOrObject === 'string' || dbConStringOrObject instanceof String) {
a = document.createElement('A');
a.href = dbConStringOrObject;
}
else {
a = dbConStringOrObject;
}
var headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa(a.username + ':' + a.password));
headers.append('Content-Type', 'application/json');
let res = await fetch(a.protocol + '//' + a.host + a.pathname + '/_security', {method: 'PUT', headers, cache: 'no-cache', body: JSON.stringify(secDoc),})
.then(res => res.json())
.catch(err => {error: err});
if (res.error) {
console.error(res);
}
return (res.ok == true);
}
/**
* getSecurity
* get a security object
*
* Note: .pathname is the DB-name
*
* @param {{username:string,password:string,protocol:string,host:string,pathname:string}|string} dbConStringOrObject the conenction object to use
* @returns {Promise<boolean>}
**/
async function getSecurity(dbConStringOrObject) {
let a;
if (typeof dbConStringOrObject === 'string' || dbConStringOrObject instanceof String) {
a = document.createElement('A');
a.href = dbConStringOrObject;
}
else {
a = dbConStringOrObject;
}
var headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa(a.username + ':' + a.password));
headers.append('Content-Type', 'application/json');
let res = await fetch(a.protocol + '//' + a.host + a.pathname + '/_security', {method: 'GET', headers, cache: 'no-cache',})
.then(res => res.json())
.catch(err => {error: err});
if (res.error) {
console.error(res);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment