Background:
I am trying to encrypt a pouchdb database by using crypto-pouch library.
I had a look at the example shown at https://github.com/calvinmetcalf/crypto-pouch
But it doesn't seem to do anything for me.
My code:
<!DOCTYPE html>
<html ng-app="pouchdbApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="pouchdbDemo.js"></script>
<script src="http://cdn.jsdelivr.net/pouchdb/5.2.1/pouchdb.min.js"></script>
<!-- <script src="crypto-pouch-master/bundle.js"></script> -->
<script src="http://wzrd.in/standalone/crypto-pouch"></script>
<script>
var db = new PouchDB('kittens2');
var password = "mypassword";
db.crypto(password).then(function (publicKey) {
console.log("publicKey");
console.log(publicKey);
});
/* db.removeCrypto(); */
var doc = {
"_id": "mittens",
"name": "Mittens",
"occupation": "kitten",
"age": 3,
"hobbies": [
"playing with balls of yarn",
"chasing laser pointers",
"lookin' hella cute"
]
};
db.put(doc);
db.get('mittens').then(function (doc) {
console.log(doc);
});
</script>
</head>
<body>
</body>
</html>
But my code doesn't see to do any encryption of the data entered, or i couldn't see any public key generated.
Any clue how i should be using the crypto-pouch library with pouchdb.
Edit: this answer originally refereed to version 1.x of crypto pouch, but is not correct for the current version (3.x), in the current version db.crypto(password) does not return a promise so the code examples updated are
db.crypto(password)
// <-- encryption set up
and
db.crypto(password);
db.put({_id: 'foo', bar: 'baz'}).then(function () {
return db.get('foo');
}).then(function (doc) {
console.log('decrypted', doc);
return db.removeCrypto();
}).then(function () {
return db.get('foo');
}).then(function (doc) {
console.log('encrypted', doc);
})
Original answer (still valid for v1.x) follows:
so the documentation is a bit confusing (which I just cleaned up) but when you call db.crypto it wraps the database so that documents are transparently encrypted and decrypted
db.crypto(password).then(function () {
// <-- encryption set up
})
and it will transparently encrypt documents you create and decrypt ones you read until you call
db.removeCrypto();
so if you want to test do something like
db.crypto(password).then(function () {
return db.put({_id: 'foo', bar: 'baz'});
}).then(function () {
return db.get('foo');
}).then(function (doc) {
console.log('decrypted', doc);
return db.removeCrypto();
}).then(function () {
return db.get('foo');
}).then(function (doc) {
console.log('encrypted', doc);
})
I tried combDB and its the only one that seems to work as of now with the new nodeJS
const PouchDB = require('pouchdb')
PouchDB.plugin(require('comdb'))
const password = 'extremely secure value'
const db = new PouchDB(POUCH_PATH)
db.setPassword(password)
db.post({
_id: 'gay-agenda',
type: 'queerspiracy',
agenda: ['be gay', 'do crimes']
}).then(() => {
// now replicate to a couchdb instance
return db.replicate.to(`${COUCH_URL}/FALGSC`)
})
or with Angular (Typescript)
import PouchDB from 'pouchdb-browser';
...
this.db = new PouchDB('myProjectDB');
this.db.setPassword(environment.dbPassword);
Related
I am trying to get a user entered amount from my checkout.html file ( below ) so that I can use it in the Stripe code on the server.js node server.
I wasn't able to get the amount field from the form to work so I disabled it and am working with console.log and variables. I was trying to make it work with a global variable passing the value.
These 2 files from the example on the Stripe website ( you select 'node' and 'html' from the page, and click 'prebuilt' also )
https://stripe.com/docs/checkout/integration-builder
My alterations
( sorry the var assignments numbers are all just random for testing )
**server.js**
( lines 8-9 )
var test = 2242;
// console.log( amountglobal);
( line 22 )
unit_amount: test,
**checkout.html** (line 47 )
amountglobal = 67865555;
My issue is that if I uncomment line 9 ( with the aim of trying to use the amountglobal gloabal var in line 22 ) then for some reason the server wont start, saying amountglobal is not defined ... so I possibly have the global variable wrong in checkout.html, it's
amountglobal = 67865555;
... and maybe there's a better way of doing this in the first place, I understand global variables are not the ideal usually.
The end result here is to be a payment form where the user can type in their own ( previously agreed) price.
Thanks.
FULL FILES
server.js
const stripe = require('stripe')
('sk_test_51IAvl4KYIMptSkmlXwuihwZa8jtdIrnD79kSQcnhvQKbg9dbAXiZisFmasrKHIK9B75d9jgeyYK8MULLbFGrGBpU00uQgDvtnJ');
const express = require('express');
const app = express();
app.use(express.static('.'));
const YOUR_DOMAIN = 'http://localhost:4242';
var test = 2242;
console.log( amountglobal);
app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'Stubborn Attachments',
images: ['https://i.imgur.com/EHyR2nP.png'],
},
unit_amount: test,
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}/success.html`,
cancel_url: `${YOUR_DOMAIN}/cancel.html`,
});
res.json({ id: session.id });
});
app.listen(4242, () => console.log('Running on port 4242'));
Checkout.html
<!DOCTYPE html>
<html>
<head>
<title>Buy cool new product</title>
<link rel="stylesheet" href="style.css">
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<section>
<div class="product">
<img
src="https://i.imgur.com/EHyR2nP.png"
alt="The cover of Stubborn Attachments"
/>
<div class="description">
<h3>Stubborn Attachments</h3>
<h5>$20.00</h5>
</div>
</div>
<form id="frm12" action="#">
First name: <input type="text" name="amount" value = "435"><br>
<!-- <input type="button" onclick="myFunction()" value="Submit"> -->
<input type="submit" id="checkout-button" value="Checkout">
</form>
</section>
</body>
<script type="text/javascript">
function myFunction() {
console.log("test");
document.getElementById("frm1").submit();
}
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe("pk_test_51IAvl4KYIMptSkmlAwhNvG0CDJRnr2hyrJuRnfdnfaEEhHPwCWsr9QK183a1pKUQ4PLrrtEqiElFLTVHIiSueX6r00TyXooIcu");
var checkoutButton = document.getElementById("checkout-button");
var amount = document.getElementById("amount");
amountglobal = 67865555;
// console.log(amount);
checkoutButton.addEventListener("click", function () {
fetch("/create-checkout-session", {
method: "POST",
})
.then(function (response) {
return response.json();
})
.then(function (session) {
console.log('here');
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
</html>
You need to POST the data from your client side code to your server side code, and then use a JSON body parser with Express so that it ends up in the server-side request.
So I'm using snoowrap to write a Chrome extension that gets a list of subreddits the user is subscribed, and subscribes to them on a different account.
I'm trying to get the list of subreddits currently but can't figure out how to do it. I've tried simply getting the JSON from https://www.reddit.com/subreddits/mine.json, which returns an empty object (persumably because no auth) and I have no idea how to do it via snoowrap. I looked through the documentation and can't find an option for it.
My code:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('login');
login.addEventListener('click', function() {
const r = new snoowrap({
userAgent: '???',
clientId: '<id>',
clientSecret: '<clientsecret>',
username: '<username-here>',
password: '<password-here>'
});
r.getHot().map(post => post.title).then(console.log);
});
var getSubs = document.getElementById('get-subs');
getSubs.addEventListener('click', function() {
fetch('https://www.reddit.com/subreddits/mine.json')
.then(function(data) {
console.log(JSON.stringify(data));
})
.catch(function(error) {
console.log('error');
});
});
});
Not sure how else to try. Anyone have suggestions? I'd like to use snoowrap for this ideally.
When using snoowrap as API wrapper, after connecting to the api with:
const r = new snoowrap({...});
They provide a function for getting your own subscribed subreddits:
r.getSubscriptions();
This will return a Listing Object, which you can use like an Array.
I have a blog that I want to make shareable via LinkedIn. The docs LinkedIn presents, while simply stated don't have enough detail for me to understand my use case. My use case requires me to dynamically put the picture and description in each blog post, which isn't being populated right now. This is an Angular project.
My current code:
post.html
<script>
delete IN;
$.getScript("https://platform.linkedin.com/in.js");
</script>
<script type="IN/Share" data-url={{webAddress}} data-counter="right"></script>
post.js
//I have all of my data in $scope variables in this area, which includes
// the picture and description I'd like to attach to the post.
Here is what the LinkedIn docs show as the right way to do this:
post.html
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to share content on LinkedIn
function shareContent() {
// Build the JSON payload containing the content to be shared
var payload = {
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
</script>
As I understand it, I need to populate the payload object with the right data/links. I have no clue how to do this based on what's in the docs.
Here are a few things I've tried/thought about along with where I'm currently stuck:
1) Get the data from post.js and put it in the payload object between the script tags in post.html. After doing some research, it is not possible to do this. Though I welcome being corrected if I'm wrong.
2) Bring the IN object into angular and populate the payload in post.js. This sounds really great but LinkedIn provides no html with which to call a function in post.js with Angular. Plus the LinkedIn code as presented takes care of formatting for the button and what comes after you click it.
3) Make an http call inside the script tags with JQuery. I rarely if ever use JQuery and have never used http for JQuery before. If this is even a feasible way to think of this problem, this is what I came up with:
<script type="IN/Share" data-url={{webAddress}} data-counter="right">
$.get( "https://public-api.wordpress.com/rest/v1.1/sites/myPost", function( response ) {
var post = _.first(_.filter(response.posts, function(n){return n.title.replace(/ /g,"-").replace(/[:]/g, "").toLowerCase() === $stateParams.id}));
var post1 = _.assign(post, {category: _.first(_.keys(post.categories)), pic: _.first(_.values(post.attachments)).URL, credit: _.first(_.values(post.attachments)).caption, linkCredit: _.first(_.values(post.attachments)).alt, fullStory: post.content.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')});
**var image = post1.pic;**
**var title = post1.title;**
**var webAddress = window.location.href;**
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function shareContent(title, image, webAddress) {
var payload = {
"content": {
"title": title,
"submitted-image-url": image,
"submitted-url": webAddress
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
});
</script>
This solution did not result in a solution either. Where to go from here, I have no ideas. I'm sure this simple but idiosyncratic enough that I need a little hand holding.
Unfortunately, I have not worked with linkedin API.
Perhaps not all will be right in my example. But I've got to use a variable IN in angular and write about the call API wrapper.
An example of the use of plugins, see page LinkedIn Plugins.
Live example on jsfiddle.
//CallBackHell
function LinkedInServiceFunc(callback) {
callback && IN.Event.onDOMReady(callback);
}
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope, LinkedInService, ShareLinkedINService) {
console.log('ExampleController IN', IN);
console.log('ExampleController LinkedInService', LinkedInService);
LinkedInService.promise.then(function(LIN) {
console.log('Complete loading script for LinkedIn in ExampleController', LIN.Objects)
});
//Then you can interact with IN object as angular service. Like this
$scope.shareContent = function() { // Use the API call wrapper to share content on LinkedIn
// Build the JSON payload containing the content to be shared
var payload = {
"comment": $scope.comment,
"visibility": {
"code": 'anyone'
}
};
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
console.log('shareContent', payload);
LinkedInService.promise.then(function(LIN) {
LIN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
});
}
$scope.shareContentService = function() {
//It's better way, i think
ShareLinkedINService.shareContent($scope.comment, 'anyone').then(function(data) {
console.log('success', data);
}).catch(function(data) {
console.err('error', data);
});
}
})
.service('LinkedInService', function($q) {
var defer = $q.defer();
LinkedInServiceFunc(function() {
defer.resolve(IN);
});
return {
promise: defer.promise
};
})
//You can create wrapper on IN API
.service('ShareLinkedINService', function(LinkedInService, $q) {
return {
shareContent: function(comment, visible) {
var defer = $q.defer();
var payload = {
"comment": comment,
"visibility": {
"code": visible
}
};
LinkedInService.promise.then(function(LIN) {
LIN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(defer.resolve)
.error(defer.reject);
});
return defer.promise;
}
}
})
.directive('linkedInShareButton', function(LinkedInService) {
return {
restrict: "E",
replace: false,
scope: {
shareUrl: "#",
counter:"#"
},
link: function(scope, elem, attr) {
var script = document.createElement('script');
script.setAttribute('type', 'IN/Share');
script.setAttribute('data-url', scope.shareUrl);
script.setAttribute('data-counter', scope.counter);
elem.append(script);
},
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
authorize: false
onLoad: LinkedInServiceFunc
//I don't have api_key, because i delete it
// api_key: YOUR_API_KEY_HERE
// authorize: true
// onLoad: onLinkedInLoad
</script>
<body ng-app="ExampleApp">
<div>
<div ng-controller="ExampleController">
<input ng-model="comment">
<button ng-click="shareContent()">
shareContent
</button>
<button ng-click="shareContentService()">
shareContentService
</button>
<script type="IN/Share" data-url="www.mail.ru" data-counter="top"></script>
<linked-in-share-button share-url="www.mail.ru" counter="top"></linked-in-share-button>
</div>
</div>
</body>
I am a newbie to Pentaho and try to make an alert(some_msg_from_datasource) in the index.jsp of Pentaho. But I cannot figure out how to access the Pentaho variables from here. This is what I have
<head> ... <script type="text/javascript">
var Home = null;
pen.require(["home/home",
"common-ui/util/ContextProvider"], function(pentahoHome, ContextProvider) {
Home = pentahoHome;
// Define properties for loading context
var contextConfig = [{
path: "properties/config",
post: function(context, loadedMap) {
context.config = loadedMap;
}
}, {
path: "properties/messages",
post: function(context, loadedMap) {
context.i18n = loadedMap;
}
}];
// Define permissions
ContextProvider.addProperty("canCreateContent", <%=canCreateContent%>);
ContextProvider.addProperty("hasAnalyzerPlugin", <%=pluginIds.contains("analyzer")%>);
ContextProvider.addProperty("hasDataAccess", false); // default
// BISERVER-8631 - Manage datasources only available to roles/users with appropriate permissions
var serviceUrl = Home.getUrlBase() + "plugin/data-access/api/permissions/hasDataAccess";
Home.getContent(serviceUrl, function(result) {
ContextProvider.addProperty("hasDataAccess", result);
ContextProvider.get(Home.init, contextConfig); // initialize
}, function(error) {
console.log(error);
ContextProvider.get(Home.init, contextConfig); // log error and initialize anyway
});
});
</script> </head>
And for the body:
<body data-spy="scroll" data-target=".sidebar" onload="onBodyLoad()">
<script>
function onBodyLoad(){
alert("MOTD: " + the_motd_from_a_pentaho_var);
}
</script>
I assume I need the webcontext but I don't understand the head-scripts and how I can make it run. Tbh I don't even fully understand the syntax in the head. Please help :(
I have got to know toaster.js from this site and trying to implement it in my web app. I have done it according to the example but it doesn't work.
Here is my service where I Implemented:
function () {
angular
.module('FoursquareApp')
.factory('DataService', DataService);
DataService.$inject = ['$http','toaster'];
function DataService($http, toaster) {
.id,
venueName: venue.name,var serviceBase = '/api/places/';
var placesDataFactory = {};
var userInContext = null;
var _getUserInCtx = function () {
return userInContext;
};
var _setUserInCtx = function (userInCtx) {
userInContext = userInCtx;
};
var _savePlace = function (venue) {
//process venue to take needed properties
var minVenue = {
userName: userInContext,
venueID: venue
address: venue.location.address,
category: venue.categories[0].shortName,
rating: venue.rating
};
return $http.post(serviceBase, minVenue).then(
function (results) {
toaster.pop('success', "Bookmarked Successfully", "Place saved to your bookmark!");
},
function (results) {
if (results.status == 304) {
toaster.pop('note', "Faield to Bookmark", "Something went wrong while saving :-(");
}
else {
toaster.pop('error', "Failed to Bookmark", "Something went wrong while saving :-(");
}
return results;
});
};
I have called the library scripts in index.html and also the css files.
Any ideas of what I might be doing wrong?
Are you sure that you use toaster.js library? The popular one is toastr.js
Try to modify your code to
DataService.$inject = ['$http','toastr'];
function DataService($http, toastr) {
...
Also ensure, that you link this js file in you index.html and also refer this package in main app module definition as a second (dependency) parameter