XSocket.Longpolling fallback on MVC 3 - xsockets.net

Having some problems with this one.
MVC3, .NET 4.0, jQuery 1.11.0, XSockets 3.0
Client:
IE8 or Firefox(websocket=false)
<script src="jquery-1.11.0.min.js"></script>
<script src="jquery-migrate-1.2.1.min.js"></script>
<script src="json2.min.js"></script>
<script src="XSockets.fallback.latest.js"></script>
<script src="XSockets.latest.js"></script>
$(function() {
var conn = new XSockets.WebSocket("ws://127.0.0.1:4502/Generic");
conn.onopen = function (connection) {
// connection is open, subscribe to the 'foo' topic
conn.on('foo', function (d) {
//Data for the topic 'foo' arrived, add message to the page
$('#content').append("<p>" + d + "</p>");
});
};
});
Server:
IIS Express, Windows Authentication
routes.MapRoute(
"Fallback",
"{controller}/{action}",
new { controller = "Fallback", action = "Init" },
new[] { "XSockets.Longpolling" }
);
Result:
"NetworkError: 404 Not Found - localhost:63360/Fallback/Init?url=ws%3A%2F%2F127.0.0.1%3A4502%2FGeneric%3FXSocketsClientStorageGuid%3D910d22f70cac4843832bd9f14ad9a549&storageGuid=&_=1401110430404"

You need MVC4 minimum for using the XSockets.NET longpolling fallback.
And also... As of 4.0 XSockets.NET will remove the fallback for MVC and only support .NET 4.5 WebAPI fallback. The IIS8 option will also be removed and focus will be on using OWIN if not self-hosting XSockets.NET
EDIT: typo

Related

Occasional 403 CSRF error in React Native WebView

I am loading a form (powered by Django) in a React Native app using react-native-webview. This form has CSRF protection. And most of the time it actually works fine, you can submit the form in the app through the webview and everything is fine. But sometimes I get a 403 CSRF error (CSRF verification failed, Request aborted).
I'm not sure what could be causing this and how could it be avoided? I'm using the WebView in a fairly straightforward way with a wrapper around it.
If there was a network connection issue on the mobile phone then I would probably get a timeout error instead right, not something specific like this?
import { WebView as BaseWebView } from 'react-native-webview';
const FullScreenWebView = styled(BaseWebView)`
flex: 1;
`;
...
export const WebView: FC<WebViewProps> = props => {
...
return (
<Layout.Root>
{url.startsWith('/') ? (
<Layout.LoadingFlex1 />
) : (
<FullScreenWebView
ref={webviewRef}
source={{ uri: urlWithLang }}
startInLoadingState={true}
onShouldStartLoadWithRequest={globalZendeskIntercept}
// only allow secure webviews and those for our deeplink scheme
originWhitelist={['https://', `${Config.DEEPLINK_SCHEME}://`]}
decelerationRate="normal"
allowsBackForwardNavigationGestures
onNavigationStateChange={navState => {
if (navState.canGoBack) {
setCanGoBack(true);
} else {
setCanGoBack(false);
}
}}
/>
)}
</Layout.Root>
);
};
I had a similar problem somewhat which turned out to be due to stale cookies in iOS WebView.
All I did was clear all the cookies before and after the WebView component was rendered to be sure.
import CookieManager from "#react-native-cookies/cookies";
...
useEffect(() => {
CookieManager.clearAll().catch(console.error);
return () => {
CookieManager.clearAll().catch(console.error);
};
}, []);
...
<WebView ... />
Maybe you can give it a try.

redirect to stripe checkout

i have my website in ruby on rails 5 and i'm updating my stripe payment gateway with this link but clicking my button doesn't redirect me to the stripe checkout, this is what i have in the controller:
def index
Stripe.api_key = Rails.configuration.stripe[:secret_key]
session = Stripe::Checkout::Session.create(
payment_method_types: ['card'],
line_items: [{
price: 'price_1HKywnBS16ZK5Vr3GYCRvTir',
quantity: 1,
}],
mode: 'subscription',
success_url: 'https://www.my_site.network/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url: 'https://www.my_site.network/cancel',
)
end
I think the error may be when replacing the session id in the javascript code of my index view:
<button id="checkout-button">Pay</button>
<script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
var stripe = Stripe('<%= Rails.configuration.stripe[:publishable_key] %>');
var checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', function() {
stripe.redirectToCheckout({
// Make the id field from the Checkout Session creation API response
// available to this file, so you can provide it as argument here
// instead of the {{CHECKOUT_SESSION_ID}} placeholder.
sessionId: '<%=session.id%>'
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});
});
</script>
you don't have to use '<%=session.id%>'.
The value that you must to use there is the entire value that you store in session when you do: Stripe::Checkout::Session.create in your controller.

Facebook JS SDK CORS problems

I'm working with Facebook js SDK "Go Live Dialog" for live streaming, every thing works fine until the last step when I want to publish the stream and I can't publish because there is a CORS error, it is:
XMLHttpRequest cannot load https://graph2.facebook.com/v2.5/10154376393778843?access_token=EAAOAPyi8mX....&suppress_http_code=1. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, https://www.facebook.com/', but only one is allowed. Origin 'https://www.facebook.com/' is therefore not allowed access.
the issue is due to graph2.facebook.com is sending CORS header twice:
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: https://facebook.com/
and Google Chrome accepts only one.
I opened it as a bug on facebook but until now their answers is to "disable CORS security" on my browsers, a bad solution if I want to make my app public for every one.
The code for the app is this:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '452751035113070',
xfbml : true,
version : 'v2.8'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<button id="liveButton">Create Live Stream To Facebook</button>
<script>
document.getElementById('liveButton').onclick = function() {
FB.ui({
display: 'popup',
method: 'live_broadcast',
phase: 'create',
}, function(response) {
if (!response.id) {
alert('dialog canceled');
return;
}
console.log('stream url:' + response.secure_stream_url);
FB.ui({
display: 'popup',
method: 'live_broadcast',
phase: 'publish',
broadcast_data: response,
}, function(response) {
console.log("video status: \n" + response.status);
});
});
};
</script>
also here here: https://plnkr.co/edit/Aq0hkCTh5suXfOl6qKuN?p=preview .
To make a real try you should start an streaming using wowza or similar, if not, the publish button is disabled and the problem occurs when I click the publish button.
did someone know how to handle it to allow all users to use the script and to force them to use other browsers or to disable the security options? or I need to wait until facebook fix it?
I Disable a Chrome extension and it works.
The extension is: JetBrains IDE Support 2.0.9
this is strange because every post talk about you can't have 2 CORS directives and I think the server keeps sending 2 directives or maybe the server send just 1 and this extensions modify the headers...I don't know, but now ir works.

Implementing Django and socket.io to work together

I am following this tutorial to build a realtime application using Django and Socket.io (node js). I am building this inside a vagrant box, and has configured the vagrant machine in my host file. Now since the tutorial is an old post, I got many errors. However after fixing some deprecated codes, this is what it looks like.
chat.js:
var server = require('http').createServer().listen(4000);
var io = require('socket.io').listen(server, {
'authorization': function(data, accept) {
if (data.headers.cookie) {
data.cookie = cookie_reader.parse(data.headers.cookie);
return accept(null, true);
}
return accept('error', false);
}
});
var cookie_reader = require('cookie');
var querystring = require('querystring');
var redis = require('redis');
var sub = redis.createClient();
sub.subscribe('chat');
io.on('connection', function (socket) {
sub.on('message', function(channel, message){
socket.send(message);
});
socket.on('send_message', function (message) {
values = querystring.stringify({
comment: message,
sessionid: socket.handshake.cookie['sessionid'],
});
var options = {
host: 'localhost',
port: 80,
path: '/node_api',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': values.length
}
};
//Send message to Django server
var req = http.get(options, function(res){
res.setEncoding('utf8');
//Print out error message
res.on('data', function(message){
if(message != 'Everything worked :)'){
console.log('Message: ' + message);
}
});
});
req.write(values);
req.end();
});
});
index.html:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="{% static "js/socket.io.js" %}"></script>
<script>
$(document).ready(function () {
var socket = io('http://localhost:4000');
socket.on('connect', function () {
console.log("connect");
});
...
...
...
</script>
But now when I load the page I am stuck with this error
GET http://localhost:4000/socket.io/?EIO=3&transport=polling&t=LA7JSiV net::ERR_CONNECTION_REFUSED
When in the index.html I change this
var socket = io('http://localhost:4000');
to this
var socket = io();
I get this error
GET http://vagrant-box.com/socket.io/?EIO=3&transport=polling&t=LA7NH61 404 (NOT FOUND)
What am I doing wrong? Please help me solve this problem. Your help will be very much appreciated. Thank you.
First notice that you can't serve the socket.io js from django, socket.io has to serve it's own js files because it does some clever magic to determine the files it has to send.
Change
<script src="{% static "js/socket.io.js" %}"></script>
to
<script type="text/javascript" src="http://localhost:4000/socket.io/socket.io.js"></script>
(you will have to change these urls on production)
after that you must let socket.io know the exact schema, host and port to connect to the node.js server or you will get a 404 as socket will try to connect to the port your django server is listening at.
var socket = io('http://localhost:4000');

Html4 browsers does not support history.pushState and history.replaceState methods of History API from HTML5

I am working on an ember application (using ember-1.0.pre.js). And I'm trying to provide cross browser compatibility on IE8.
The issue is with url generate after every transition, it seems incorrect/falsy to user. Let say I hit the url like the_ domain_name/sell/new which initially land me to on sell page of our application. and then i tries to transit a new state called "Purchase" which will land me on purchase page of our application. The new state transition generates a URL the_ domain_name/sell/new#/offers/purchase?&suid=1365149991779013736531657156165 in IE8 addressbar instead of the domain_name/offers/purchase.
Note: the_domain_name = http://www.example.com
The generated url includes two incorrect things,
The initial prefix "/sell/new#".
The parameter "?&_suid=1365149991779013736531657156165" in query string of url.
I tried to figure out the issue and found that HTML4 browsers does not supports pushState and replaceState methods from History API from HTML5. How can i provide the support on IE8 Can anyone help me on this?
I suggest History.js as polyfill for browsers not support History API: https://github.com/browserstate/history.js
It is working in:
HTML5 Browsers:
Firefox 4+
Chrome 8+
Opera 11.5
Safari 5.0+
Safari iOS 4.3+
HTML4 Browsers:
IE 6, 7, 8, 9
Firefox 3
Opera 10, 11.0
Safari 4
Safari iOS 4.2, 4.1, 4.0, 3.2
Add jquery.history.js & Register a history.js location handler into you Ember App.
Here are the parts I modified from original Ember.HistoryLocation ( Full code )
(function() {
var get = Ember.get, set = Ember.set;
var popstateFired = false;
Ember.HistoryJsLocation = Ember.Object.extend({
initState: function() {
this.replaceState(this.formatURL(this.getURL()));
set(this, 'history', window.History);
},
getState: function() {
return get(this, 'history').getState().state;
},
pushState: function(path) {
History.pushState({ path: path }, null, path);
},
replaceState: function(path) {
History.replaceState({ path: path }, null, path);
}
});
Ember.Location.registerImplementation('historyJs', Ember.HistoryJsLocation);
})();
Then use this polyfill in your App:
App.Router.reopen({
location: 'historyJs'
});