OT.Publisher.onStreamAvailableError Permission Denied - javascript

I'm working with OpenTok, trying to publish an app where a person shows a room and some clients can see, in order to buy it or not.
When using the example code in my localhost (and also in Firefox and nasty iExplorer) everything works smooth, but when I do it in Chrome i get this error in my JS Console:
OT.Publisher.onStreamAvailableError Permission Denied
I dont remember never saying "no" to any pop up that asked me permition to share my cam, so is not like "Chrome will remember my last choise".
Any help?
This is the code that I'm executing:
<?php
//Obviously I changed this.
$apiKey = "123456789";
$apiSecret = "VICTORIA's SECRET";
require '../vendor/autoload.php';
use OpenTok\OpenTok;
use OpenTok\MediaMode;
use OpenTok\Session;
use OpenTok\Role;
$opentok = new OpenTok($apiKey,$apiSecret);
$session = $opentok->createSession();
$sessionId = $session->getSessionId();
$data = array(
'role' => Role::PUBLISHER,
'data' =>""
);
$token = $session->generateToken($data);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>OpenTok Hello World</title>
<script src='https://static.opentok.com/v2/js/opentok.min.js'></script>
<!--script src="//static.opentok.com/webrtc/v2.2/js/TB.min.js"></script-->
<script type="text/javascript">
var token = '<?php echo $token; ?>';
var apiKey = '<?php echo $apiKey; ?>';
var sessionId = '<?php echo $sessionId; ?>';
var session = TB.initSession(sessionId);
var publisher = TB.initPublisher(apiKey, 'subscribers');
// Attach event handlers
session.on({
sessionConnected: function(event)
{
session.publish(publisher);
},
streamCreated: function(event)
{
var subContainer = document.createElement('div');
subContainer.id = 'stream-' + event.stream.streamId;
document.getElementById('subscribers').appendChild(subContainer);
session.subscribe(event.stream, subContainer);
}
});
session.connect(apiKey, token);
</script>
</head>
<body>
<h2>Hello, Universe!</h2>
<div id="publisher"></div>
<div id="subscribers"></div>
</body>
</html>
When I check the JS Console, I get this warning:
getUserMedia() no longer works on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.
An also this Error:
OT.Publisher.onStreamAvailableError Permission Denied
This is our development server, so is not https.
EDIT:
After checking the OpenTok JS that I have to load at the beging, I realice this:
// The user has clicked the 'deny' button the the allow access dialog
// (or it's set to always deny)
var onAccessDenied = function(error) {
if (_isScreenSharing) {
if (global.location.protocol !== 'https:') {
/**
* in http:// the browser will deny permission without asking the
* user. There is also no way to tell if it was denied by the
* user, or prevented from the browser.
*/
error.message += ' Note: https:// is required for screen sharing.';
}
}
logging.error('OT.Publisher.onStreamAvailableError Permission Denied');
So, It won't ask me if I'm using http. There's a way to workaround this? Overwrite this behavior?

Related

Google Sign In not being signed in when page refreshes (Polymer)

I'm implementing "Google Sign In" into my website to handle all user authentication etc.. I will have a back-end database that I use to store information against users to keep track of their profile and their actions etc..
I've followed the Google Developer documentation and have got a "Google Sign In" button on a web page and when this button is clicked I choose my account and am signed in and the id_token goes off and is authenticated with my back-end server successfully. The only problem I'm now having is that when I refresh the page the button is back to "Sign In" rather than staying signed in, is this normal behaviour or is there something I'm missing? I don't want users to have to have to sign in again whenever the page changes.
On a side note I have managed to store the id_token from successfully logging into Google in localStorage and then using this id_token to re-authenticate with the back-end server automatically (as you can see in the commented out code) but this doesn't obviously automatically change the status of the "Google Sign In" button which would confuse users on the client-side.
Can anyone shed any light on this problem please?
Not signed in:
After signing in (doesn't currently stay like this after a page refresh):
login.html:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/base.css"/> <!-- Base CSS -->
<script src="./js/all.js"></script> <!-- All JavaScript file -->
<script src="./js/Logger.class.js"></script> <!-- Logger class -->
<script src="./bower_components/jquery/dist/jquery.min.js"></script> <!-- jQuery -->
<script src="./js/gSignIn.js"></script>
<!-- Polymer -->
<script src="./bower_components/webcomponentsjs/webcomponents-lite.min.js"></script> <!-- Web Components Import -->
<!-- Element Imports -->
<link rel="import" href="./bower_components/paper-button/paper-button.html"/>
<link rel="import" href="./bower_components/google-signin/google-signin.html"/>
</head>
<body>
<google-signin id="gSignIn" client-id="--- REMOVED FOR PRIVACY ---" scopes="profile email openid"></google-signin>
Sign Out
</body>
</html>
gSignIn.js:
/**
* Google Sign In JavaScript
*/
$(document).ready(function() {
var logger = new Logger("gSignIn.js", false); // logger object
var id_token = null;
logger.log("Load", "Successful");
// Try to automatically login
// if (localStorage !== null) { // If local storage is available
// if (localStorage.getItem("gIDToken") !== null) { // If the Google ID token is available
// id_token = localStorage.getItem("gIDToken");
// // Send off AJAX request to verify on the server
// $.ajax({
// type: "POST",
// url: window.api.url + "googleauth/verify/",
// data: { "id_token": id_token },
// success: function (data) {
// if (!data.error) { // If there was no error
// logger.log("Google SignIn", "Successfully signed in!");
// }
// }
// });
// }
// }
/**
* EVENT: Google SignIn success
*/
$("#gSignIn").on("google-signin-success", function () {
id_token = getGoogleAuthResponse().id_token;
var profile = getGoogleProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log("Name: " + profile.getName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// Send off AJAX request to verify on the server
$.ajax({
type: "POST",
url: window.api.url + "googleauth/verify/",
data: { "id_token": id_token },
success: function (data) {
if (!data.error) { // If there was no error
logger.log("Google SignIn", "Successfully signed in!");
// Store the id_token
if (localStorage !== null) { // If localStorage is available
localStorage.setItem("gIDToken", id_token); // Store the id_token
}
}
}
});
});
$("#signOut").click(function () {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log("User signed out.");
});
});
/**
* Get Google Profile
*
* #returns object
*/
var getGoogleProfile = function () {
var profile = gapi.auth2.getAuthInstance().currentUser.get().getBasicProfile();
return profile;
};
/**
* Get Google Auth Response
*
* #returns object
*/
var getGoogleAuthResponse = function () {
var response = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse();
return response;
};
});
Thanks!
I had the same problem and, after ensuring third party cookies were enabled, it came down to the hostname, localhost in this case.
In the end, I had to fake a domain using /etc/hosts, ensure google developers dashboard has that domain whitelisted, and start using that domain instead of localhost.
I can only assume that gapis don't like localhost, even though it's whitelisted in my google developers dashboard for the account I'm using. If you do manage to get localhost to work, do give me a shout!
Another way to do this is to access localhost from a nonstandard port (not 80). I managed to get around this headache by using an nginx proxy from port 80 to 81:
server {
listen 81;
location / {
proxy_pass http://localhost:80;
}
}

Paypal lightbox: does not permit cross-origin framing

I have attempted to go about the use of Paypal Lightbox a bit differently.
I have used a button to trigger an ajax call which then generates the PayKey and if all goes well then triggers the form (from the documentation) to be created and submitted.
When i click the button the lightbox html is created but the content is not loaded into it. Instead i get the error:
Load denied by X-Frame-Options: https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_dispatch-failed does not permit cross-origin framing.
My Code:
<head>
<script src="https://www.paypalobjects.com/js/external/dg.js" type="text/javascript"></script>
</head>
External Script:
$("#checkout").click(function() {
var id = $(this).data("id");
if(id) { pay(id); }
});
function pay(id) {
$.ajax({
url : 'paypal/Pay-Chained.php',
type : 'POST',
data : "id="+id,
success : function (data) {
var info = (JSON.parse(data));
if (info['Type'] == 'Success') {
var output = info['URL'].substr(0, 64) + "expType=light&" + info['URL'].substr(64);
$("body").append('<form action="'+output+'" target="PPDGFrame" class="standard"><input type="submit" id="submitBtn"></form>');
$("#submitBtn").click();
} else {
alert("Error: Please try again or contact support.");
}
},
error : function () {
alert("Error: Please try again.");
}
});
}
At the bottom of the buttons page:
<script type="text/javascript" charset="utf-8">
var embeddedPPFlow = new PAYPAL.apps.DGFlow({trigger: 'checkout'});
</script>
I am thinking maybe it has to do with the order things are executed but can't seem to figure it out. Any help would be great!
EDIT: I just created a blank page and copied the script from the documentation exactly. I still get the same error. Might it have something to do with server settings? I am running a WampServer with an address like 192.168.1.1/mysite/index.html.

how do you get twitter timeline through oauth using javascript

Im currently trying to get users timeline data from twitter through the oauth process and I cant get it to work.
I tried a few things here http://bytespider.github.com/jsOAuth/ and I keep running into the same problem.
Whoa there!
There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.
It cant be this hard to do this right?
Here is my code
<html>
<head>
<title></title>
</head>
<body>
<script src="jsOAuth-1.3.4.min.js"></script>
<script>
var config = {
consumerKey: "[removed]",
consumerSecret: "[removed]",
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizationUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
};
var oauth = new OAuth(config);
oauth.fetchRequestToken(openAuthoriseWindow, failureHandler);
function openAuthoriseWindow(url)
{
var wnd = window.open(url, 'authorise');
setTimeout(waitForPin, 100);
function waitForPin()
{
if (wnd.closed)
{
var pin = prompt("Please enter your PIN", "");
oauth.setVerifier(pin);
oauth.fetchAccessToken(getSomeData, failureHandler);
}
else
{
setTimeout(waitForPin, 100);
}
}
}
function getSomeData()
{
oauth.get("https://api.twitter.com/oauth/something/?format=jsonp", function (data) {
console.log(data.text);
}, failureHandler);
}
function failureHandler(data)
{
console.error(data);
}
</script>
</body>
</html>
I also get this error in console
OPTIONS https://api.twitter.com/oauth/request_token 403 (Forbidden)
EDIT: Does anyone know how to do this? Cant even find a good resource on twitter. Also can you achieve this without pin and just have users enter their login details?
Thanks in advance

FB.getLoginStatus() not working

I am trying to write a code that checks whether the user is logged in or not,
and found that there is a built-in method in FBJS API, which is called getLoginStatus()
I have implemented it inside of html,
but for some how, alert() inside of the getLoginStatus() is not fired.
I have also tried to add channelUrl at init(),but it still does the same.
Below is the code that I have written.
Can anyone help me with it?
Thanks in advance!
<!-- Initialize FB API for use -->
<div id="fb-root"></div>
<script type="text/javascript">
//var curLoc = window.location;
//var chanURL = curLoc.protocol + "//" + curLoc.hostname + ":" +
//curLoc.port + "/channel.html"
window.fbAsyncInit = function() {
FB.init({appId: '####', status: true, cookie: true, xfbml: true});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
alert('logged in');
} else {
// no user session available, someone you dont know
alert('not logged in');
}
});
};
(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);
}());
</script>
I had this the other day and the problem was that I was NOT logged in in Facebook AND my App was in Sandbox mode. Maaaaybe it's the same here, longshot but wanted to suggest it anyway.
Note: Comparable combinations that wouldn't work are being logged in in Facebook as a Test user that has no access to the application in question or being logged in in Facebook as a non-test/non-admin user AND having the app in sandbox mode.
BTW. They changed it again.
It is now:
response.authResponse
and not response.session anymore.
I was having the same problem. I was caused by the 'Sandbox Mode' in the FB App settings. When enabled, it won't fire the getLoginStatus() response. Probably because it is unknown if you're actually a registered developer when not logged in.
They changed it. Run console.log on response, and see you need to test as so:
if (response.status=='connected')) {...}
edit: here is most of my login:
<?php
// using Facebook PHP SDK (v.3.1.1)
$facebook = new Facebook(array(
'appId' => APP_ID
'secret' => SECRET
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
and the js in the body:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
status : true,
cookie : true,
oauth: true,
channelUrl : MY_CHANNEL_URL,
xfbml : true
});
FB.getLoginStatus(function(response) {
console.log( response );
if ((response.status)&&(response.status=='connected')) {
loadStreamInto ( $("#FBmessages") );
} else {
}
});
};
</script>
I assume you replaced you actual appId with #### in the code you linked. If not, that is your problem.
Assuming you have actually placed your appId in here, it could be related to the fact that you are testing on localhost. I believe that the javascript will not function if the url it is being served from does not match up with the url associated with the app for the given App Id
the response.status=='connected' happens only if you put oauth:true in fb.init
code looks fine to me should work as is not sure why it doesn't work
I'm not saying this would work for you, but I had a similar problem with my deployed app. It worked fine on my localhost but not when deployed to Heroku. I realised that in the Facebook App settings I had the urls all set as local ones - when I changed this to my deployed app url it fixed it.

How to send web browser a loading page, then some time later a results page

I've wasted at least a half day of my company's time searching the Internet for an answer and I'm getting wrapped around the axle here. I can't figure out the difference between all the different technology choices (long polling, ajax streaming, comet, XMPP, etc.) and I can't get a simple hello world example working on my PC.
I am running Apache 2.2 and ActivePerl 5.10.0. JavaScript is completely acceptable for this solution. All I want to do is write a simple Perl CGI script that when accessed, it immediately returns some HTML that tells the user to wait or maybe sends an animated GIF. Then without any user intervention (no mouse clicks or anything) I want the CGI script to at some time later replace the wait message or the animated GIF with the actual results from their query.
I know this is simple stuff and websites do it all the time using JavaScript, but I can't find a single working example that I can cut and paste onto my machine that will work in Perl.
Here is my simple Hello World example that I've compiled from various Internet sources, but it doesn't seem to work. When I refresh this Perl CGI script in my web browser it prints nothing for 5 seconds, then it prints the PLEASE BE PATIENT web page, but not the results web page. So the Ajax XMLHttpRequest stuff obviously isn't working right. What am I doing wrong?
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub Create_HTML {
my $html = <<EOHTML;
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" content="-1" />
<script type="text/javascript" >
var xmlhttp=false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#end #*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
</script>
<title>Ajax Streaming Connection Demo</title>
</head>
<body>
Some header text.
<p>
<div id="response">PLEASE BE PATIENT</div>
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
print Create_HTML();
sleep(5);
print "<script type=\"text/javascript\">\n";
print "\$('response').innerHTML = 'Here are your results!';\n";
print "</script>\n";
If your process relies on query-string parameters, a simple meta-refresh would suffice. E.g. if they load http://yoursite.com/message?foo=1, then that can output a meta tag like:
<meta http-equiv="refresh" content="0; http://yoursite.com/realquery?foo=1" />
And some HTML that has your "please wait" message. The realquery script would actually execute the query and the HTML output by message will remain on the screen until realquery provides some output.
If the query relies on POST data, then it gets a little more complicated, because you can't redirect a POST. You can, however, output a form with some hidden fields and use Javascript to submit it. For example:
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'form_with_hidden_fields' ).submit();
}
</script>
<form method="POST" action="realquery" id="form_with_hidden_fields">
<input type="hidden" name="foo" value="1" />
...
</form>
Please wait while your query is processed...
If you're interested in an AJAX solution, here's an example using jQuery:
$( '#submit-button' ).click( function() {
// show a "please wait" image
$( '#status-div' ).html( '<img src="please_wait.gif" />' ); // animated gif
// get form values
var formdata = { foo: $( 'input#foo' ).val(),
...
};
// submit form via ajax:
$.ajax( { type: "POST", url: "/realquery", data: formdata, success: function() {
$( '#status-div' ).html( '<img src="success.gif" />' );
} );
} );
And you could attach that to a form like:
<form>
<input type="text" name="foo" id="foo" />
<input type="submit" id="submit-button" />
<div id="status-div"> </div>
</form>
The empty status-div div will receive an image tag that points to a "please wait" image (this can be an animated gif). When the Ajax query finishes, it's replaced by a "success" image.
See Watching long processes through CGI by Randal Schwartz.
Here is a complete working example using friedo's HTTP meta refresh solution. This is not my personal first choice solution because it modifies the URL in the browser and it also refreshes the whole web page.
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub html_page {
my ( $meta_string, $results_string ) = #_;
my $html = <<EOHTML;
<html>
<head>
$meta_string
<title>Two Stage Web Page Demo</title>
</head>
<body>
Some header text.
<p>
$results_string
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
if ($cgi->param()) {
if ($cgi->param('doResults') eq "true") {
sleep(5);
print html_page('', 'Here are your results!');
}
}
else {
my $meta_refresh = '<meta http-equiv="refresh" content="0; /cgi-bin/twoStageScript.pl?doResults=true" />';
print html_page($meta_refresh, 'PLEASE BE PATIENT');
}
exit;
Finally got an Ajax version working. The slow.pl file is the file that takes a while to return.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Two Stage web page demo using Ajax</title>
</head>
<body>
<h1>Two Stage web page demo using Ajax</h1>
<div id="result">
Users input form goes here.
<p>
<input type="submit" value="Here is your submit button" id="load_basic" />
</div>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "Please be patient, this could take a while. <p> <img src='img/load.gif'/>";
// load() function
$("#load_basic").click(function(){
$("#result").html(ajax_load).load("/cgi-bin/slow.pl");
});
</script>
</body>
</html>

Categories