I'm using chrome.identity.launchWebAuthFlow to make user can login with FB OAuth 2.0, which is working perfectly under unpacked.
However, when I packed the chrome extension.
And the Authentication totally failed.
I just want to confirm is anyone successfully integrate the Facebook OAuth with the Chrome extension. Maybe the FB whitelist policy totally won't make this work at all.
Can you whitelist redirect URI's in manifest.json
Ex:
"content_security_policy": "script-src 'self' https://*.facebook.com;
EDIT 1:
Following code for Facebook OAuth Login is working properly:
manifest.json
{
"name": "Facebook Sample",
"description": "Facebook Sample",
"version": "1",
"manifest_version": 2,
"minimum_chrome_version": "29",
"browser_action": {
"default_popup": "index.html"
},
"permissions": ["identity", "https://*.facebook.com/*"]
}
index.html and index.js
onload = function() {
var login = document.getElementById("login");
login.onclick = function() {
var redirectUrl = chrome.identity.getRedirectURL();
var clientId = "1ac94815c30440efa6f7de3c0d529515";
var authUrl = "https://facebook.com/oauth/authorize/?" +
"client_id=" + clientId + "&" +
"response_type=token&" +
"redirect_uri=" + encodeURIComponent(redirectUrl);
chrome.identity.launchWebAuthFlow({url: authUrl, interactive: true},
function(responseUrl) {
console.log(responseUrl);
var accessToken = responseUrl.substring(responseUrl.indexOf("=") + 1);
console.log(accessToken);
});
};
};
var facebookAPI = function(accessToken) {
this.request = function(method, arguments, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(JSON.parse(xhr.response));
};
xhr.open("GET", "https://api.facebook.com/v1/" + method + "?access_token=" + accessToken);
xhr.send();
};
}
<html>
<head>
<title>Facebook Login</title>
<script src="index.js"></script>
</head>
<body>
<button id="login">Facebook Log in</button>
</body>
</html>
Related
Newbie to JS and getting the below error with AWS Cognito. I am not able to work out why it is not able to recognize AmazonCognitoIdentity even i have mentioned it explicitly in import statement...
ReferenceError: AmazonCognitoIdentity is not defined
<script type="text/javascript" src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js" ></script>
import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js';
userAuth();
function userAuth() {
var data = {
UserPoolId: 'us-east-1_*****',
ClientId: '********'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
console.log("Success");
}
else {
console.log("Failure");
}
Any help will be appreciated!
_sppagecontext.userEmail does not return email ID for all users.
for some users _spPageContextInfo.userLoginNam is needed.
For SharePoint Online, user login name and userEmail should be the same and will be:
username#tenantname.onmicrosoft.com
For SharePoint On-Premise, _spPageContextInfo only provide userId property, for email and Loginname:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var userid = _spPageContextInfo.userId;
function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
}
function onSuccess(data, request){
console.log(data.d);
var loginName = data.d.LoginName;
var email=data.d.Email;
alert(loginName);
alert(email);
}
function onError(error) {
alert(error);
}
GetCurrentUser();
});
</script>
Make sure the work email in current user profile is not empty.
I want to change my current text email format to HTML format, so that I can send an email in nicely formatted way with headers, font values etc as shown in the screenshot below.
Image showing email body with header font size etc
Currently I have text format for sending email using AWS.ses
exports.sendEmail = function(email, token, event, context) {
var ses = new AWS.SES({
region: process.env.SES_REGION
});
var eParams = {
Destination: {
ToAddresses: [email]
},
Message: {
Body: {
Text: {
//template or environment variable
Data: `Hello ${event.request.userAttributes.given_name},\n\nYour Device Validation Token is ${token}\nSimply copy this token and paste it into the device validation input field.`
}
},
Subject: {
//template or environment variable
Data: "CWDS - CARES Device Validation Token"
}
},
//environment variable
Source: process.env.SOURCE_EMAIL
};
/* eslint-disable no-unused-vars */
ses.sendEmail(eParams, function(err, data){
if(err) {
logWrapper.logExceptOnTest("FAILURE SENDING EMAIL - Device Verify OTP");
logWrapper.logExceptOnTest(event);
logWrapper.logExceptOnTest(context);
context.fail(err);
}
else {
logWrapper.logExceptOnTest("Device Verify OTP sent");
context.succeed(event);
}
});
/* eslint-enable no-unused-vars */
}
It's fairly straight forward, just add the Html section of the Body node, i.e.:
var eParams = {
Destination: {
ToAddresses: [email]
},
Message: {
Body: {
Text: {
Data: `Hello ${event.request.userAttributes.given_name},\n\nYour Device Validation Token is ${token}\nSimply copy this token and paste it into the device validation input field.`
},
Html: {
Data: `<html><head><title>Your Token</title><style>h1{color:#f00;}</style></head><body><h1>Hello ${event.request.userAttributes.given_name},</h1><div>Your Device Validation Token is ${token}<br/>Simply copy this token and paste it into the device validation input field.</div></body></html>`
}
},
Subject: {
//template or environment variable
Data: "CWDS - CARES Device Validation Token"
}
},
//environment variable
Source: process.env.SOURCE_EMAIL
};
However... I generally split out the email template into html and text files, and use handlebars to inject data items. Here is an extract of one of my working solutions:
contact/contact.js
var AWS = require('aws-sdk');
var ses = new AWS.SES();
var fs = require('fs');
var Handlebars = require('handlebars');
module.exports.sendemail = (event, context, callback) =>
var eventData = JSON.parse(event.body);
fs.readFile("./contact/emailtemplate.html", function (err, emailHtmlTemplate) {
if (err) {
console.log("Unable to load HTML Template");
throw err;
}
fs.readFile("./contact/emailtemplate.txt", function (err, emailTextTemplate) {
if (err) {
console.log("Unable to load TEXT Template");
throw err;
}
// Prepare data for template placeholders
var emailData = {
"given_name": event.request.userAttributes.given_name,
"token": token
};
// Inject data into templates
var templateTitle = Handlebars.compile(process.env.EMAIL_TITLE);
var titleText = templateTitle(emailData);
console.log(titleText);
emailData.title = titleText;
var templateText = Handlebars.compile(emailTextTemplate.toString());
var bodyText = templateText(emailData);
console.log(bodyText);
var templateHtml = Handlebars.compile(emailHtmlTemplate.toString());
var bodyHtml = templateHtml(emailData);
console.log(bodyHtml);
// Prepare SES params
var params = {
Destination: {
ToAddresses: [
process.env.EMAIL_TO
]
},
Message: {
Body: {
Text: {
Data: bodyText,
Charset: 'UTF-8'
},
Html: {
Data: bodyHtml
},
},
Subject: {
Data: titleText,
Charset: 'UTF-8'
}
},
Source: process.env.EMAIL_FROM
}
console.log(JSON.stringify(params,null,4));
// Send Email
ses.sendEmail(params, function(err,data){
if(err) {
console.log(err,err.stack); // error
var response = {
statusCode: 500,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
},
body: JSON.stringify({"message":"Error: Unable to Send Message"})
}
callback(null, response);
}
else {
console.log(data); // success
var response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
},
body: JSON.stringify({"message":"Message Sent"})
}
callback(null, response);
}
});
}); //end of load text template
}); //end of load html template
};
contact/emailtemplate.html
<!DOCTYPE html>
<html>
<head>
<title>Your New Token</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
h1 { color:#f00; }
</style>
</head>
<body>
<div class="emailwrapper">
<div class="main">
<div class="content">
<h1>Hi {{given_name}}</h1>
<div style="padding:20px;">
<div>your new token is {{token}}.</div>
</div>
</div>
</div>
</div>
</body>
</html>
contact/emailtemplate.txt
Hi {{given_name}}
your new token is {{token}}.
I am creating an fb app , I just want to navigate to next page if the user already liked my page and for not liked user only onclick of like it will go to the next page . this code is working fine for my account but not for others . Can you please help me out .
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '657165490961669',
channelUrl : 'https://www.facebook.com/cypiyow',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
var page_id = "228530813943529";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
window.location = "email_form.php";
} else {
FB.Event.subscribe('edge.create',
function(response) {
window.location = "email_form.php";
}
);
}
});
} else {
//error message
}
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
in your app's settings in the facebook developer area, is this app in sandbox mode? that would cause it to only be available to you, if that is what you mean when you say it is only working for you. you would need to add some testers in your app settings or move out of sandbox mode
I am trying to check with my application if one application is installed on specific fan page and if it is not installed I want to install it..
for some reason i am unable to get the page access tokens.
I am able to get the user access tokens and user id, but the page access token returns "Exception" "Unknown fields: access_token".
What is wrong here?
I am using this resources:
http://developers.facebook.com/docs/reference/api/page/#tabs
https://developers.facebook.com/docs/authentication/
<html>
<head>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '188474844587139',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var userAccessToken = response.authResponse.accessToken;
console.log("User Access Token: "+userAccessToken);
console.log("User ID: "+uid);
// get page access token
FB.api('https://graph.facebook.com/'+uid+'/accounts?access_token='+userAccessToken, function(response) {
console.log(response);
var pageAccessToken = 'Need to get from the response...';
// get information if user got this app
FB.api("https://graph.facebook.com/102561956524622/tabs/353470634682630?access_token="+pageAccessToken,
function(data) {
console.log(data);
});
// install the app
var params = {};
params['app_id'] = '353470634682630';
FB.api('https://graph.facebook.com/102561956524622/tabs'+pageAccessToken, 'post', params, function(response) {
if (!response || response.error) {
console.log("Error: "+response);
} else {
console.log("Ok: "+response);
}
});
});
} else if (response.status === 'not_authorized') {
console.log("the user is logged in to Facebook, but not connected to the app.");
} else {
console.log("the user isn't even logged in to Facebook.");
}
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
</body>
</html>
I managed to solve this issue if any one care this is the code
One of reasons it didn't work was because I used the full address "http://graph.facebook.com..." and as you can see in the code I am using the
FB.api function which is adding this address automatically.
Another reason is that I used the user access token to get information about the application instead of the page access token.
I was also having problem to install the application because I needed to send the page access token as well.
P.S: Don't forget that you need manage_pages permission.
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '188474844587139',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
console.log(response.authResponse);
var userAccessToken = response.authResponse.accessToken;
var pageId = '102561956524622';
var appId = '353470634682630';
console.log("User Access Token: "+userAccessToken);
console.log("User ID: "+uid);
// get page access token
FB.api('/'+pageId+'?fields=access_token='+userAccessToken, function(response) {
var pageAccessToken = response.access_token;
// get information if user got this app
FB.api('/'+pageId+'/tabs/'+appId+'?access_token='+pageAccessToken,
function(data) {
if (data.data.length < 1) {
console.log("Not installed, Installing...");
// install the app
var params = {};
params['app_id'] = appId;
FB.api('/'+pageId+'/tabs?access_token='+pageAccessToken, 'post', params, function(response) {
if (!response || response.error) {
console.log("Error Installing:");
console.log(response);
} else {
console.log("Installed :)");
console.log(response);
}
});
}
else {
console.log("Already installed.");
}
});
});
} else if (response.status === 'not_authorized') {
console.log("the user is logged in to Facebook, but not connected to the app.");
} else {
console.log("the user isn't even logged in to Facebook.");
}
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));