Auto Login to User from Site to Disqus - single-sign-on

I added the Disqus to my website and making use of the script
SSO configuration is like this:
Name: example
Slug: example
no call back url is set at my end.
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'myexample';
var disqus_identifier = 'http://www.example.com/Welcome...
var disqus_title = 'My Example';
var disqus_url = 'http://www.example.com/Welcome...
var remote_auth_s3 = "<%=Payload%>";//Its generate by server side code
var api_key = "Public Api Key Is here";
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
I am just using the above script and passing the values.
Will this script auto login my website users to Disqus or I have to do other extra efforts.
Thanks Dalvir

My issue fixed after making use of variable like this
var disqus_config = function () {
// The generated payload which authenticates users with Disqus
this.page.remote_auth_s3 = "<%=Payload%>";
this.page.api_key = "<%=Key%>";
};

Related

Convert "," to ";" in a CSV file Google script

With the below code my goal is to extract a sheet from the Google sheet file in CSV format. However, when I want to convert the , to ; the following error message appears:
r.join is not a function
Could you please help me to solve this problem.
Also, do you think it is possible to download this new file directly to the desktop of the computer ?
function sheetToCsv(){
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "Int_Module";
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var newfile = [result].map(r => r.join(";")).join("\n");
newfile.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
}
I understand that there is 2 questions ... how to produce CSV file with semi-colon, and how to download the file directly to your PC.
1- To produce the csv content, try
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
2- To download, you will have to go through an html page.
Try this for both needs
function downloadMyCSVFile() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
var html = HtmlService.createHtmlOutput(`
<html><body onload="document.getElementById('dwn-btn').click()">
<textarea id="text-val" rows="10" style="display:none;">${content}</textarea>
<input type="button" id="dwn-btn" value="Download text file" style="display:none;"/>
<script>
window.close = function(){window.setTimeout(function(){google.script.host.close()},100)}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function(){
var text = document.getElementById("text-val").value;
var filename = "${sh.getName()}.csv";
download(filename, text);
close();
}, false);
</script>
</body></html>
`)
.setWidth(250).setHeight(100);
SpreadsheetApp.getUi().showModalDialog(html, "Downloading ...");
}

How to use the Gmail API, OAuth2 for Apps Script, and Domain-Wide Delegation to set email signatures for users' alias in a G Suite domain

This is a continuation of this question: How to use the Gmail API, OAuth2 for Apps Script, and Domain-Wide Delegation to set email signatures for users in a G Suite domain
It showed a way to set a signature for another account, using Oauth2, Apps Script, and domain wide delegation.
However, it was not working for me when I have this scenario: I have a domain alias in our G-Suite account where myuser#aliasdomain.com is an alias for myuser#maindomain.com. I want to set a signature for myuser#aliasdomain.com. The example from the prior question only did myuser#maindomain.com.
Is it possible?
I tried this (modified from prior question's example code):
var credentials = {
"type": "service_account",
"project_id": "project-id-4606494xxxxxxxxx3",
"private_key_id": "8481966716a20fe34615daxxxxxxxxa",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXbOAiODt\n-----END PRIVATE KEY-----\n",
"client_email": "xxxxxxxxxxxx#project-id-46064949xxxxxxxxxxxx.iam.gserviceaccount.com",
"client_id": "112076306220190xxxxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxxxxxxx%40project-id-4606494951xxxxxxxxxxxxxx.iam.gserviceaccount.com"
}
function setSignatureTest() {
var loginEmail = 'myuser#maindomain.com';
var sendAsEmail = 'myuser#aliasdomain.com';
var signature = 'test for awesome signature';
var test = setSignature(loginEmail, sendAsEmail, signature);
Logger.log('test result: ' + test);
}
function setSignature(loginEmail, sendAsEmail, signature) {
Logger.log('starting setSignature');
var signatureSetSuccessfully = false;
var service = getDomainWideDelegationService('Gmail: ', 'https://www.googleapis.com/auth/gmail.settings.basic', loginEmail);
if (!service.hasAccess()) {
Logger.log('failed to authenticate as user ' + loginEmail);
Logger.log(service.getLastError());
signatureSetSuccessfully = service.getLastError();
return signatureSetSuccessfully;
} else Logger.log('successfully authenticated as user ' + loginEmail);
var resource = { signature: signature };
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
requestBody.contentType = "application/json";
requestBody.method = "PUT";
requestBody.payload = JSON.stringify(resource);
requestBody.muteHttpExceptions = false;
var loginEmailForUrl = encodeURIComponent(loginEmail);
var sendAsEmailForUrl = encodeURIComponent(sendAsEmail);
var url = 'https://www.googleapis.com/gmail/v1/users/' + loginEmailForUrl + '/settings/sendAs/' + sendAsEmailForUrl;
var maxSetSignatureAttempts = 10;
var currentSetSignatureAttempts = 0;
do {
try {
currentSetSignatureAttempts++;
Logger.log('currentSetSignatureAttempts: ' + currentSetSignatureAttempts);
var setSignatureResponse = UrlFetchApp.fetch(url, requestBody);
Logger.log('setSignatureResponse on successful attempt:' + setSignatureResponse);
signatureSetSuccessfully = true;
break;
} catch(e) {
Logger.log('set signature failed attempt, waiting 3 seconds and re-trying');
Utilities.sleep(3000);
}
if (currentSetSignatureAttempts >= maxSetSignatureAttempts) {
Logger.log('exceeded ' + maxSetSignatureAttempts + ' set signature attempts, deleting user and ending script');
throw new Error('Something went wrong when setting their email signature.');
}
} while (!signatureSetSuccessfully);
return signatureSetSuccessfully;
}
function getDomainWideDelegationService(serviceName, scope, email) {
Logger.log('starting getDomainWideDelegationService for email: ' + email);
return OAuth2.createService(serviceName + email)
// Set the endpoint URL.
.setTokenUrl(credentials.token_uri)
// Set the private key and issuer.
.setPrivateKey(credentials.private_key)
.setIssuer(credentials.client_email)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject(email)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope(scope);
}
It works as I have loginEmail and sendAsEmail set to the loginEmail, but not when set to the one for the domain alias.
I'd appreciate any ideas/help.
Thanks.

Adding disqus comments to sinatra app using slim template language

I have an app built with Sinatra. One of the pages is called "discussion" and I chose to power the comments with disqus. I copied the universal instructions
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'voltairequotes';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
but i converted the code to slim and added them to the page
discussion.slim
h2 Discussion Area
p Add your comments below and please cite what quote you are referring to.
#disqus_thread
javascript:
/!* * * CONFIGURATION VARIABLES * * */
| var disqus_shortname = 'voltairequotes';
/!* * * DON'T EDIT BELOW THIS LINE * * */
| (function() {
| var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
| dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
| (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
| })();
noscript
| Please enable JavaScript to view the
a href="https://disqus.com/?ref_noscript" rel="nofollow" comments powered by Disqus.
But the comments will not show up. But the code shows up when I go to inspect element.
Not sure what I am missing or perhaps i have a typo or mistake in my markup
OK i solved the problem overall. Hence I am posting the solution to help others.
But leaving the question since I still fail to see how my first attempt was unsuccessful.
What I did was move the javascript to its own file, which is a good practice anyways.

Facebook JS connect unsupported browser IE mobile

I am getting error "unsupported browser: IE" when I am trying to login using facebook in windows mobile device(Lumia 800). Is there any way it can be fixed or facebook have to do fixes in their script. Or any other workaround can be done for this issue? Please suggest.
I have faced this problem as well with a big project I did for Microsoft. I needed to oath with Facebook on windows mobile devices, and got the same error. This is how I solved it:
Generally there are two ways to oath with javascript - the simple way (which generates this error) described here:
https://developers.facebook.com/docs/javascript/quickstart
and the manually build login flow described here:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
Here is a quick explanation of what you have to do for the second option:
1) Load SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
2) On page load check for access_token. If the user didn't login, there will be no access token. if the user did, there will be access token appended to the URL as a query but with '#' instead of '?'
I used this function:
function getUrlVars()
{
var query = '#';//normally ?
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf(query) + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Now determine if you got the access_token:
var urlString = getUrlVars();
var hasAccess=false;
var userToken;
if(typeof(urlString)!='undefined' && typeof(urlString.access_token)!='undefined'){
hasAccess=true;
userToken=urlString.access_token;
}
if user has access redirect them to the same (or other) url with the app id, access token and response type:
var appID = 'your app id';
if(!hasAccess){
$('#login').on('click',function(){
var login_redirect_uri = 'http://www.yourpage.com/';
var login_response_type = 'token';
var loginURL = 'https://www.facebook.com/dialog/oauth?client_id='+appID+'&redirect_uri='+login_redirect_uri+'&response_type='+login_response_type;
window.location.replace(loginURL);
});//login-click
}
3) if there is no access token in the url query, use a server side service (we will build below) to validate the token
var tokenValidate = 'https://titan-img-gen.aws.af.cm/toeknValidate.php';
$.ajax({
type: 'GET',
url: tokenValidate,
crossDomain: true,
data:{
token:userToken
},
dataType:'json',
success: function(validateData){
if(validateData.error){
showError();
}else{
username = validateData.username;
firstname = validateData.firstname;
lastname = validateData.lastname
//continue your code
}
},
error: function (responseData, textStatus, errorThrown) {
showError();
}
});
4) Server side service (PHP)
a)generate app token: https://developers.facebook.com/docs/facebook-login/access-tokens/
b)same origin resolution might be needed:
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
c) define app_token :
$app_token='*******';
d)check for token parament in get
$reponse = array();
if(!isset($_GET['token']) || $_GET['token']==NULL ){
$reponse['error'] = true;
}else{
$user_access_token = $_GET['token'];
//continue here...
}
e) use facebook graph service to debug token
$fbDebug = "https://graph.facebook.com/debug_token?input_token=$user_access_token&access_token=$app_token";
f)get the json file, decode it and get the user_id from it. you can then retrieve more info from Facebook easily
try{
$fbResult = file_get_contents($fbDebug);
$fbResultDecode = json_decode($fbResult);
if(isset($fbResultDecode->data->error)){
$reponse['error'] = true;
}else{
$user_id= $fbResultDecode->data->user_id;
$userJSON = file_get_contents("https://graph.facebook.com/$user_id");
$userInfo = json_decode($userJSON);
$reponse['username'] = $userInfo->username;
$reponse['firstname'] = $userInfo->first_name;
$reponse['lastname'] = $userInfo->last_name;
}
}catch(Exception $e){
$reponse['error'] = true;
}
g)return the JSON
header('Content-Type: application/json');
echo json_encode($reponse);
Bada-Bim-Bada-Boom
I lied, it wasn't a quick explanation... but I hope it will save you some time!!!
Tomer Almog

phonegap - using external site as app - facebook login

I'm building a app site running through phone gap. Phone gap simply checks the user has internet connection and loads an external web app into the frame. I can navigat through the site fine with no blibs but as soon as I try the login to Facebook (either PHP redirect or javascript SDK) the app suddenly gets its navbar back or opens a new window (javascript SDK).
Is there anyway I can prevent this?
regards
It took some doing but using the ChildBrowser plugin, I've managed to login! (this is for android) I've used some code from a facebook connect plugin which didnt work for me, re wrote some stuffs so I could understand it and now works. Chears Juicy Scripter!
var fb_success = 'https://www.facebook.com/connect/login_success.html';
var fb_logout = 'https://www.facebook.com/connect/login_failed.html';
var fb_logout_ = 'http://m.facebook.com/logout.php?confirm=1&next=' + fb_logout;
var authorize_url = '';
var my_client_id = '##################';
var my_secret = '######################';
var my_type = 'user_agent';
var my_display = 'touch';
var token = false;
var fb_code = false;
var device_ready = false;
var ajax_url = '';
function logged_in(){
// alert('do what you need to do!');
}
function fb_force_logout(){
}
function fb_auth_check(){
console.log('fb_auth_check()');
if( fb_code !== false ) {
console.log('ajax test instigated...');
ajax_url = 'https://graph.facebook.com/oauth/access_token?client_id=' + encodeURIComponent(my_client_id) + '&client_secret=' + encodeURIComponent(my_secret) + '&code=' + encodeURIComponent(fb_code) + '&redirect_uri=' + fb_success;
$.ajax({
url: ajax_url,
type: 'POST',
success: function(html){
token = html.split("=")[1];
console.log('success! token = ' + token);
window.plugins.childBrowser.close();
fb_init();
},
error: function(error) {
console.log('there was an error...' + ajax_url);
window.plugins.childBrowser.close();
}
});
}
}
function fb_track_redirects(loc){
console.log('redirect tracked... ' + loc);
if ( loc.indexOf(fb_success) >= 0 || loc.indexOf(fb_success) > -1 ) {
fb_code = loc.match(/code=(.*)$/)[1]
console.log('success redirect... fb_code=' + fb_code);
fb_auth_check();
window.plugins.childBrowser.close();
} else if ( loc.indexOf(fb_logout) >= 0 || loc.indexOf(fb_logout) > -1 ) {
window.plugins.childBrowser.close();
}
}
function inner_init(){
console.log('inner_init()');
if( token === false ) {
console.log('token was false...');
authorize_url += "https://graph.facebook.com/oauth/authorize?";
authorize_url += "client_id=" + encodeURIComponent(my_client_id);
authorize_url += "&redirect_uri=" + encodeURIComponent(fb_success);
authorize_url += "&display=" + encodeURIComponent(my_display);
authorize_url += "&scope=publish_stream,offline_access";
console.log('instigated location change...');
window.plugins.childBrowser.onLocationChange = function(loc){
fb_track_redirects(loc);
}
console.log('open Facebbok login window');
window.plugins.childBrowser.showWebPage(authorize_url);
}else{
logged_in();
}
}
function fb_init(){
console.log('fb_init()');
if( device_ready === false ) {
console.log('first device run...');
document.addEventListener("deviceready", function(){
device_ready = true;
console.log('device ready...');
inner_init();
}, false);
}else{
inner_init();
}
}
$(document).ready(function(){
$('#login').bind('click', function(){
fb_init();
return false;
})
});
</script>
This is how it works for all apps native or web without patching the SDK code.
This is probably can be done, but will require digging into code. The question is do you really need it? This is a desired behavior.
You can try to use PhoneGap Facebook plugin and enable Single Sign On so native Facebook App if exists will be opened instead of browser to authenticate the user.
BTW,
Apps that are just external sites wrapped mostly rejected in app store.
Update:
Where is some points that may be also helpful in answer (by Facebook employee) to similar question How can I use an access token to circumvent FB.login().
Also have a look on ChildBrowser PhoneGap plugin (and Example).