get text from page and put it into a variable - javascript

I want to extend a facebook access token using the method below:
function extend(fb_access_token) {
var extendingUrl;
try{
console.log("Extending Facebook Access Token.");
if (app_id == "" || app_id == null) {
alert("App ID not configured properly.");
hasError = true;
return;
} else {
hasError = false;
}
if (app_secret == "" || app_secret == null) {
alert("App Secret not configured properly.");
hasError = true;
return;
} else {
hasError = false;
}
if (fb_access_token == "" || fb_access_token == null) {
alert("Facebook Access Token not was not generated.");
hasError = true;
return;
} else {
hasError = false;
}
if(hasError) {
alert("URL not formed.");
} else {
extendingUrl = "https://graph.facebook.com/oauth/access_token?client_id="+app_id+"&client_secret="+app_secret+"&grant_type=fb_exchange_token&fb_exchange_token="+fb_access_token;
window.location.replace = extendingUrl;
console.log("Facebook Access Token successfully extended.");
}
} catch (OAuthException) {
console.log("Login status or access token has expired, been revoked, or is otherwise invalid.");
}
}
I want to get the generated access token from the page that will eventually give the extended access token, see var extendingUrl.
The page will return something like:
access_token=CAAERkjuisOYBALHbBZB9oq01ybCoyBfyGlSHtkkZBDqDvevrWZC42JwMawxxxOxQsiKHMNVPHZCbh3ntF7GdnYwnq3BLTh6ZA2YUJCVSh8QA5nEZACZCXVtZCL5RZC72pl3afKMAOMG2WGKtjnD1GJTjQEPC2XH3X1ycr3GeAUWBShDj7ojFVCWhDe6jBGvBu2nn7Ohu9C2udBoamOBxoQFun&expires=5182005
and I will substring the string above and eliminate access_token= and &expires=5182005 to a new variable, and store it into my database.

Got it. I used jquery and fed the url (extendingUrl), in return, it gave me the contents of the url I requested. Then I used regex and substring to eliminate the unwanted text.
$.get(extendingUrl, function(data) {
var raw = data;
var patt1 = /(access_token=)(.*)(?=&expires=)/;
var result = raw.match(patt1);
var longToken = result[0].substring(13, 400);
});

Related

How to Validate the Anti-XSRF token in pure javascript

I have a base page in my asp.net application where where am setting _antiXsrfTokenValue like below.
const string ViewStateFieldName = "__VIEWSTATEKEY";
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.IsViewStateEnabled)
{
if (requestCookie != null && requestCookieGuidValue != Guid.Empty)
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
}
}
}
I'm also setting the user name in Page_PreLoad like below.
protected void Page_PreLoad(object sender, EventArgs e)
{
// this check is required because when user come from MTS then CUser is null, so get user identity
string userName;
if (CUser.Current == null)
{
userName = string.Empty;
if (Request.IsAuthenticated)
{
var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
userName = userClaims?.FindFirst("preferred_username")?.Value;
}
}
else
{
userName = CUser.Current.UserName;
}
if (ViewState != null && Context != null && userName != string.Empty)
{
if (!IsPostBack)
{
if (Page != null)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey ?? "";
ViewState[AntiXsrfUserNameKey] = userName;
}
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != userName)
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
}
So with the code samples above, does any one know how i can do the below C# check in javascript?
// Validate the Anti-XSRF token
//I need to do the below check in Javascript.
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != userName)
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}

Redirecting to app store using window.location

I have a script that checks to make sure that I am on a mobile device, grabs a feed with a list of apps and their app store addresses, and then calls on a function that, depending on what type of device it is, redirects the user to the correct app page.
var redirecToAppPage = function(device, types) {
var url;
if (device === 'android') {
url = types.android;
} else if (device === 'iphone' || device === 'ipod') {
url = types.apple;
} else if (device === 'ipad') {
url = types.apple;
} else if (device === 'blackberry') {
url = types.phone;
}
if (url) {
window.location = url;
return false;
}
return url;
};
This is not working. The redirect never happens, and instead it executes the rest of the code on the page.
I have tried window.location, window.location.href, window.location.assign(url), and window.location.replace(url), none of them working. Any ideas why this wouldn't work?
I remake you function and worked well for me with this example:
function redirectToAppPage(device, types) {
var url;
if (device === 'android') {
url = types.android;
} else if (device === 'iphone' || device === 'ipod') {
url = types.apple;
} else if (device === 'ipad') {
url = types.apple;
} else if (device === 'blackberry') {
url = types.phone;
}
if (url) {
window.location.replace(url);
}
}
// Example
var device = 'android';
var types = {
android : "https://www.apple.com/itunes/"
}
redirectToAppPage(device, types);
Tried it with jsfiddle.

Empty php session (if else statement)

I've been wanting to create a JavaScript function that changes the PHP session timeout for both logged-in and not-logged-in user.
I've added the session timeout to header.php. This is because when users are logged in, users are able to access whole website. However, some pages are accessible to both logged-in and not-logged-in users.
I'm not sure how to make the JavaScript in if else statement such it will differentiate guest session id or may be the success of the Ajax to accommodate the true or false return from the PHP. I'm unsure how it should be done.
As of now, my website will show the pop out for both logged-in and not-logged-in users as I've added the session timeout and the Ajax in header.php
Searched everywhere, but could not find any leads at all. Please help me. Thanks! Here's my code.
ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
if (xmlReq.responseText == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
}
}
It looks to me as if your server returns 1 which is what the line xmlReq.responseText == 1 is evaluating. Instead just return a JSON object and then parse that response and look for the result.
In PHP, return a JSON encoded array as opposed to return true
return json_encode(array(
'role' => $_SESSION['role'], //assuming something like guest/logged-in
'user_id' => $_SESSION['user_id']
));
Then parse your response text like such in order to make a comparison:
var obj = xmlReq.responseText;
var jsonObj = JSON.parse(obj);
//now we can make a comparison against our keys 'role' and 'user_id'
if(jsonObj['role'] == 'guest'){
//guest role, do something here
} else if (jsonObj['role'] == 'logged-in') {
//do something else for logged in users
}
Good luck.

Disable CRM form control through plugin / javascript based on specific Security Role

I have requirement to disable certain control's on the CRM form based on the user's role.
I am new to CRM & I am not fully sure how can I check user's role through javascript.
Requirement is that if user has certain roles I need to disable some controls on the form.
It would be nice if you can put code snippet. Thank you.
Exact scenario : Disable some control on CRM Account form through plugin/javascript based on some specific condition of other control (i.e When some picklist has some specific value I would like to disbale control and if user changes I would like to enable as well.
In JavaScript you can get Current User's Security Roles as following
var roles = Xrm.Page.context.getUserRoles();
Following code should work for you.
function OnLoad() {
if (UserHasRole("Security Role Name")) {
Xrm.Page.getControl("fieldname").setDisabled(true);
} else {
Xrm.Page.getControl("fieldname").setDisabled(false);
}
}
function UserHasRole(roleName) {
var serverUrl = Xrm.Page.context.getServerUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
var org = Xrm.Page.context.getOrgUniqueName()
var oDataEndpointUrl = "/" + org + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += "RoleSet?$top=1&$filter=Name eq '" + roleName + "'";
var service = GetRequestObject();
if (service != null) {
service.open("GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json, text/javascript, */*");
service.send(null);
var requestResults = eval('(' + service.responseText + ')').d;
if (requestResults != null && requestResults.results.length == 1) {
var role = requestResults.results[0];
var id = role.RoleId;
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRole = currentUserRoles[i];
if (GuidsAreEqual(userRole, id)) {
return true;
}
}
}
}
return false;
}
function GetRequestObject() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
}
else {
try
{
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
} catch (ex) {
return null;
}
}
}
function GuidsAreEqual(guid1, guid2) {
var isEqual = false;
if (guid1 == null || guid2 == null) {
isEqual = false;
} else {
isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
}
return isEqual;
}
Apart from that, have a look at field level security feature in Dynamics CRM. Check the link below:
How to configure Field Level Security in Microsoft Dynamics CRM 2011

Override Ext.data.Connection - Best Practice

I need to override Ext.data.Connection to show a Login Form.
I do this at the moment in Ext.application.launch which works as expected.
Is it possible to swap this piece of code somewhere different like in an extra file?
If you need this only to recognize when user is not authenticated you might want to consider doing something else. Like adding a handler to Ajax singleton:
function addAjaxErrorHandler(object) {
Ext.Ajax.on('requestexception', function(conn, response, options, e) {
var statusCode = response.status,
errorText = null,
captionText = response.statusText;
// 404 - file or method not found - special case
if (statusCode == 404) {
Ext.MessageBox.alert('Error 404', 'URL ' + response.request.options.url + ' not found');
return;
}
if (response.responseText != undefined) {
var r = Ext.decode(response.responseText, true);
if (r != null) {
// 401 - not authenticated. For some reason we don't have authentication cookie anymore
if (r.ErrorCode == 401) {
Ext.MessageBox.alert('Error', 'You must log in to use application',
function() {
// do something when user is not authenticated
object);
return;
}
errorText = r.ErrorMessage;
}
if (errorText == null)
errorText = response.responseText;
}
if (!captionText)
captionText = 'Error ' + statusCode;
Ext.MessageBox.alert(captionText, errorText);
},
object);
}
Then just call this function from your application.launch() function and pass application object so the scope if defined.

Categories

Resources