I was wondering if I could just simply do the following to limit logins, but I seem to run into a problem where the page just reloads constatly once I log in once.
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('Name: ' + profile.getName());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
//list the emails that can login to the website using Gmail OAuth
if (profile.getEmail() == "XXXXXXXX#gmail.com") {
window.location.href = "./index.html"
} else {
let done = confirm("You don't have permission to access this.")
if (done) {
window.location.href = "https://www.HOMEPAGEco.uk/"
} else {
alert("Please try again.")
}
}
}
The line window.location.href = "./index.html" will always reload the page; if you want no action to be taken when they are in the whitelist, just check if they are NOT in the list.
if (profile.getEmail() !== "XXXXXXXX#gmail.com") {
let done = confirm("You don't have permission to access this.")
if (done) {
window.location.href = "https://www.HOMEPAGEco.uk/"
} else {
alert("Please try again.")
}
}
Related
can you help me with my Twitch Ban Checker
it worked a few months ago, but something is wrong now
maybe someone can give me a tip why it doesn't work anymore
I wrote this Twitch Ban Checker which, after entering the username, gives an answer whether you were banned on Twitch or not
the app is also on codepen https://codepen.io/olthoffs/pen/zqxbWW
var check_user = function (user) {
$(".description").fadeOut(20)
$.getJSON('https://api.twitch.tv/kraken/users/' + encodeURIComponent(user) + '?callback=?').done(function (data) {
if (/.+is unavailable$/.test(data.message)) { // Ban Check
var message = 'It looks like you were banned from twitch, please open a ticket via the '
message += '<a target="_blank" href="https://help.twitch.tv/customer/portal/emails/new?interaction[name]=' + user + '">official twitch support</a> '
message += 'site in order to see why you were banned.<br />'
message += '<span>TwitchTips cannot and will not help with your appeal</span>'
form_result('fail', message)
} else if (/.+is not available on Twitch$/.test(data.message) || /.+does not exist$/.test(data.message)) { // JTV/Nonexistant Check
var message = 'That account is either not a Twitch account or it does not exist.'
form_result('warn', message)
} else {
var message = 'The account provided does not seem to be banned on Twitch. '
message += 'If you\'re seeing a message telling you that you\'re blocked from Twitch, '
message += 'try disabling any VPN, proxy, or extension which re-routes traffic from your browser.<br/><br/>'
message += 'Got multiple accounts? Try checking those too because Twitch bans can be IP based.<br/><br/>'
message += 'If after doing so you are still getting the same error, '
message += 'your ISP may have provided your modem with a previously banned IP address. '
message += 'You can <a style="color: #fff" href="https://help.twitch.tv/customer/portal/emails/new?interaction[name]=' + user + '" target="_blank"><strong>open a ticket</strong></a> with Twitch to check.'
form_result('success', message)
}
}).fail(function () {
form_result('warn', 'The Twitch API appears to have returned an invalid response. Twitch may be having issues at the moment.')
})
}
var form_result = function (type, message) {
if (type === 'success') {
var title = "All is well!"
} else if (type === 'warn') {
var title = "Hmm, That's not right!"
} else {
var title = "Oh dear!"
}
$('.result').attr('class', 'result')
$('.result').html('<h3>' + title + '</h3>' + message)
$('.result').addClass(type)
$(".result").fadeIn()
}
$(document).ready(function () {
$('#ban-check').submit(function (e) {
e.preventDefault()
})
$('#ban-check').keyup(function (e) {
if (e.keyCode !== 13) {
return
}
e.preventDefault()
var user = $('#ban-check input').val()
window.location.hash = '#' + user
check_user(user)
})
var hash = location.hash
if (hash) {
var user = hash.substr(1)
$('#ban-check input').val(user)
check_user(user)
}
})
GET https://api.twitch.tv/kraken/users
(with client-id in the header)
returns:
{
"error": "Gone",
"status": 410,
"message": "It's time to kick ass and serve v3... and I'm all outta v3. See https://dev.twitch.tv/docs"
}
You might need to switch to helix, and go through OAuth flow.
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 created a login.php file where the user can will be navigated to instamojo payment page . After completing the transaction the user is getting the success message from instamojo , but i need to display the successful transaction in my domain or in own php file . so how can i get the transation related information to my webpage or to my login.php file
Ex: Redirecting from our login.php to instamojo(payment gateway)and response back (success message)to our login.php intimating the user that payment is success
var rootURL = "cgshealthcare.com/HealthCareSystem/";;
$(document).ready(function() {
$('#login').click(function() {
if ($('#username').val() == "" || $('#password').val() == "") {
alert("Please enter username or password");
return false;
}
cardloginUser($('#username').val(), $('#password').val());
});
});
function forwardtoRegister() {
window.location = "login.php?page=register";
}
function cardloginUser(userName, password) {
console.log('userName: ' + userName);
console.log('password: ' + password);
if (userName.length < 1) {
$('#errorlist').html("<font color='red'><b> Please enter User ID</b></font>");
return false;
}
if (password.length < 1) {
$('#errorlist').html(" <font color='red'><b> Please enter Password</b></font>");
return false;
}
console.log(rootURL + '/authenticate/' + userName + '/' + password);
$.ajax({
type: 'GET',
url: rootURL + '/authenticate/' + userName + '/' + password,
dataType: "json",
success: function(data) {
console.log("hello" + data.responseMessageDetails);
var list = data == null ? [] : (data.responseMessageDetails instanceof Array ? data.responseMessageDetails : [data.responseMessageDetails]);
console.log("List : " + list);
if ((list).length < 1) {
$('#errorlist').html("<font color='red'><b> Invalid User Name and Password Combination </b></font>");
$('#errorblock').css("visibility") == "visible";
}
$.each(list, function(index, responseMessageDetails) {
console.log("Status " + responseMessageDetails);
var message = responseMessageDetails.message;
if (message.indexOf("]:") > 0) message = message.substring(0, message.indexOf("]:") + 2);
console.log("message" + message);
console.log("USer Data" + responseMessageDetails.status);
console.log("USer Data" + responseMessageDetails.message);
if (responseMessageDetails.status == "Success") {
window.location = "imjo.in/NpKxN";;
} else if (responseMessageDetails.status == "Fail") {
window.location = "www.google.com";
console.log("Fail1");
$('#errorlist').html("<font color='red'><b>" + message + "</b></font>");
} else {
console.log("Fail111");
$('#errorlist').html("<font color='red'><b> We are sorry some intermittent Issue. Please try after some time. </b></font>");
}
});
},
error: function(data) {
console.log("data...." + data);
var list = data == null ? [] : (data.responseMessageDetails instanceof Array ? data.responseMessageDetails : [data.responseMessageDetails]);
console.log("data...." + data);
$.each(list, function(index, responseMessageDetails) {
console.log(responseMessageDetails);
var message = responseMessageDetails.message;
if (message.indexOf("]:") > 0) message = message.substring(0, message.indexOf("]:") + 2);
$('#errorlist').html("<font color='red'><b>" + message + "</b></font>");
});
}
});
}
function showLogin() {
window.location = "login.php";
}
Please look at the integration guide here.
After user enters payment information on instamojo, they are redirected to a redirect-url which you specify (and is a url on your website). Instamojo appends transaction results to this url. You can make it a php url on your website and read the results using GET method. Depending upon the results, you can process your payment and display results to the end-user. More on GET method here...
Instamojo also provides for webhooks, which are like silent POSTs in the background and can be used as backups in case redirect urls in front-end fail for some reason. This way if end-users' redirection failed for any reason, the webhook will still receive information in the background which can be used you to update your database for success/failure of transaction. Of course you webserver has to be up and running to receive webhooks notifications. If that's the point of failure, nothing will work :)
The API link I shared has all those details.
Thanks
I am using Javascript sdk with a facebook app to create login page for user.
FB.login prompts the user to enter facebook username and password. I have saved all the info such as user_id, Access_token, and all info. However, when the user logout. I want to login to facebook without the need to re-enter username and password again. i want to use the user-id and access token to login directly using the javascript API.
Thanks
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
testbut = document.getElementById('test');
var rr = getResponse("user_profile.xml");
if(rr != null)
{
response = rr;
}
if (response.authResponse) {alert('me/permissions/?access_token='+
response.authResponse.accessToken);
FB.api('me/permissions/?access_token='+ response.authResponse.accessToken
,function(response)
{
for (var name in response) {
alert(response.data);
}
alert(response);
});
//user is connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
},
{scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run for the current status and whenerve it is changed
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
ajaxFunction(response);
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
}
You have to store User access token in your database to user for next time.
Here is some small hint to pass access token using javascript sdk
FB.api('me/permissions/?access_token=Your access token',function(response){console.log(response)});
Chiming in a bit late, but my guess is you are trying to login using an expired or invalidated short-term access token. For future logins, you should convert the short-term access token to a long-term access token, good for about 60 days. The conversion to a long-term token needs to happen on your server as it requires your app-secret. Details are here. The long-term token is what you should be storing in your database (or similar) for future use.
I have a javascript function that uses fb.login to retrieve the users info and checks to see if the user likes my fb page. fb.login causes a pop up where the user must click a login button. If the user likes my page i need to first create a cookie then redirect them to the main app:
function checkUser() {
var page_id = "my id goes here"; //
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
var fql_query = "SELECT uid FROM page_fan WHERE page_id = " + page_id + "and uid=" + response.id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == response.id) {
//$("#container_like").show();/
//set cookie
document.cookie = "fbId=" + response.id;
window.location = "/kisses.aspx";
} else {
$("#likepageholder").show();
//$("#container_notlike").show();
//window.location = "/kisses.aspx";
//and here you could get the content for a non liker in ajax...
}
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
If there a way around using fb.login to do this?
Nope. Unfortunately, you need the user to log in (and grant your app basic permissions [based on the appId you use in FB.init) in order to query the user's likes.
That being said, it looks like your code should work.