Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday, June 5, 2011

How to get user data from active directory using javascript.

Recently I've been working on SAP Portal password reset tool, that is asking user to enter his user id, email, name, etc. I've made a script to get required information from company's active directory domain. This javascript unfortunately working only in IE.
Function getUserName() takes currently logged in user's name.
Function getAD(userName) search our company AD to get user's email and first/last name.
This script can give you an idea on how to query active directory domain.

And the source code:
function getUserName() {
var wshNetwork = new ActiveXObject("WScript.Network");
var userName = wshNetwork.UserName;
return userName;
}

function getAD(userName) {
//var name = userName.split(".");
objConnection = new ActiveXObject("ADODB.Connection");
objConnection.Provider="ADsDSOObject";
objConnection.Open("ADs Provider");
objCommand = new ActiveXObject("ADODB.Command");
objCommand.ActiveConnection = objConnection;

objCommand.CommandText = "SELECT sAMAccountName, givenName, SN, mail FROM 'LDAP://ad.mycompany.com/OU=User Accounts,OU=User Directory,DC=ad,DC=mycompany,DC=com' WHERE objectCategory='user' and sAMAccountName = '"+userName+"'";

/* Next up is the command itself.*/
objRecordSet = objCommand.Execute();

/* Then we execute the command */
/* Once executed, the command will return an enumeration of the results.*/

var userMail,lastName,firstName;
if (objRecordSet.RecordCount == 1) {
objRecordSet.Movefirst;
userMail = objRecordSet.Fields("mail").value;
firstName = objRecordSet.Fields("givenName").value;
lastName = objRecordSet.Fields("SN").value;
}
else
{
userMail = "";
firstName = "";
lastName = "";
}
objConnection.Close;

return userMail+";"+firstName+";"+lastName;
}

var AD = getAD(getUserName()).split(";");

var mail = AD[0];
var firstName = AD[1];
var lastName = AD[2];


If this post help you, please don't hesitate to share it.