Showing posts with label user data from active directory. Show all posts
Showing posts with label user data from active directory. Show all posts

22 August, 2013

Fetch current login user data from active directory using JavaScript in SharePoint

Problem Description:
Fetch current login user data from active directory using JavaScript in SharePoint.

Resolution:

<script type="text/javascript">
/* getUserName function is use to find Current System User */
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,physicalDeliveryOfficeName FROM 'LDAP://DomainName.com/DC=Domain,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;
  samaccountname= objRecordSet.Fields("samaccountname").value;
  physicalDeliveryOfficeName= objRecordSet.Fields("physicalDeliveryOfficeName").value;
 }
 else
 {
  userMail = "";
  firstName = "";
  lastName = "";
  physicalDeliveryOfficeName = "";
 }
 objConnection.Close;
 return userMail+";"+firstName+";"+lastName+";"+physicalDeliveryOfficeName;
}

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

var mail = AD[0];
var firstName = AD[1];
var lastName = AD[2];
var Office = AD[3];
</script>


References:
In objCommand.CommandText make connection string properly.

In Select query use column name of active directory from which you want data.
Refer this link for column name:

Product Applies To:
·         SharePoint Server 2010
·         SharePoint Foundation 2010
·         SharePoint Server 2013


Feel free to revert in-case of any query...