Ajax request issue in sencha touch 2 - authentication

I have a problem with sending an ajax request for the authentification..
i dont get errors but Network in chrome says : method : get , status : canceled , type : pending
and no response from this request ..
when i click on the file connection.js it point in this line :
// start the request!
xhr.send(requestOptions.data);
& my path name and the method get have the color RED
here is my code :
Ext.onReady(function() {
Ext.Ajax.request({
url: 'https://api.mysite.com/api/oauth/',
method: 'GET',
useDefaultXhrHeader:false,
disableCaching: false,
timeout:120000,
params: {
client_id: 'xxxxxx',
client_secret: 'xxx',
format: 'json'
},
success: function(response) {
var resultat = Ext.JSON.decode(response.responseText);
//the response is : {"status":"ok","auth_token":"xxxxxxxxxxx"}
if (resultat.status === "ok") {
if (!resultat.access_token === "") {
access_token = resultat.access_token;
me.sessionToken = resultat.sessionToken;
}
else
{
new Ext.Ajax.request({
url: 'https://api.mysite.com/api/oauth/signin',
method: 'post',
params: {
username: username,
password: password,
authtoken: resultat.access_token,
format: 'json'
},
success: function(response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "true") {
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
me.sessionToken = loginResponse.sessionToken;
me.signInSuccess(); //Just simulating success.
} else {
me.signInFailure(loginResponse.message);
}
},
failure: function(response) {
me.sessionToken = null;
me.signInFailure('Login failed. Please try again later.');
}
});
}
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
} else {
//exception
}
}
,
failure: function(response) {
me.sessionToken = null;
Ext.Msg.alert('failed !!'); // its what it shows me
}
});

Related

How to read the response returned to a Twilio function from another function?

Really basic question - I'm calling a twilio function from another twilio function to retrieve the ID of a salesforce record. The following code is what gets returned from one function to another. I'm just trying to "read" the contents of the response to get the ID but can't seem to figure it out. I confirmed that the function returning the response works correctly (contains the right data.)
Help is much appreciated!
responsebody
2020-11-24T19:38:02.642Z 13c8fae2-5f74-40c2-942a-d6aa7ed85c48 INFO Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object] },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'https://coxczsdlk-dffcat-8307.twil.io/sf-get-record',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object] },
counter: 0 } }
Here's the code for the function returning this response - this line returns the correct ID - response.body.records[0].Id
const querystring = require('querystring');
const request = require('request');
let globalCallback;
exports.handler = function(context, event, callback) {
globalCallback = callback;
console.log("Starting");
console.log("event: ", event);
run(context.DOMAIN_NAME, event);
};
function run(domain, event){
request({
uri: `https://${domain}/sf-access-token`,
method: 'GET'
}, function (err, res, body) {
if(res.statusCode == 200){
// Received Access Token. Now build and send the request
processRequest(JSON.parse(body), event);
} else{
globalCallback(`Error getting token: ${res.body}`);
}
});
}
function processRequest(sfAuthReponse, event){
// if(validateRequest(event)) {
var options = {
// uri: `${sfAuthReponse.instance_url}/services/data/v43.0/query/?q=SELECT+id+From+${event.objectAPIName}+WHERE+callSID__c='${event.callSID}'`,
uri: `${sfAuthReponse.instance_url}/services/data/v43.0/query/?q=SELECT+id+From+Case+WHERE+callSID__c='1'`,
headers: {
'Authorization': 'Bearer ' + sfAuthReponse.access_token,
'Content-Type': 'application/json',
},
body: event.fields,
json:true,
method: 'GET'
};
request(options, processResponse);
// }
}
function validateRequest(event) {
let valid = false;
let validationMessage;
if(!event.objectAPIName || event.objectAPIName.trim().length === 0) {
validationMessage = "Parameter, objectAPIName, was not set in the JSON Request Body. Provide the SF API Name of the object to create";
} else if (!event.fields) {
validationMessage = "Parameter, fields, was not set in the JSON Request Body. Provide this parameter with a JSON value representing the fields to set when creating the SF object.";
} else {
valid = true;
}
if(!valid) {
globalCallback(validationMessage);
}
return valid; // <== This will always return true since execution is terminated with the callback if invalid
}
function processResponse(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('response.body.records[0].Id');
console.log(response.body.records[0].Id);
// Successfully created new object. Response 201 from successful object creation
//globalCallback(null, response.body.records[0].Id);
globalCallback(null, response);
} else{
console.log("Error: ", error);
console.log("Response: ", response);
console.log(body);
globalCallback(body);
}
}
and here's some of the code for the first function calling the above function, not sure how to dot notation into the response.
fetch('https://casdflk-dsfdsfat-8707.twil.io/sf-get-record', {
headers: {
'Authorization': 'Basic ' + context.ENCODED_TWILIO_CREDS,
'Content-Type': 'application/json'
},
method: 'POST',
body: {
objectAPIName: 'Case',
callSID: '1',
}
// callback(null,sid);
}).then(record => {
console.log('recordbody11');
console.log(record.body);
return record;
It looks like you are using fetch.
Fetch has a method .json() that you need to call on the response.
See the MDN page
Is that your question or did I miss something?

Google OAuth2 in external window Asp.Net Core

I'm trying to implement google oauth external authorization to happen in external browser window. My code looks like below:
$('#signinButton').click(function () {
window.auth2.grantOfflineAccess()
.then(signInCallback)
.catch(error => console.log(error));
});
function start() {
gapi.load('auth2', function () {
window.auth2 = gapi.auth2.init({
client_id: 'CLIENT_Id'
});
});
};
function signInCallback(authResult) {
if (authResult['code']) {
var authCode = authResult['code'];
$.ajax({
type: 'POST',
url: '/Auth/GooglePostredirect',
data: authCode,
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function (result) {
},
processData: false,
});
} else {
}
};
And the question is after getting authToken, how i should call google api to get user info by auth token. Is there any handy libraries for that? I can't find any to request userInfo by token from c#.
Thanks you all in advance!
You can use Google.Apis.Auth library from nuget package manager, and get info from google token, which you get from your front-end
public async Task<IActionResult> ExternalLoginGoogleAsync(string googleTokenId)
{
GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
settings.Audience = new List<string>() { Configuration["Authentication:Google:ClientId"] };
GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(googleTokenId, settings);
ApplicationUser user = await _userManager.FindByEmailAsync(payload.Email);
if (user == null) //create new user if not exsits
{
user = new ApplicationUser
{
Email = payload.Email,
UserName = payload.Name
};
...
}
return Ok(something);
}

How to check unwrapError

var users = m.request({
method: "GET",
url: "hoge.json",
unwrapSuccess: function(response) {
return response;
},
unwrapError: function(response) {
//return response.error;
return "404 error";
}
});
users.then(function(result) {
console.log(result);
});
After delete "hoge.json".
I want to catch "404 error",but
uncaught SyntaxError: Unexpected token <
2016/2/18 add
I want to test alert ("unwrapError");
Below code is always alert ("unwrapSuccess");
How to change below code?
What is the unwrapError?
▼js
var users = m.request({
method: "GET",
url: "hoge.json",
unwrapSuccess: function(response) {
alert ("unwrapSuccess");
return response;
},
unwrapError: function(response) {
alert ("unwrapError");
return "error";
}
});
users.then(function(result) {
console.log(result);
});
▼hoge.json
[{"name": "John"}, {"name": "Mary"}]
If you take a look at mithril's source code you will see that m.request is just a wrapper for the XMLHttpRequest API. And that's what happens when the request's readyState attribute changes:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
options.onload({type: "load", target: xhr})
} else {
options.onerror({type: "error", target: xhr})
}
}
}
So mithril's unwrapError callback will be called whenever the response status is not a 2xx.
I updated the fiddle calling a URL that returns a 500 response and now the unwrapError is called.

Hapi.js reply.redirect() is not working after image upload

I have the following code, in my server. I'm uploading an image using mongoose and s3 and then want to redirect the user to another page but this isn't happening. (the upload is successful).
Routes.js:
{path: '/success', method: 'GET', config: controller.success} ......
controller.js:
imageUpload: {
payload: {
maxBytes: 209715200,
output: 'file',
parse: true
},
handler: function(request, reply) {
var userName = request.auth.credentials.username;
members.findMemberByUsername(userName, function(err, member){
if (err) {
return reply.view('upload', {error: err});
} else if (member) {
var IDImagePath = request.payload.uploadedIDname.path;
console.log(IDImagePath);
members.addID(member, IDImagePath, function(err1){
console.log("add id error", err1);
if (err1){
return reply.view('upload', {error: err1, member: member});
} else {
console.log("SUCCESSFUL!");
return reply.redirect('/success');
}
});
}
});
}
},
success: {
handler: function (request, reply){
request.auth.session.clear();
console.log("success handler working!!");
return reply.view('success');
}
}
The code hits both console.log("SUCCESSFUL") and console.log("success handler working!!") in the controller but the redirect doesn't take place. By the way I'm using 'Jade' as the templating language so I have a success.jade. Thanks.
I found out what the problem was. I'm using AJAX on the client side but didn't have a 'success' method to reload the page:
$('#submitID').click(function(){
var formData = new FormData($('#uploadID')[0]);
$.ajax({
url: '/api/image',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
console.log(myXhr.upload);
}
return myXhr;
},
success: function(data) {
window.location.href = "/success"
},
data: formData,
cache: false,
contentType: false,
processData: false
}, "json");
});
I needed window.location.href = "/success" to reload the page. Please note the jQuery Ajax SUCCESS method is different to my '/success' route, they just happen to be the same word.

Sencha Touch 2 Session Storage

I had created an ajax request in sencha touch 2, when i get a success message how can i set my return values to session and please also tell me a way through which i can get the value from session also.
submitLoginForm: function() {
var form = this.getLoginForm().getValues();
Ext.Ajax.request({
url: '../../authenticate.php',
method: 'POST',
params: {
email: form.email,
password: form.password
},
success: function(response) {
var json = Ext.decode(response.responseText);
if(json.message == 'success') {
Ext.Msg.alert('Login Success.....');
//Here i want to store return data in session
} else {
Ext.Msg.alert('Invalid Login Or Password.....');
}
},
failure: function(response) {
Ext.Msg.alert('The request failed.....');
}
});
},
on Success response, use HTML5 local storage to set and get the session variables:
var sessionObject = { 'var1': 1, 'var2': 2, 'var3': 3 };
// Put the session object into storage
localStorage.setItem('sessionObject ', JSON.stringify(sessionObject ));
// Retrieve the session object from storage
var sessionObject = localStorage.getItem('sessionObject ');
console.log('sessionObject : ', JSON.parse(sessionObject ));