Classic ASP organisational structure from AD - asp-classic

I have the following code to pull the organizational structure from Active Directory:
<%# Language="VBScript"%>
<% response.Buffer = True
'Define the AD OU that contains our users
dim department
%>
<!--#include file="includes/functions.asp"-->
<!--#include file="includes/display.asp"-->
<h1>Organisational Structure</h1>
<div class="commandspace">
<p class="infotext">The org structure can be viewed with or without staff, indented or left justified.</p>
</div>
<div class="Structure_Item_1">
<%
ADUser = "LDAP://OU=Staff,OU=Users,DC=DOMAIN,DC=internal"
' Make AD connection and run query
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.provider ="ADsDSOObject"
objCon.Properties("User ID") = "DOMAIN\example_user"
objCon.Properties("Password") = "password"
objCon.Properties("Encrypt Password") = TRUE
objCon.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText ="select company FROM '"& ADUser &"' where company ='*' ORDER by company ASC"
Set objRS = objCom.Execute
' Loop over returned recordset and output HTML
Do While Not objRS.EOF Or objRS.BOF
Response.Write "<div id='Structure_Item_Field'>" & objRS("company") & "</div>"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText ="select department FROM '"& ADUser &"' where company ='*" & objRS("company") & "*' ORDER BY company ASC"
Set department = objCom.Execute
' Loop over returned recordset and output HTML
Do While Not department.EOF Or department.BOF
Response.Write " " & department("department") & "<br>"
'&nbsp is the HTML entity of a space character. I put &nbsp four times so that the department is indented four spaces
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText ="select givenName, sn FROM '"& ADUser &"' where department ='*" & department("department") & "*' ORDER by givenName ASC"
Set names = objCom.Execute
Do While Not names.EOF Or names.BOF
Response.Write " " & names("givenName") & " " & names("sn") & "<br>"
names.MoveNext
Response.Flush
Loop
department.MoveNext
Response.Flush
Loop
objRS.MoveNext
Response.Flush
Loop
' Clean up
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCon = Nothing
Set objCom = Nothing
%>
Excuse my ignorance but it seems very slow and I'm not sure why. I'm not sure what I need to do to improve performance.

Related

Classic ASP: Type mismatch: 'GroupCheck'

I have a function named GroupCheck, which is designed to get the logged in users group from AD. It is, however, giving me the following error:
Microsoft VBScript runtime error '800a000d'
Type mismatch: 'GroupCheck'
/ldap.asp, line 67
Line 67 is where I call the function, passing in the Request.ServerVariables("AUTH_USER")
The following function is stored in a file which is included at the top of the page:
<%
function GroupCheck(user)
dim user, ADUser, objCom, objCon, objRS, membership
ADUser = "LDAP://OU=Staff,OU=Users,DC=example,DC=internal"
' Make AD connection and run query'
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.provider ="ADsDSOObject"
objCon.Properties("User ID") = "EXAMPLE\user"
objCon.Properties("Password") = "Test"
objCon.Properties("Encrypt Password") = TRUE
objCon.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText = "SELECT memberOf FROM '" + ADUser + "' where sAMAccountName='*" + 'user + "*' AND UserAccountControl <> 514"
Set objRS = objCom.Execute
Do While Not objRS.EOF Or objRS.BOF
if isNull(objRS.Fields("memberOf").value) then
membership = ""
else
for each item in objRS.Fields("memberOf").value
membership = item + "<br>"
next
end if
if inStr(membership, "UserGroup") then
GroupCheck = 1
else
GroupCheck = 0
end if
objRS.MoveNext
Response.Flush
Loop
'Clean up'
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCon = Nothing
Set objCom = Nothing
end function
%>
I really don't know what the problem is, because /ldap.asp, line 67 is :
Set getMembership(username)
EDIT: My code for ldap.asp is:
getMembership = GroupCheck(Request.ServerVariables("AUTH_USER"))
'This should fetch all the accounts that appears in the "Contact Centre" group
if getMembership = 1 then
'Response.Write "<td><a href='entry.asp?account_name=" & objRS("sAMAccountName") & "'>Edit</a></td>"
elseif objRS("sAMAccountName") = session("username") then
Response.Write "<td><a href='entry.asp?account_name=" & objRs("sAMAccountName") + "'>Edit</a></td>"
else Response.Write "<td></td>"
end if
Response.Write "</tr>" + vbCrL
objRS.MoveNext
Response.Flush
Loop
Response.Write "</table>"
' Clean up
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCon = Nothing
Set objCom = Nothing
%>
So what exactly is in line 67?
Set getMembership(username)
or
[unknown variable] = GroupCheck(Request.ServerVariables("AUTH_USER"))
?
In any case, this is probably the cause of the problem:
objCom.CommandText = "SELECT memberOf FROM '" + ADUser + "' where sAMAccountName='*" + 'user + "*' AND UserAccountControl <> 514"
In VBScript, the + operator is for arithmetic addition. "SELECT memberOf From '" cannot be converted into a number; hence the type mismatch. Probably. (I can't be sure because I don't know how you're calling or including the function.)
Instead, use the proper VBScript concatenation operator, &.
objCom.CommandText = "SELECT memberOf FROM '" & ADUser & "' where sAMAccountName='*" & user & "*' AND UserAccountControl <> 514"
Also, you're potentially shooting yourself in the foot by dimming a variable with the same name as the function argument:
function GroupCheck(user)
dim user, ADUser, objCom, objCon, objRS, membership
'^^^^
It may still work if you do that, but it's just not a good idea.

Error when leaving input blank in ASP

I am developing a script to allow users to write to Active Directory. The problem is that, when I leave a field blank, it results in an error. When, however, I put a value in, even a space, it seems happy. I have the following code:
<%#LANGUAGE="VBScript">
%>
<%
if isEmpty(request.form("subval")) then
response.write("You did not submit the form, please <a href='ldap.asp'>go back</a>")
else
'If the subval field is empty, we know the form has been submitted OK
dim firstname, lastname, email, telephonenumber, mobile, description
ADUser = "LDAP://OU=Staff,OU=Users,DC=example,DC=internal"
' Make AD connection and run query
subval = request.querystring("account_name")
'This value held the CN earlier, it is now overwriten here
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.provider ="ADsDSOObject"
objCon.Properties("User ID") = "EXAMPLE\Exampe"
objCon.Properties("Password") = "TestPassword"
objCon.Properties("Encrypt Password") = TRUE
objCon.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText ="select sAMAccountName, distinguishedName FROM '"+ ADUser +"' where sAMAccountname='"& subval &"'"
Set objRS = objCom.Execute
distinguishedName = objRS.Fields("distinguishedName")
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCom = Nothing
'We select the distinguishedName from AD
firstname = request.form("firstname")
lastname = request.form("lastname")
email = request.form("email")
telephonenumber = request.form("telephonenumber")
mobile = request.form("mobile")
description = request.form("description")
Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _ ("LDAP://" & distinguishedName)
if (IsNull(firstname)) Then
firstname = " "
end if
if (IsNull(lastname)) Then
lastname = " "
end if
if (IsNull(email)) Then
email = " "
end if
if (IsNull(telephonenumber)) Then
telephonenumber = " "
end if
if (IsNull(mobile)) Then
mobile = " "
end if
if (IsNull(description)) Then
description = " "
end if
objUser.Put "givenName", firstname
objUser.Put "mail", email
objUser.Put "sn", lastname
objUser.Put "mobile", mobile
objUser.Put "description", description
objUser.Put "telephoneNumber", telephonenumber
objUser.SetInfo
Response.Write("User data for "& subval &" has been modified")
end if
%>
The error I get whenever I leave a field blank is why I am trying to inject spaces into the variables since that seems to work in my form.
The error I get is on the SetInfo line
error '8007200b'
/updateldap.asp, line 68
I'm not sure what I can try since I've done all the stuff I can think of
8007200b = LDAP_INVALID_SYNTAX (The attribute syntax specified to the directory service is invalid)
I would say that you have worked out what the issue is. LDAP attributes cannot be NULL. You probably don't even need to have spaces, an empty string might work as well.
e.g.
if (IsNull(firstname)) Then
firstname = ""
end if

ASP and LDAP: The connection cannot be used to perform this operation. It is either closed or invalid in this context.

Continuing with ASP, I have sine code which gives the user a form, which displays data currently held in Active Directory, and lets the user update some of their details. I have tried everything but am stil getting the error
"ADODB.Command error '800a0e7d'
The connection cannot be used to perform this operation. It is either closed or invalid in this context.
/editentry.asp, line 31"
Anyway, my code isL
<%# Language=VBScript %>
<% response.Buffer = True
'Define the AD OU that contains our users
dim ADUser, user, firstname, lastname, email, telephonenumber, mobile
'This initializes all of our variables
user = request.querystring("account_name")
'This puts the value of the account_name into a variable
if len(user) = 0 then
'If the length of the username is equal to 0
response.write "Please supply a username in the query string"
elseif len(user) > 0 then
'Else is length of user is greater than 0
ADUser = "LDAP://OU=Staff,OU=Users,DC=Something,DC=internal"
' Make AD connection and run query
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.provider ="ADsDSOObject"
objCon.Properties("User ID") = "EXAMPLE\Testuser"
objCon.Properties("Password") = "TestUser1!"
objCon.Properties("Encrypt Password") = TRUE
objCon.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
objCom.CommandText ="select ADsPath, givenName,sn,mail,telephonenumber,mobile,sAMAccountName FROM '"+ ADUser +"' where sAMAccountname='"& user & "'"
'objCom.Properties("searchscope") = ADS_SCOPE_ONELEVEL
Set objRS = objCom.Execute
' Loop over returned recordset and output HTML
Response.Write vbCrLf
Do While Not objRS.EOF Or objRS.BOF
Response.Write " <form action='editentry.asp?account_name=" + user + "' method='POST'>"
Response.Write "<p><label for='firstname'>Firstname</label><input type='text' id='firstname' value='" + objRS("givenName") +"' name='fname'></p>"
Response.Write "<p><label for='lastname'>Lastname</label><input type='text' id='lastname' value='" + objRS("sn") +"' name='lname'></p>"
Response.Write "<p><label for='mail'>E-Mail Address</label><input type='text' id='lastname' value='" + objRS("mail") +"' name='email'></p>"
Response.Write "<p><label for='mobile'>Mobile</label><input type='text' id='mobile' value='" + objRS("mobile") +"' name='mobile'></p>"
Response.Write "<p><label for='telephone'>Telephone Number</label><input type='text' id='email' value='" + objRS("telephonenumber") +"' name='telephonenumber'></p>"
Response.Write "<p><input type='hidden' id='subval' value='1' name='subval'></p>"
Response.Write "<p><input type='submit' name='submit'><input type='reset' name='reset'></p>"
Response.Write "</form>" + vbCrLf
objRS.MoveNext
Response.Flush
Loop
if isEmpty(request.form("subval"))=FALSE then
'Subval will contain 1 if the form is submitted, else it won't exist, so we can check the form has been submitted by reading it back
firstname = request.form("fname")
lastname = request.form("lname")
email = request.form("email")
mobile = request.form("mobile")
telephonenumber = request.form("telephonenumber")
Do While Not objRS.EOF
Set usr = GetObject(objRS.Fields("ADsPath").Value)
usr.Put "gjvenName", firstname
usr.Put "sn", lastname
usr.Put "mail", email
usr.Put "mobile", mobile
usr.Put "telephonenumber", telephonenumber
usr.SetInfo
objRS.MoveNext
loop
response.write "Entry has been updated "
end if
end if
' Clean up
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCon = Nothing
Set objCom = Nothing
%>
I'm not sure what is wrong here
Assign the connection of the command object (before calling the Execute function) like this:
Set objCom.ActiveConnection = objCon

get value from asp result set

In the following asp page I am trying to get the fullName attribute from the first row of the result set. (there should only be one row) What is the right way to do this?
<%
set Y = server.CreateObject("ADODB.Connection")
X = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ= " & Server.MapPath(".\account.mdb")
Y.open X
user=request.Form("username")
passwd=request.Form("pwd")
set userexsist=Y.Execute("select * from logintable where username='" & user & "'")
set useraccount=Y.Execute("select * from logintable where username='"& user & "' and passwd='" & passwd & "'")
if userexsist.eof then
Response.Redirect("41697hw1noaccount.htm")
else
if useraccount.eof then
Response.Redirect("41697hw1wrongpasswd.htm")
else
Response.Write("<h1>Welcome, " & useraccount[0].fullName & "</h1>")
End if
end if
%>
The error is on `useraccount[0].fullName.
Whats the right way to get this information?
Thanks for your help!
Here's your code with as much wrong stuff as I could spot fixed:
I did test it, but not with an Access database.
It should work, but I only have a working knowledge of Classic ASP.
<%
Set Conn = Server.CreateObject("ADODB.Connection")
Set RS = Server.CreateObject("ADODB.Recordset")
Set RS2 = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ= " & Server.MapPath(".\account.mdb")
user = Request.Form("username")
passwd = Request.Form("pwd")
RS.Open "select * from logintable where username='" & user & "'", Conn
if RS.eof then
Response.Redirect("41697hw1noaccount.htm")
else
RS2.Open "select * from logintable where username='" & user & "' and passwd='" & passwd & "'", Conn
if RS2.eof then
Response.Redirect("41697hw1wrongpasswd.htm")
else
Response.Write("<h1>Welcome, " & RS2("fullName") & "</h1>")
end if
end if
%>

Querying Active Directory using VBScript

I want to query Active Directory using VBScript (classic ASP).
How can I accomplish that?
To look at all the members of an OU, try this...
Set objOU = GetObject("LDAP://OU=YourOU,DC=YourDomain,DC=com")
For each objMember in ObjOU ' get all the members'
' do something'
Next
To do a custom search for DNs try this...
set conn = createobject("ADODB.Connection")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
strQueryDL = "<LDAP://" & strDefaultNamingContext & ">;(&(objectCategory=person)(objectClass=user));distinguishedName,adspath;subtree"
set objCmd = createobject("ADODB.Command")
objCmd.ActiveConnection = Conn
objCmd.Properties("SearchScope") = 2 ' we want to search everything
objCmd.Properties("Page Size") = 500 ' and we want our records in lots of 500
objCmd.CommandText = strQueryDL
Set objRs = objCmd.Execute
While Not objRS.eof
' do something with objRS.Fields("distinguishedName")'
objRS.MoveNext
Wend
I had to query WinAD by oldskool username, this .vbs script prints user accounts.
find by sAMAccountname, use * wildcard
print few attributes from each user object
use AccountType filter its most optimized way of iterating AD user objects
Test script first gets an user object by fully qualified string, its just an example. Second part does actual query by smith* filter.
WinADSearch.vbs
' c:> cscript -nologo script.vbs
' c:> wscript script.vbs
' http://msdn.microsoft.com/en-us/library/d6dw7aeh%28v=vs.85%29.aspx
' WindowsAD queries
' http://www.kouti.com/tables/userattributes.htm
Option Explicit
'On Error Resume Next
Dim StdOut: Set StdOut = WScript.StdOut
Dim objUser
Set objUser = GetObject("LDAP://CN=Firstname Lastname,OU=Internal Users,OU=MyCompany,OU=Boston,OU=Root,DC=REGION1,DC=COM")
println(objUser.givenName & " " & objUser.middleName & " " & objUser.lastName)
println("name=" & objUser.name)
println("displayName=" & objUser.displayName)
println("userPrincipalName=" & objUser.userPrincipalName)
println("sAMAccountName=" & objUser.sAMAccountName)
println("distinguishedName=" & objUser.distinguishedName)
println("")
Dim conn, strQueryDL, strAttrs, objCmd, objRs, idx
set conn = createobject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "ADs Provider"
strAttrs = "sAMAccountName,displayName,distinguishedName" ' get attributes
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person) );" & strAttrs & ";SubTree"
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person)(objectClass=user) );" & strAttrs & ";SubTree"
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person)(objectClass=user)(sAMAccountName=smith*) );" & strAttrs & ";SubTree"
strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (samAccountType=805306368)(sAMAccountName=smith*) );" & strAttrs & ";SubTree"
set objCmd = createobject("ADODB.Command")
objCmd.ActiveConnection = Conn
objCmd.Properties("SearchScope") = 2 ' search everything
objCmd.Properties("Page Size") = 100 ' bulk operation
objCmd.CommandText = strQueryDL
println(objCmd.CommandText)
Set objRs = objCmd.Execute
idx=0
do while Not objRS.eof
idx=idx+1
println( objRs.Fields("sAMAccountName") & " / " & objRs.Fields("displayName") & " / " & objRs.Fields("distinguishedName") )
if (idx>5) then exit do
objRS.MoveNext
loop
objRs.Close
Conn.close
set objRs = Nothing
set conn = Nothing
println("end")
'********************************************************************
Sub println(ByVal str)
If (StdOut Is Nothing) Then Exit Sub
StdOut.WriteLine str
End Sub
You want to use Active Directory Service Interfaces (ADSI)
The ADSI Scripting Primer is a good place to start learning and find examples.
(btw, these links refer to Windows 2000, but are valid for subsequent versions of Windows as well).

Resources