I'm doing a project for University where I have a login for a website and I have to implement some operations. My issue is to maintain user session when a user is logged; so, if I open the website in a new tab, I want to be logged with the account of the main tab.
This is my angularjs code for the loginController:
mainAngularModule
.controller('LoginCtrl', ['$scope', '$state', 'AuthFactory',
function ($scope, $state, AuthFactory) {
let ctrl = this;
ctrl.authRequest = {username: 'admin', password: 'password'};
ctrl.doLogin = doLoginFn;
ctrl.authMessage = '';
//check if user already logged
let logSession = localStorage.getItem(("authinfo"));
if(logSession == null){
console.log("logSession null");
}
if(logSession == undefined){
console.log("isundefined");
}
if(logSession != null){
console.log("not null");
console.log("usern: " + logSession.username);
//console.log("authinfo authorities: " + logSession.authorities)
AuthFactory.setJWTAuthInfo(logSession);
$state.go("dashboard.home");
}
console.log("login authinfo: " + localStorage.getItem("authinfo"));
let sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key === 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
} else if (event.key === 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
}
function doLoginFn() {
console.log("doLoginFn");
var requiresLogin = $state.jwtToken;
console.log("requireLogin: " + requiresLogin);
AuthFactory.sendLogin(ctrl.authRequest, successCB, errorCB);
function successCB(response) {
let authInfo = response.data;
console.log("data = " + response.data.all);
let header = response.headers();
authInfo.jwtToken = header['authorization'];
console.log("authInfo", authInfo);
// AuthFactory.user.username = authInfo.username;
// AuthFactory.user.role = authInfo.role;
let debugJWT = true;
//if (debugJWT) {
if (true) {
console.log(authInfo);
console.log("username: " + authInfo.username);
console.log("roles: " + JSON.stringify(authInfo.authorities));
console.log("jwtToken: " + authInfo.jwtToken);
console.log("userType: " + authInfo.userRole);
console.log("ended.");
}
AuthFactory.setJWTAuthInfo(authInfo);
//console.log("authinfoo1234: " + authInfo);
// localStorage.setItem("authinfo",authInfo);
console.log("authorities: " + authInfo.authorities);
$state.go("dashboard.home");
}
function errorCB(response) {
let error = response.data;
if (error && error.status === 401) {
ctrl.authMessage = error.message;
}
else {
console.error(response);
ctrl.authMessage = 'No response from server';
}
}
}
}
]);
I have a very strange problem: I'm using Intellj, and it tells me in lines
console.log("roles: " + JSON.stringify(authInfo.authorities));
console.log("userType: " + authInfo.userRole);
but if I comment lines with localStorage.setItem and localStorage.getItem, console prints on output correct userType and userRole; if I add those lines, console prints out this message:
TypeError
columnNumber: 17
fileName: "http://localhost:63342/ISSSR_frontend/app/scripts/service/AuthFactory.js"
lineNumber: 59
message: "authInfo.authorities is undefined"
I really don't understand, why it says me that it cannot resolve variable, but it can print out it?
Unfortunately I could not deploy your code would you please prepare codepen or flickr.
Some points that I can mention is below:
instead of use console.log("username: " + authInfo.username); use : console.log('username : ',authInfo.username)
Instead of JSON.stringify(authInfo.authorities) use : angular.toJson(authInfo.authorities,true)
Also console.log(response) to see what it returns.
Related
I'm using the samples for the MSAL and converting them to use MS Graph to read SharePoint but when it comes to reading list items it seems I am getting permissions issues.
To make sure I have my syntax correct, I use the Graph Explorer with my AD account and I am able to read list items and confirm the URI is correct. I am also able to read and get an array of lists. But as soon as I try to get the list items for a list nothing is returned.
The base code is here https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa
Here's the code I converted from the sample. If you update the variables and register in Azure you should be able to run against your SPO site.
<!DOCTYPE html>
<html>
<head>
<title>Quickstart for MSAL JS</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/msal.js"></script>
</head>
<body>
<h2>Welcome to MSAL.js Quickstart</h2><br />
<h4 id="WelcomeMessage"></h4>
<button id="SignIn" onclick="signIn()">Sign In</button><br /><br />
<button id="btnAllLists" onclick="GetWithEndPoint()">Get All Lists</button><br /><br />
<button id="btnListItems" onclick="GetWithEndPoint()">Get List Items</button><br /><br />
<button id="btnListItemsAllFields" onclick="GetWithEndPoint()">Get List Items All Fields</button><br /><br />
<pre id="json"></pre>
<script>
var config = {
portalname: "yourportalname",
sitename: "yoursitename",
listid: "guidofalist"
}
var msalConfig = {
auth: {
clientId: "azureclientguid",
authority: "https://login.microsoftonline.com/yourportal.onmicrosoft.com"
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
var graphConfig = {
graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
spShowAllListsEp: "https://graph.microsoft.com/v1.0/sites/" + config.portalname + ".sharepoint.com:/sites/" + config.sitename + ":/lists",
spShowListItemsEp: "https://graph.microsoft.com/v1.0/sites/" + config.portalname + ".sharepoint.com:/sites/" + config.sitename + ":/lists/" + config.listid + "/items",
spShowListItemsAllFieldsEp: "https://graph.microsoft.com/v1.0/sites/" + config.portalname + ".sharepoint.com:/sites/" + config.sitename + ":/lists/" + config.listid + "/items?expand=fields",
};
// this can be used for login or token request, however in more complex situations this can have diverging options
var requestObj = {
scopes: ["user.read"]
};
var myMSALObj = new Msal.UserAgentApplication(msalConfig);
// Register Callbacks for redirect flow
myMSALObj.handleRedirectCallback(authRedirectCallBack);
function callMSGraph(theUrl, accessToken, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200)
callback(JSON.parse(this.responseText));
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xmlHttp.send();
}
function signIn() {
myMSALObj.loginPopup(requestObj).then(function (loginResponse) {
//Login Success
showWelcomeMessage();
acquireTokenPopupAndCallMSGraph();
}).catch(function (error) {
console.log(error);
});
}
function acquireTokenPopupAndCallMSGraph() {
//Always start with acquireTokenSilent to obtain a token in the signed in user from cache
myMSALObj.acquireTokenSilent(requestObj).then(function (tokenResponse) {
callMSGraph(graphConfig.graphMeEndpoint, tokenResponse.accessToken, graphAPICallback);
}).catch(function (error) {
console.log(error);
// Upon acquireTokenSilent failure (due to consent or interaction or login required ONLY)
// Call acquireTokenPopup(popup window)
if (requiresInteraction(error.errorCode)) {
myMSALObj.acquireTokenPopup(requestObj).then(function (tokenResponse) {
callMSGraph(graphConfig.graphMeEndpoint, tokenResponse.accessToken, graphAPICallback);
}).catch(function (error) {
console.log(error);
});
}
});
}
function graphAPICallback(data) {
document.getElementById("json").innerHTML = JSON.stringify(data, null, 2);
}
function showWelcomeMessage() {
var divWelcome = document.getElementById('WelcomeMessage');
divWelcome.innerHTML = 'Welcome ' + myMSALObj.getAccount().userName + "to Microsoft Graph API";
var loginbutton = document.getElementById('SignIn');
loginbutton.innerHTML = 'Sign Out';
loginbutton.setAttribute('onclick', 'signOut();');
var btn1 = document.getElementById('btnAllLists');
btn1.setAttribute('onclick', "GetWithEndPoint('" + graphConfig.spShowAllListsEp + "');");
var btn2 = document.getElementById('btnListItems');
btn2.setAttribute('onclick', "GetWithEndPoint('" + graphConfig.spShowListItemsEp + "');");
var btn3 = document.getElementById('btnListItemsAllFields');
btn3.setAttribute('onclick', "GetWithEndPoint('" + graphConfig.spShowListItemsAllFieldsEp + "');");
}
//This function can be removed if you do not need to support IE
function acquireTokenRedirectAndCallMSGraph() {
//Always start with acquireTokenSilent to obtain a token in the signed in user from cache
myMSALObj.acquireTokenSilent(requestObj).then(function (tokenResponse) {
callMSGraph(graphConfig.graphMeEndpoint, tokenResponse.accessToken, graphAPICallback);
}).catch(function (error) {
console.log(error);
// Upon acquireTokenSilent failure (due to consent or interaction or login required ONLY)
// Call acquireTokenRedirect
if (requiresInteraction(error.errorCode)) {
myMSALObj.acquireTokenRedirect(requestObj);
}
});
}
function authRedirectCallBack(error, response) {
if (error) {
console.log(error);
}
else {
if (response.tokenType === "access_token") {
callMSGraph(graphConfig.graphEndpoint, response.accessToken, graphAPICallback);
} else {
console.log("token type is:" + response.tokenType);
}
}
}
function requiresInteraction(errorCode) {
if (!errorCode || !errorCode.length) {
return false;
}
return errorCode === "consent_required" ||
errorCode === "interaction_required" ||
errorCode === "login_required";
}
function signOut() {
myMSALObj.logout();
}
// Browser check variables
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
var msie11 = ua.indexOf('Trident/');
var msedge = ua.indexOf('Edge/');
var isIE = msie > 0 || msie11 > 0;
var isEdge = msedge > 0;
//If you support IE, our recommendation is that you sign-in using Redirect APIs
//If you as a developer are testing using Edge InPrivate mode, please add "isEdge" to the if check
// can change this to default an experience outside browser use
var loginType = isIE ? "REDIRECT" : "POPUP";
if (loginType === 'POPUP') {
if (myMSALObj.getAccount()) {// avoid duplicate code execution on page load in case of iframe and popup window.
showWelcomeMessage();
acquireTokenPopupAndCallMSGraph();
}
}
else if (loginType === 'REDIRECT') {
document.getElementById("SignIn").onclick = function () {
myMSALObj.loginRedirect(requestObj);
};
if (myMSALObj.getAccount() && !myMSALObj.isCallback(window.location.hash)) {// avoid duplicate code execution on page load in case of iframe and popup window.
showWelcomeMessage();
acquireTokenRedirectAndCallMSGraph();
}
} else {
console.error('Please set a valid login type');
}
</script>
<script>
function GetWithEndPoint(endpointString) {
myMSALObj.acquireTokenSilent(requestObj).then(function (tokenResponse) {
callMSGraph(endpointString, tokenResponse.accessToken, graphAPICallback);
}).catch(function (error) {
console.log(error);
if (requiresInteraction(error.errorCode)) {
myMSALObj.acquireTokenPopup(requestObj).then(function (tokenResponse) {
callMSGraph(endpointString, tokenResponse.accessToken, graphAPICallback);
}).catch(function (error) {
console.log(error);
});
}
});
}
</script>
</body>
</html>
Clicking either button that returns list items throws this message which I understand to mean is permissions.
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.list)('myid')/items",
"value": []
}
My expectation is that I would get the same results from the Graph Explorer. But this indicates I don't have permission. I've tried a few different lists and the results are always the same. I can get a list of all the lists. But trying to get the items from a list fails.
Can we not use the Graph API with JS to get list items?
Here are the Azure delegated permissions from Azure which I think should be all I need to get list items.
But this indicates I don't have permission
That's right, empty results usually indicates one of the following permissions (delegated permissions in your case) are missing for Get Items endpoint:
Sites.Read.All - read items in all site collections
Sites.ReadWrite.All - edit or delete items in all site collections
I have a login button with onclick event...onclick = "login();"
I successfully logged in ...but I wanted to open new tab instead.
This is my javascript:
login = function() {
if ($("#UserName").val().length == 0) {
return;
}
if ($("#Password").val().length == 0) {
return;
}
var logindata = new Object();
logindata.UserName = $("#UserName").val();
logindata.Password = $("#Password").val();
locustraxx.showLoading("loginformDiv");
locustraxx.doAjaxPostback('//example.com/LoginHandler.ashx', logindata, null, null,
function(data, textStatus, jqXHR) {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (data.success == true) {
if ($("#Remember").is(':checked')) {
$.cookie('remember', $("#UserName").val() + '|' + $("#Password").val(), {
expires: 36500,
path: '/'
});
}
var retUrl = $.QueryString("ReturnUrl");
if (retUrl == undefined || retUrl == null) {
window.location.replace(data.data, '_blank');
} else {
window.location.href = decodeURIComponent(retUrl).replace(/\~~/g, ".");
}
if (isChrome) {
// clearCookies();
}
return false;
} else {
alert(data.message);
$("#UserName").focus();
}
}, null,
function() {
login.hideLoading("loginformDiv");
});
}
I tried _blank... window open, but to no avail
Could you please specify better what you have tried so far in theory you should be OK with:
window.open('https://www.google.com', '_blank');
If It isn’t working please specify the error output of the console.
There is also a known issue in which the browser opens a new window instead of a new tab, but that has to do with the user preferences, nothing to do about that. See here.
I have chat on Socket.IO, MySQL, PHP. Everything is working good, but i need download and diplay messages history when you update the page.
php code:
<script>var USER = {"id":"<?php echo $_SESSION['steamid']?>","login":"<?php echo $_SESSION['personaname']?>","image":"<?php echo $_SESSION['avatarmedium']?>","hash":"<?php echo md5($_SESSION['steamid']) ?>"};</script>
js site code:
var messageTpl = _.template($("#chat-message").html());
function sendMessage(text) {
socket.emit('message', {user: USER, message: text});
}
var lastUser = null;
function addMessage(data, checkLast) {
var a = $("#chatScroll")[0];
var isScrollDown = (a.offsetHeight + a.scrollTop) == a.scrollHeight;
if (checkLast && lastUser && lastUser.id == data.user.id) {
$('.chatMessage').last().find('.body').append('<br/>' + _.escape(data.message))
}
else {
console.log(data);
data.user.url = 'http://steamcommunity.com/profiles/' + data.user.id;
data.user.image = 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + _.escape(data.user.image).replace('_medium', '');
var html = messageTpl(data);
$('#messages').append(html);
if ($('.chatMessage').length > 100) {
$('.chatMessage').eq(0).remove();
}
}
lastUser = data.user;
if (isScrollDown) a.scrollTop = a.scrollHeight;
$("#chatScroll").perfectScrollbar();
}
socket.on('online', function(data) {
$('#online').text(data.online);
});
socket.on('chat-message', function(data) {
addMessage(data, true);
});
socket.on('chat-history', _.once(function(data) {
$("#chatScroll").perfectScrollbar();
if (data) _.each(data, addMessage);
}));
function addMessage works good, but with socket.on('chat-history') i got error
Uncaught TypeError: Cannot read property 'id' of undefined
js server code:
connection.query('SELECT * FROM cs_chat ORDER BY id DESC LIMIT 50', function(error, rows) {
if(!error) {
var user = [];
rows.forEach(function (data) {
user.push(data);
});
console.log(user);
socket.emit('chat-history', {user: JSON.stringify(user)});
} else {
console.log(error.message);
}
});
when you refresh the page - all last messages lost
console.log server js rows.forEach below.
[{"id":668,"message_text":"3qwe","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:15.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":667,"message_text":"12312","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":666,"message_text":"213123","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":665,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":664,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":663,"message_text":"g","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":662,"message_text":"gdf","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":661,"message_text":"df","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"}]
I am stuck with Social login (Facebook, Google and twitter) through Phonegap.
I have googled and found so many solutions, but they don't work on either platform (i.e: android or iOS).
Does any one have implemented social login in his/her app using phonegap?
If any one could provide me the running code, that would be appreciated.
Thanks,
Sabir
I know it's probably late to answer your particular question but I have had the same issue - all of the current (September 2016) scripts, snippets and libraries for social login in PhoneGap/Cordova that I have tried did not work so I made some simple functions from scratch which may still be useful to people ending up here. You can use them to log the user in with LinkedIn, Facebook and Google(+). I have also made some simple functions that retrieve some basic user information from the access token that is returned by logging the user in with the given network. You can examine the functions but they usually save the token or/and the user data to localStorage for later usage. They have been tested in September 2016 and work perfectly. I hope that this would help other people who also land on failing snippets around the web.
You can just insert the code and use the functions whenever you want. It requires jQuery and PhoneGap's InAppBrowser (besides having made apps/clients in the social media in order to fill the app id and app secret).
As a side note, it is not the best move to store the client secret directly in the PhoneGap application as the source can be viewed by malevolent people.
The code can be refactored at many places, so feel free to do that, but it does the trick. You may also have to handle cases where the user cancels the login process.
var facebookLogin = function(appId, appSecret, successCb,errCb) {
/*$.get("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" +appSecret + "&grant_type=client_credentials", function(res) {
if (res.indexOf("access_token=") !== -1) {
successCb(res.replace("access_token=", "").trim());
}
else {
errCb(res);
}
})
*/
var ref = window.open("https://www.facebook.com/dialog/oauth?display=popup&response_type=token&client_id="+appId+"&redirect_uri="+"http://anyurlhere.com", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("#access_token") !== -1) {
localStorage.fbToken = evt.url.split("#access_token=")[1];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.fbToken);
})
}
}
})
}
var linkedinLogin = function(appId,appSecret,successCb,errCb) {
var ref = window.open("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id="+appId+"&redirect_uri="+(encodeURI("http://anyurlhere.com"))+"&state=987654321&scope=r_basicprofile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("code=") !== -1) {
var code = evt.url.split("code=")[1];
code = code.split("&")[0];
//TODO: get actual token to access user profile
$.post("https://www.linkedin.com/oauth/v2/accessToken", {"grant_type": "authorization_code", "code": code, "redirect_uri":encodeURI("http://anyurlhere.com"), "client_id":appId,"client_secret":appSecret}, function(data) {
for (key in data) {
if (key == 'access_token') {
localStorage.linkedinToken = data[key];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.linkedinToken);
})
}
}
})
}
}
})
}
var googleLogin = function(appId, appSecret, successCb, errCb) {
var ref = window.open("https://accounts.google.com/o/oauth2/v2/auth?response_type=token&client_id=" + appId + "&redirect_uri="+encodeURI("http://anyurlhere.com")+"&scope="+encodeURIComponent("email profile")+"&state=profile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("access_token=") !== -1) {
var accessToken = evt.url.split("access_token=")[1];
accessToken = accessToken.split("&")[0];
localStorage.gToken = accessToken;
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.gToken);
})
}
}
})
}
var getGoogleInfo = function(successCb, errCb) {
//get basic user profile
$.get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + localStorage.gToken, function(userInfo) {
successCb(userInfo);
})
}
var getFacebookInfo = function(successCb, errCb) {
//get basic user profile-name
$.get("https://graph.facebook.com/me?fields=email,name,picture&access_token=" + localStorage.fbToken, function(userInfo) {
var myInfo = {};
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.email) {
myInfo.email = userinfo.email;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture.data.url;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
// localStorage.myInfo = myInfo;
})
}
//get basic data for linked in
var getLinkedinInfo = function(successCb, errCb) {
$.ajax({
url: "https://api.linkedin.com/v1/people/~?format=json",
headers: {
"Authorization": "Bearer " + localStorage.linkedinToken
},
success: function(userInfo) {
var myInfo = {};
if (userInfo.firstName && userInfo.lastName) {
myInfo.name = userInfo.firstName + " " + userInfo.lastName;
}
if (userInfo.headline) {
myInfo.linkedinHeadline = userInfo.headline;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
},
fail: function(err) {
alert(err);
for (key in err) {
alert(key);
alert(err[key]);
}
}
})
}
//example of logging in the user with Google + and getting his/her data
googleLogin("93-54932-423-fkfew.apps.googleusercontent.com", "", function(accessToken) {
getGoogleInfo(function(userInfo) {
var myInfo = {};
alert(userInfo.name);
if (userInfo.email) {
myInfo.email = userInfo.email;
}
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.given_name) {
myInfo.firstName = userInfo.given_name;
}
if (userInfo.familyName) {
myInfo.familyName = userInfo.family_name;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture;
}
I have a JS function which is sending request twice to action class. I am not sure where should I modify it to resolve the issue.
Below is the JS function.The problem is in ELSE part of it where I am checking runNoEmail==1 && runEmail==0
I am providing full JS function for better understanding
function runReportCheck(obj){
obj = window.event.srcElement;
if(runEmail==1 && runNoEmail==0)
{
openPopupWindow('popupType:Working');
runEmail=0;
var opt = {
method: 'post',
parameters: $('formLicStrands').serialize(true),
onSuccess: function(t) {
destroyPopupWindow();
if(t.responseText=="-2"){
openPopupWindow('title:Error; message: Conflict report is already being run.Please try again later.; popupType: Error; button1Value: OK; topRightClose: false',obj);
return;
}else
if(t.responseText=="-3"){
openPopupWindow('title:Warning; message: The conflict report will run and save in the background.An email will be sent to you upon completion.; popupType: Warning; button1Value: OK; topRightClose: false',obj);
return;
}
else
{ openPopupWindow('title:Run And Email Issue Report; URL:<c:url value="/secure/deal/conflict/newReport.dooo?"/>;formToSubmit:formLicStrands;topRightClose: false;onTitleBarCloseFunction:onConflictReportClose(<c:out value="${DEAL_BRIEF.ventanaId}"/>)',obj);
}
return;
},
onFailure: function(t) {
alert('Error ' + t.status + ' -- ' + t.responseText);
}
}
new Ajax.Request("<%=request.getContextPath()%>/secure/deal/conflict/newReport.dooo?isRunEmailClicked=true",opt);
return false;
}
else if(runNoEmail==1 && runEmail==0)
{
openPopupWindow('popupType:Working');
runNoEmail=0;
var opt = {
method: 'post',
parameters: $('formLicStrands').serialize(true),
onSuccess: function(t) {
destroyPopupWindow();
if(t.responseText=="-11"){
openPopupWindow('title:Error; message: Conflict report is already being run.Please try again later.; popupType: Error; button1Value: OK; topRightClose: false',obj);
return;
}
else
{
openPopupWindow('title:Run Issue Report; URL:<c:url value="/secure/deal/conflict/newReport.dooo?"/>;formToSubmit:formLicStrands;topRightClose: false;onTitleBarCloseFunction:onConflictReportClose(<c:out value="${DEAL_BRIEF.ventanaId}"/>)',obj);
}
return;
},
onFailure: function(t) {
alert('Error ' + t.status + ' -- ' + t.responseText);
}
}
new Ajax.Request("<%=request.getContextPath()%>/secure/deal/conflict/newReport.dooo",opt);
return false;
}else {
openPopupWindow('title:Run Issue Report; URL:<c:url value="/secure/deal/conflict/newReport.dooo?"/>;formToSubmit:formLicStrands;topRightClose: false;onTitleBarCloseFunction:onConflictReportClose(<c:out value="${DEAL_BRIEF.ventanaId}"/>)',obj);
}
return;}