How to pass credentials through code instead of requesting user - text-to-speech

I want to pass credentials thru code instead of requesting user to give credentials thru this prompt.
Although I'm passing credentials in header as given in below code:
<html>
<head>
</head>
<body>
<div id="text-to-speech">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<input type="text" name="speech-text" TextMode="MultiLine" height:50px;">
<input type="button" id="btnPOst" value="Play" />
<br /><br /><br />
<audio id="speech" autoplay preload="auto" autobuffer controls class="audio"></audio>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
debugger;
$("#btnPOst").click(function () {
debugger;
var username= "";
var password = "";
var request = $("#text-to-speech input[name=speech-text]").val();
var url = "https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=en-US_MichaelVoice&accept=audio/wav&text=" + request;
$.ajax
({
type: "POST",
url: url,
dataType: "application/json; charset=utf-8",
headers: {
'Content-Type': 'application/json',
'Accept': 'audio/wav',
'Authorization': ("Basic " + btoa(username + ":" + password))
},
success: function (content) {
},
});
$("#speech").attr("src", url)[0].play();
});
});
</script>
</body>
</html>

hi #akash it is not a good practice to do basic authentication directly from the webpage since the credentials will be publicly available and that is a big security issue. Have you thought of using tokens instead? For production apps the recommended a approach is to do basic auth from a server side app that generates tokens, then webpages get those tokens from the server app and connect directly to the STT service. Tokens are valid for one hour. Of course you will need your own authentication mechanism between the webpage and your server app so you deliver tokens in a controlled way.
Please see this: https://github.com/watson-developer-cloud/speech-javascript-sdk which is used to build this webpage: https://speech-to-text-demo.mybluemix.net/

You can build a dynamic url like this:
"https://"+username+":"+password+"#gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters

Related

binding dynamic img in vuejs does not work for me

I have a dynamic img being pulled from an api using vue.js. For some strange reason, the image won't bind. I have tried both :src. and :attr but neither works. The url does display in the vue console inside of the data but can't get the image to display on the page. any help will go a long way.
<html>
<head>
<style></style>
</head>
<body>
<div class="container">
<div id="editor">
<img v-bind:src="PictureURL" />
</div>
</div>
<script type="text/javascript" src="https://unpkg.com/vue#2.0.3/dist/vue.js"></script>
<script>
new Vue({
el: "#editor",
data: {
PictureUrl: "",
},
created: function() {
this.getCurrentUser();
},
methods: {
getCurrentUser: function() {
var root = 'https://example.com';
var headers = {
accept: "application/json;odata=verbose"
}
var vm = this;
var __REQUESTDIGEST = '';
$.ajax({
url: root + "_api/Properties",
type: 'Get',
headers: headers,
success: function(data) {
vm.PictureUrl = data.d.PictureUrl;
}
})
},
}
})
</script>
</body>
</html>
Change <img v-bind:src="PictureURL" /> to <img v-bind:src="PictureUrl" />, so that you match the data item name. Vue should be giving you an error in the console about this.
https://jsfiddle.net/kch7sfda/
Example here.
You can try to:
1. add v-if to img element
2. rename PictureUrl to pictureUrl (first lowercase letter)

dgrid (onDemandGrid) loads on first time button click, but error on second time button is clicked

Thanks to some previous help here, I got the Dojo dgrid to work; and even figured out how to tie it to data from my rest service.
Now I added an input box, a button, and all the logic happens on the button-click. But the second time I click the button, even with the same input value in the input field, I get an error.
ERROR:
TypeError: Cannot read property 'element' of undefined in StoreMixin.js:33
Including the picture so you can see my console.logs
I read this How To reset the OnDemandGrid, but is it necessary to check to see if grid exists and do different logic? Can't I just "new up" a new one each time?
CODE:
<div data-dojo-type="dijit/layout/ContentPane" data-dojo-props='title:"CustomersGrid"'>
<label for="lastnameStartsWith">Lastname Starts With:</label>
<input id="lastnameStartsWith" type="text" name="lastnameStartsWith" value="Wag"
data-dojo-type="dijit/form/TextBox"
data-dojo-props="trim:true, propercase:true" />
<br />
<br />
<button id="queryStudentsButton" data-dojo-type="dijit/form/Button"
data-dojo-type="dijit/form/Button"
data-dojo-props="iconClass:'dijitIconTask'">
<span>Query</span>
<script type='dojo/on' data-dojo-event='click'>
require([
'dstore/RequestMemory',
'dstore/Memory',
'dgrid/OnDemandGrid'
], function (RequestMemory, Memory, OnDemandGrid) {
var url = '../students/' + dojo.byId('lastnameStartsWith').value;
console.log("query students for dataGrid latsnameStartsWith:" + dojo.byId('lastnameStartsWith').value);
require(['dojo/request'], function(request){
request.get(url,
{headers: {"Content-Type": 'application/json',
"username": securityConfig.username,
"password": securityConfig.password}}
)
.then(function(response){
//console.log("string response=" + response);
var respJSON = JSON.parse(response);
var respDataForDGrid = respJSON.recordset;
console.log("got respJSON back, num rows= " + respDataForDGrid.length);
//================================================
// Create an instance of OnDemandGrid referencing the store
console.log("Debug1");
var grid2 = new OnDemandGrid({
collection: new Memory({ data: respDataForDGrid }),
columns: {
student_id: 'ID',
student_firstname: 'First Name',
student_lastname: 'Last Name',
student_city: 'City',
student_state: 'State',
student_zip: 'Zip'
}
}, 'grid2');
console.log("Debug2");
grid2.startup();
console.log("Debug3");
},
function(error){
console.log("Error=" + error);
//dom.byId('studentFeedback').value += response;
});
});
});
</script>
</button>
<h2>My demoGrid - From JSON RestService (Database)</h2>
<div id='grid2'></div>
</div>
Part 2 -
I tried mix of your code and code on this page:
How To reset the OnDemandGrid
if (grid2Registered){
console.log("reuse existing grid");
grid2Registered.set('collection', memStore);
// refresh: clear the grid and re-queries the store for data.
grid2Registered.refresh();
}
else{...
Doc here (https://github.com/SitePen/dgrid/blob/v0.4.3/doc/components/core-components/OnDemandList-and-OnDemandGrid.md) says:
Clears the grid and re-queries the store for data. If
keepScrollPosition is true on either the instance or the options
passed to refresh, an attempt will be made to preserve the current
scroll position. OnDemandList returns a promise from refresh, which
resolves when items in view finish rendering. The promise resolves
with the QueryResults that were rendered.
This one has been tough! Below a working example.
First I switched from declarative to programmatic for the onClick function: declarative scripts are parsed by dojo, and as a consequence you cannot examine them (set break points, etc.) under the debugger (at least I don't know how to do that). So it seems to me good practice to avoid them.
Then, indeed the bug is due to re-instantiating the dgrid with the same id, so that you do need a way to detect that the dgrid already exists. But there is a trick: for dgrids to be properly handled by the dijit system, they need to be mixed in with the dijitRegistry extension. See here for details.
Then you can use registry.byId('grid2') to detect that the dgrid already exists.
Also I had to skip the respDataForDgrid part and used directly respJSON instead (may be due to a difference with your server side(?) - I used a simple text file with a json array on the server side).
<!DOCTYPE HTML><html lang="en">
<head>
<meta charset="utf-8">
<title>Neal Walters stask overflow test</title>
<link rel="stylesheet"
href="dojo-release-1.12.2-src/dijit/themes/claro/claro.css"
media="screen">
<link rel="stylesheet"
href="dojo-release-1.12.2-src/dgrid/css/dgrid.css" media="screen">
</head>
<body class="claro">
<div data-dojo-type="dijit/layout/ContentPane"
data-dojo-props='title:"CustomersGrid"'>
<label for="lastnameStartsWith">Lastname Starts With:</label> <input
id="lastnameStartsWith" type="text" name="lastnameStartsWith"
value="Wag" data-dojo-type="dijit/form/TextBox"
data-dojo-props="trim:true, propercase:true" /> <br /> <br />
<button id="queryStudentsButton" data-dojo-type="dijit/form/Button"
data-dojo-props="iconClass:'dijitIconTask', onClick: myClick">Query</button>
<h2>My demoGrid - From JSON RestService (Database)</h2>
<div id='grid2'></div>
</div>
<script src="dojo-release-1.12.2-src/dojo/dojo.js"
data-dojo-config="async:true"></script>
<script type="text/javascript">
require(["dojo", "dojo/parser", "dojo/domReady!"],
function(dojo, parser){
parser.parse();
});
function myClick(){
var url = 'students/' + dojo.byId('lastnameStartsWith').value, securityConfig = {username: 'john', password: 'Doe'};
console.log("query students for dataGrid latsnameStartsWith:" + dojo.byId('lastnameStartsWith').value);
require(['dojo/_base/declare', 'dojo/request', "dijit/registry", "dstore/RequestMemory", "dstore/Memory", "dgrid/OnDemandGrid", "dgrid/extensions/DijitRegistry"], function(declare, request, registry, RequestMemory, Memory, OnDemandGrid, DijitRegistry){
request.get(url,{})
.then(function(response){
console.log("string response=" + response);
var respJSON = JSON.parse(response);
//var respDataForDGrid = respJSON.recordset;
//console.log("got respJSON back, num rows= " + respDataForDGrid.length);
//================================================
// Create an instance of OnDemandGrid referencing the store
console.log("Debug1");
var theGrid = registry.byId('grid2');
if (theGrid){
theGrid.set('collection', new Memory({data: respJSON}));
}else{
var grid2 = new (declare([OnDemandGrid, DijitRegistry]))({
collection: new Memory({ data: respJSON }),
columns: {
student_id: 'ID',
student_firstname: 'First Name',
student_lastname: 'Last Name',
student_city: 'City',
student_state: 'State',
student_zip: 'Zip'
}
}, 'grid2');
console.log("Debug2");
grid2.startup();
console.log("Debug3");
}
},
function(error){
console.log("Error=" + error);
//dom.byId('studentFeedback').value += response;
});
});
};
</script>
</body>
</html>

expressjs is not returning any response to html

while submitting a form without using ajax I could see "message sent successfully" in my http://localhost/ss (working fine as it should)
But while submitting a form using ajax $.post() response is not receiving to $.post() method. I couldn't find any reason..
Please note: same code works fine with php
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#buttons").click(function() {
$.post("http://localhost:3000/ss", {
sendemail: $("#email").val(),
sendname: $("#UserName").val(),
sendpass: $("#Password").val()
}, function(res) {
alert(res);
});
});
});
</script>
<body>
<div class="forms">
<form>
<div class="formdiv">
<label>User Email</label>
<input type="email" id="email" name="email" />
</div>
<div class="formdiv">
<label>User Name</label>
<input type="text" name="UserName" id="UserName" />
</div>
<div class="formdiv">
<label>User Password</label>
<input type="password" name="Password" id="Password" />
</div>
</form>
<div style="background:green;padding:15px;" id="buttons">send</div>
</div>
</body>
</html>
parse.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.listen(3000, function(req, res)
{
console.log("express is listening to port 3000");
});
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json());
app.get("/", function(req, res)
{
res.send("hai");
});
app.post("/ss", function(req, res)
{
var ss = req.body.sendemail;
if (ss != undefined)
{
console.log(ss);
res.send("message sent successfully");
}
else
{
res.send("error occurred");
}
});
console prints user's email address "The only problem is response to html"
Code looks okey by itself, although there's one issue, with (i suspect) the way you use it. You're not allowing for cross-origin sharing. In other words, if you'd try to run this code on another domain, you'd receive a CORS error, as server refuses to respond to the client.
Therefore, I suspect you're loading the .html file either:
As local, html file.
Are running it from different domain
both of those would (and are) returning mentioned above error. That's why you're not receiving the response, so you're not seeing the alert message.
In order to bypass the issue, you can either:
Enable CORS support
Render HTML file through the server (so request will be coming from the same domain).
Example here:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var path = require("path");
...
app.get("/", function(req, res)
{
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post("/signup", function(req, res)
{
var email = req.body.email;
if (!email)
{
return res.json({
message: "error occurred"
});
}
res.json({
success: true;
});
});

Switching Google reCaptcha Version 1 from 2

I have successfully designed and implemented Google reCaptcha Version 2 but now my Manager wants that to be of version 1 with numbers to be entered and validated. Is there a way to switch from later to former i.e.- from 2 to 1. I am using following library for reCaptcha:
<script src='https://www.google.com/recaptcha/api.js'></script>
Update..
To implement Captcha inside form i am using following HTML..
<form class="contact_form" action="#" method="post" name="contact_form">
<div class="frm_row">
<label id="lblmsg" />
<div class="clear">
</div>
</div>
<div class="g-recaptcha" data-sitekey="6Lduiw8TAAAAAOZRYAWFUHgFw9_ny5K4-Ti94cY9"></div>
<div class="login-b">
<span class="button-l">
<input type="button" id="Captcha" name="Submit" value="Submit" />
</span>
<div class="clear"> </div>
</div>
</form>
As i need to get the Captcha inside the above form to Validate and get the response on button click but as now i am using <script src="http://www.google.com/recaptcha/api/challenge?k=6Lduiw8TAAAAAOZRYAWFUHgFw9_ny5K4-Ti94cY9"></script> , so not getting the Captcha inside the form ..Please help me to get that ..Also here is the Jquery Ajax code to send the request on Server side code..
$(document).ready(function () {
alert("hii1");
$('#Captcha').click(function () {
alert("Hii2");
if ($("#g-recaptcha-response").val()) {
alert("Hii3");
var responseValue = $("#g-recaptcha-response").val();
alert(responseValue);
$.ajax({
type: 'POST',
url: 'http://localhost:64132/ValidateCaptcha',
data: JSON.stringify({ "CaptchaResponse": responseValue }),
contentType: "application/json; charset=utf-8",
dataType: 'json', // Set response datatype as JSON
success: function (data) {
console.log(data);
if (data = true) {
$("#lblmsg").text("Validation Success!!");
} else {
$("#lblmsg").text("Oops!! Validation Failed!! Please Try Again");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
}
});
}
});
});
Please help me ..Thanks..
You have to verify the reCaptcha at "http://www.google.com/recaptcha/api/verify" on Server side.
The parameters of this are:
privatekey: Your Private Key
remoteip: User's IP Address
challenge: Value of input[name=recaptcha_response_field]
response: Value of input[name=recaptcha_challenge_field]
Therefore, you have to post them on your server-side method like this:
cshtml file:
var recaptchaResponseField=$("input[name=recaptcha_response_field]").val();
var recaptchaChallengeField=$("input[name=recaptcha_challenge_field]").val();
// ajax block
$.ajax({
url: '/api/VerifyReCaptcha/', // your Server-side method
type: 'POST',
data: {
ipAddress: '#Request.ServerVariables["REMOTE_ADDR"]',
challengeField: recaptchaChallengeField,
responseField: recaptchaResponseField
},
dataType: 'text',
success: function (data) {
// Do something
},
Since you are using .NET so an example of C# code is as follows:
cs file:
using System.Net;
using System.Collections.Specialized;
[HttpPost]
public bool VerifyReCaptcha(string ipAddress, string challengeField, string responseField)
{
string result = "";
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues("http://www.google.com/recaptcha/api/verify", new NameValueCollection()
{
{ "privatekey", "{Your private key}" },
{ "remoteip", ipAddress },
{ "challenge", challengeField },
{ "response", responseField },
});
result = System.Text.Encoding.UTF8.GetString(response);
}
return result.StartsWith("true");
}

blank window with query of permissions

I use js sdk for login my site with facebook. If user go to my site first time and try login, it work fine. If user is logged into facebook and go to my site, it work fine too. But if user is logged out from facebook and my site and go to my site after click login button he see popup window and input their email and pass for facebook. After he click login it show blank popup window with this url.
I can't understand why it request permission if facebook know that this user is authorized for my site.
here is my code
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: 189221317879406, status: true, cookie: true, xfbml: true, oauth:true });
};
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
function loginWithFacebook(){
FB.login(function(response) {
if (response.authResponse) {
//FB.api('/me', function(response) {alert(response.name);});
window.location.href='http://mysite.com/home/';
}
},
{scope: 'user_photos,friends_photos,user_birthday,friends_birthday,user_education_history,friends_education_history,user_location,friends_location,user_relationships,friends_relationships,user_work_history,friends_work_history'});
}
</script>
<a href="#" onclick="loginWithFacebook()">
<img src="/files/images/facebook-login-button.png" style="width: 90px; height: 90px;"></a>
</body>
I was wrong in code. There neccessary add option - channelURL: '//site.com/channel.php'
http://developers.facebook.com/docs/reference/javascript/#channel