javascript active directory user / groups query - javascript

Is it possible to query AD from javascript?
I'm working from within SharePoint, and I can get the current SharePoint user's information using some js I found on a blog.
But I'm wondering if I can then query AD to see if the current user is in a specific AD group.

I think you'd be better off writing a quick asp.net page that you could call via AJAX and get some JSON back. .NET directory services class are going to be much better at talking to Active Directory than javascript, unless you can find a js library specifically for this (which I haven't been able to find).

This is a little late, but for future visitors from Google, I had to write something in JavaScript to fix a scheduled task that is run with cscript:
var conn = WScript.CreateObject("ADODB.Connection")
var rootDSE = GetObject("LDAP://RootDSE");
var context = rootDSE.Get("defaultNamingContext");
conn.Provider = "ADsDSOObject";
conn.Open("ADs Provider");
var query = "<LDAP://" + context + ">;(&(objectCategory=person)(objectClass=user));samAccountName;subtree";
var cmd = WScript.CreateObject("ADODB.Command");
cmd.ActiveConnection = conn;
cmd.CommandText = query;
cmd.Properties.Item("SearchScope") = 2;
cmd.Properties.Item("Page Size") = 500;
var r = cmd.Execute();
while(!r.EOF)
{
for (var e=new Enumerator(r.Fields);!e.atEnd();e.moveNext())
{
WScript.Stdout.Write(e.Item().name + "=" + e.Item().value + " ");
}
WScript.Stdout.WriteLine("");
r.MoveNext();
}

There is no way known to me how one could access AD from a client script. I could only think of some kind of an ActiveX control which does the job, however that 1) would work only in IE 2) would also be limited to zone settings in IE.
So, the reason is why you need this. Most probably, to be able to show the user something or hide something from the user. If this is the case, you could think of applying the "target audiences" solution to your page (see here - http://office.microsoft.com/en-us/sharepointserver/HA101690531033.aspx). For instance, add two versions of your webpart to the page, one for users who are in the group and another for users who aren't.
If you really need to have this information on the client side in JS, you can create some "AD helper" web service on your server and call into that service using AJAX, as per #squillman's post.

Related

Saving the output of the output of a random array?

So this function works fine, however everytime i refresh the page the WINNER (person1 to 4) changes, i want to save the output and have it FIXED so that it wont change everytime i refresh..
Basicly: There is a timer on my website and when it hits 0 , it should automaticly pick someone from the list as the winner... but the winner should appear on the website for everyone and stay there
function randomNavn(){
document.getElementById("utskrift").innerHTML = "";
for (i = 0; i < 1; i++){
randName.push(nname.splice(Math.floor(Math.random() * nname.length), 1));
}
document.getElementById("utskrift").innerHTML = randName.join(", ");
}
var nname = ["Person1", "Person2", "Person3", "Person4"],
randName = [];
You need server-side code to do this -- and most likely a database. You can't do what you want from JavaScript. Each person's browser will run that javascript and get their own answer, bit it is only on their browser. Someone else will get a different answer, etc. That's not what you want to happen I assume.
To save data more permanently to be used in a web page, you have a few options:
Create a web service that accepts POST or PUT requests and saves the data on a server. This will allow you to share data between users.
Use a cookie. This will only save a value for each user's session. It won't share data between users.
You could use localStorage:
$window.localStorage.setItem('initData', {data: 'here'}
after some nights spent i've managed to found the perfect solution.
1) I've eliminated the javascript function for the array and instead craeted a php file where a winner or more is choosed.
2) From that php file we write the winners into a text file.
3) From that text file we read it through ajax and list it when countdown is over.
If anyone is ever in need, its good solution.
Thanks for everytning

Listen for new urls of ads posted to site

for (var i = 3848450; i > 3848400; i--) {
var query = {
url: 'http://classifieds.rennug.com/classifieds/viewad.cgi?adindex=' + i,
type: 'html',
selector: 'tr',
extract: 'text'
}
,
uriQuery = encodeURIComponent(JSON.stringify(query)),
request = 'http://127.0.0.1:8888//?q=' +
uriQuery + '&callback=?';
jQuery.getJSON(request, function (data) {
var datastring = data[0].results;
var datasplit = datastring.toString().split('Sign');
$('#inner-content').append(datasplit[0]);
});
}
I want to listen for new URLs of ads that are posted without writing some kind of arbitrary code that takes up a lot of memory looping through new URLs, etc. I can do that but it seems redundant and such as my code listed above. Im using noodle.js to get the info from the pages. Now I would like a way to listen for new urls instead of looping through every possible url from a to z. Since I don't know z it's a safe bet I'll be using an if statement but how would one go about incorporating this nth URL without ending up with undefined iterations. Im still learning and find this place has many helpful people. This is simply a fun project I'm doing to learn something new.
If I understand you correcly, you want an external thing to inform your javascript when there's new a URL or JSON data
Unfortunately the web is not built for servers to contact clients, with one exception to my knowleadge: WebSockets
You already seem to have a local server so you meet the requirements plus node ships with them ready for use (also available on the browser). To use noodlejs with websockets you'd have to require the package and set up the WebSocket to send data to your client
Other than pointing you towards that direction, I don't think I can do better than the internet at giving you a tutorial. Hope this helps, Have fun! Also thanks for telling me about noodle, that thing is awesome!

Displaying a localstorage variable

This question pertian to a Chrome Browser Extension (js Injection and localstorage)
Okay, I swear I have searched for days for the answer to this question (or one similar) and either there is not one or I am a complete moron about this topic.
Here is what I'm trying to do and it should be something very simple. I am not new to chrome extensions but VERY new to creating options for the addon....
I simply want to display a saved piece of data visually. For example...
Let's say the localstorage has stored an input text field (username) as "MyUsername".
I want to recall and display that visually in the page that i am injecting code to. Here is an example...
The Code (inject.js):
var el = document.createElement('div'),
b = document.getElementsByTagName('body')[0];
otherlib = false,
el.setAttribute("id", "vBar");
el.style.position = 'fixed';
msg = 'just testing';
return showMsg();
Where you see "msg = 'just testing';"... I just want it to display the username (from local storage) instead of 'just testing'.
The Output should just look like...
MyUsername
Please tell me I'm not an idiot. I can't figure out why it's not displaying the result. It simply shows...
Undefined
When a content script accesses localStorage, it will access the storage belonging to the domain of the page where the script was injected. That's probably not what you want in this case.
You can use the chrome.storage api instead, that will allow you to share information across all your extension scripts instances and your background page.

Get Twitter Feed as JSON without authentication

I wrote a small JavaScript a couple of years ago that grabbed a users (mine) most recent tweet and then parsed it out for display including links, date etc.
It used this json call to retrieve the tweets and it no longer works.
http://twitter.com/statuses/user_timeline/radfan.json
It now returns the error:
{"errors":[{"message":"Sorry, that page does not exist","code":34}]}
I have looked at using the api version (code below) but this requires authentication which I would rather avoid having to do as it is just to display my latest tweet on my website which is public anyway on my profile page:
http://api.twitter.com/1/statuses/radfan.json
I haven't kept up with Twitter's API changes as I no longer really work with it, is there a way round this problem or is it no longer possible?
Previously the Search API was the only Twitter API that didn't require some form of OAuth. Now it does require auth.
Twitter's Search API is acquired from a third party acquisition - they rarely support it and are seemingly unenthused that it even exists. On top of that, there are many limitations to the payload, including but not limited to a severely reduced set of key:value pairs in the JSON or XML file you get back.
When I heard this, I was shocked. I spent a LONG time figuring out how to use the least amount of code to do a simple GET request (like displaying a timeline).
I decided to go the OAuth route to be able to ensure a relevant payload. You need a server-side language to do this. JavaScript is visible to end users, and thus it's a bad idea to include the necessary keys and secrets in a .js file.
I didn't want to use a big library so the answer for me was PHP and help from #Rivers' answer here. The answer below it by #lackovic10 describes how to include queries in your authentication.
I hope this helps others save time thinking about how to go about using Twitter's API with the new OAuth requirement.
You can access and scrape Twitter via advanced search without being logged in:
https://twitter.com/search-advanced
GET request
When performing a basic search request you get:
https://twitter.com/search?q=Babylon%205&src=typd
q (our query encoded)
src (assumed to be the source of the query, i.e. typed)
by default, Twitter returns top 25 results, but if you click on
all you can get the realtime tweets:
https://twitter.com/search?f=realtime&q=Babylon%205&src=typd
JSON contents
More Tweets are loaded on the page via AJAX:
https://twitter.com/i/search/timeline?f=realtime&q=Babylon%205&src=typd&include_available_features=1&include_entities=1&last_note_ts=85&max_position=TWEET-553069642609344512-553159310448918528-BD1UO2FFu9QAAAAAAAAETAAAAAcAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Use max_position to request the next tweets
The following json array returns all you need to scrape the contents:
https://twitter.com/i/search/timeline?f=realtime&q=Babylon%205&src=typd
has_more_items (bool)
items_html (html)
max_position (key)
refresh_cursor (key)
DOM elements
Here comes a list of DOM elements you can use to extract
The authors twitter handle
div.original-tweet[data-tweet-id]
The name of the author
div.original-tweet[data-name]
The user ID of the author
div.original-tweet[data-user-id]
Timestamp of the post
span._timestamp[data-time]
Timestamp of the post in ms
span._timestamp[data-time-ms]
Text of Tweet
p.tweet-text
Number of Retweets
span.ProfileTweet-action–retweet > span.ProfileTweet-actionCount[data-tweet-stat-count]
Number of Favo
span.ProfileTweet-action–favorite > span.ProfileTweet-actionCount[data-tweet-stat-count]
Resources
https://code.recuweb.com/2015/scraping-tweets-directly-from-twitter-without-authentication/
If you're still looking for unauthenticated tweets in JSON, this should work:
https://github.com/cosmocatalano/tweet-2-json
As you can see in the documentation, using the REST API you'll need OAuth Tokens in order to do this. Luckily, we can use the Search (which doesn't use OAuth) and use the from:[USERNAME] operator
Example:
http://search.twitter.com/search.json?q=from:marcofolio
Will give you a JSON object with tweets from that user, where
object.results[0]
will give you the last tweet.
Here is a quick hack (really a hack, should be used with caution as its not future proof) which uses http://anyorigin.com to scrape twitter site for the latest tweets.
http://codepen.io/JonOlick/pen/XJaXBd
It works by using anyorigin (you have to pay to use it) to grab the HTML. It then parses the HTML using jquery to extract out the relevant tweets.
Tweets on the mobile site use a div with the class .tweet-text, so this is pretty painless.
The relevant code looks like this:
$.getJSON('http://anyorigin.com/get?url=mobile.twitter.com/JonOlick&callback=?', function(data){
// Remap ... utf8 encoding to ascii.
var bar = data.contents;
bar = bar.replace(/…/g, '...');
var el = $( '<div></div>' );
el.html(bar);
// Change all links to point back at twitter
$('.twitter-atreply', el).each(function(i){
$(this).attr('href', "https://twitter.com" + $(this).attr('href'))
});
// For all tweets
$('.tweet-text', el).each(function(i){
// We only care about the first 4 tweets
if(i < 4) {
var foo = $(this).html();
$('#test').html($('#test').html() + "<div class=ProfileTweet><div class=ProfileTweet-contents>" + foo + "</div></div><br>");
}
});
});
You can use a Twitter API wrapper, such as TweetJS.com which offers a limited set of the Twitter API's functionality, but does not require authentication. It's called like this;
TweetJs.ListTweetsOnUserTimeline("PetrucciMusic",
function (data) {
console.log(data);
});
You can use the twitter api v1 to take the tweets without using OAuth. For example: this link turns #jack's last 100 tweets.
The timeline documentation is here.
The method "GET statuses/user_timeline" need a user Authentification like you can see on the official documentation :
You can use the search method "GET search" wich not require authentification.
You have a code for starting here : http://jsfiddle.net/73L4c/6/
function searchTwitter(query) {
$.ajax({
url: 'http://search.twitter.com/search.json?' + jQuery.param(query),
dataType: 'jsonp',
success: function(data) {
var tweets = $('#tweets');
tweets.html('');
for (res in data['results']) {
tweets.append('<div>' + data['results'][res]['from_user'] + ' wrote: <p>' + data['results'][res]['text'] + '</p></div><br />');
}
}
});
}
$(document).ready(function() {
$('#submit').click(function() {
var params = {
q: $('#query').val(),
rpp: 5
};
// alert(jQuery.param(params));
searchTwitter(params);
});
})

can't get ajax to work with jsp

Ok, so I'm learning web design as a co-op at a company. However, the department I'm in is lacking in knowledgeable people in web design. So here we go...
Building a site that will allow the department to manage PTO. I want to implement ajax b/c the main page will have a calendar system so the manager can view the PTO week by week. As a precursor to that, I'm attempting to implement ajax with the "add Employee" page for practice.
However, I can't seem to figure out what I'm missing (aka, why it's not doing anything)
This page just needs to add the new employee to the database. No display needed.
The main page just has 4 text fields and I get the information from those fields in javascript like so
var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");
Simple enough so far.
So I set up the ajax code like so, (this is gathered from what I've read.
var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange=dummy;
xmlhttp.send(null);
This is the part where I'm assuming it's correct as I'm still learning ajax and how it works. I don't think I need to handle a response as I simply want the called jsp file to automatically do whats needed. (if that's possible).
The jsp file looks like this
<%
ResultSet rsEmpl;
Connection connection1 = getDBConnection();
Statement statment1=connection1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String fName = request.getParameter("firstNameField");
String lName = request.getParameter("lastNameField");
String manager = request.getParameter("managerField");
String networkID = request.getParameter("networkIDField");
Int empId = 0;
String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);
rsEmpl.last();
empId = rsEmpl.getRow() - 1;
statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);
%>
I have a button on the page that executes the javascript function that contains the ajax info. I'm avoiding jquery atm b/c I'm trying to understand this stuff and how it works before I attempt to use "shortcuts" like jquery. I'm working towards a degree in Software Engineering so understanding this stuff is my priority, not getting it done.(that's just a bonus) If you need anymore information I can provide it. Sorry for my lack of knowledge and if this is completely off base then :(
The main page just has 4 text fields and I get the information from those fields in javascript like so
var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");
That gives you whole HTML DOM elements back, not the values of those elements. HTML DOM elements are like Java classes, having properties, methods and so on. Assuming that it are HTML input elements like <input>, then use their value property instead to get the value. So:
var firstName = document.getElementById("firstNameField").value;
var lastName = document.getElementById("lastNameField").value;
var manager = document.getElementById("managerField").value;
var networkID = document.getElementById("networkIDField").value;
So I set up the ajax code like so, (this is gathered from what I've read.
var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange=dummy;
xmlhttp.send(null);
The escape() is the wrong function. It escapes JS syntax, it does not encode URI components. You should be using encodeURIComponent() function instead.
The jsp file looks like this
...
Int empId = 0;
...
This doesn't compile. It should be int instead.
...
String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);
rsEmpl.last();
empId = rsEmpl.getRow() - 1;
...
Unnecessarily overcomplicated. Learn how to use DB builtin sequences/autoincrement IDs. Refer the DB specific manual or ask DB admin for help.
...
statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);
...
You should put quotes around string values in the SQL query. Assuming that lName, fName and networkID are strings, not numbers, then it should look like this:
statement1.execute("INSERT INTO PTO_employee VALUES (" + empID + ",'" + lName + "','" + fName + "'," + 0 + "," + 2 + ",'" + networkID + "'");
But you have there a huge SQL injection attack hole and you also don't seem to close DB resources at all after use, so they may leak away and cause your webapp to crash sooner or later because the DB runs out of resources. Use PreparedStatement to create a parameterized SQL query and use its setters to set the values. Close the resources in finally block.
After all, reading the server logs should provide you information about compile errors and any server exceptions. Reading the ajax response should provide you information about the response status and body. Your core problem was that you ignored it and thus didn't have any chance to understand what is happening.

Categories