Active Directory/Search for a user: Difference between revisions

Added FreeBASIC
(→‎{{header|Phix}}: added syntax colouring the hard way)
(Added FreeBASIC)
 
(6 intermediate revisions by 3 users not shown)
Line 1:
[[Category:Active Directory]]
{{task|Programming environment operations}}
 
Line 4 ⟶ 5:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <ldap.h>
 
char *name, *password;
Line 24 ⟶ 25:
 
ldap_msgfree(*result); /* free messages */
ldap_unbind(ld); /* disconnect */</langsyntaxhighlight>
 
=={{header|D}}==
Based on dopenldap.
<syntaxhighlight lang="d">
<lang d>
import openldap;
import std.stdio;
Line 57 ⟶ 58:
}
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
Line 63 ⟶ 64:
 
Moreover, strings in Eiffel are objects and cannot be directly passed to the Windows OS. As such, they need to undergo a format change through the facilities of a WEL_STRING, which makes the appropriate structure conversion.
<syntaxhighlight lang="eiffel">
<lang Eiffel>
feature -- Validation
 
Line 76 ⟶ 77:
Result := cwel_is_credential_valid (l_domain.item, l_username.item, l_password.item)
end
</syntaxhighlight>
</lang>
 
Because Active Directory is a Windows OS facility, in Eiffel we must use the WEL (Windows Eiffel Library) components. Thus, the code above is not cross-platform. Moreover, the call to `cwel_is_credential_valid' is shown below:
 
<syntaxhighlight lang="eiffel">
<lang Eiffel>
cwel_is_credential_valid (a_domain, a_username, a_password: POINTER): BOOLEAN
external
Line 87 ⟶ 88:
"return cwel_is_credential_valid ((LPTSTR) $a_domain, (LPTSTR) $a_username, (LPTSTR) $a_password);"
end
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
See [https://rosettacode.org/wiki/Active_Directory/Connect#FreeBASIC Active_Directory/Connect#FreeBASIC]
 
=={{header|Go}}==
Line 93 ⟶ 97:
<br>
There are a large number of third-party LDAP libraries for Go. This uses one of the simpler ones and the code below is largely taken from the example on its main page.
<langsyntaxhighlight lang="go">package main
 
import (
Line 117 ⟶ 121:
}
log.Printf("Groups: %+v", groups)
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 123 ⟶ 127:
Example uses the [https://hackage.haskell.org/package/ldap-client <tt>ldap-client</tt>] package:
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
 
module Main (main) where
Line 137 ⟶ 141:
Ldap.search ldap (Ldap.Dn "o=example.com") (Ldap.typesOnly True) (Attr "uid" := Text.encodeUtf8 "user") []
for_ entries $ \entry ->
print entry</langsyntaxhighlight>
 
=={{header|Java}}==
Line 143 ⟶ 147:
The following code uses the Apache Directory project, version 1.0.0.
 
<langsyntaxhighlight lang="java">import java.io.IOException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
Line 180 ⟶ 184:
}
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using LDAPClient
 
function searchLDAPusers(searchstring, uname, pword, host=["example", "com"])
conn = LDAPClient.LDAPConnection("ldap://ldap.server.net")
LDAPClient.simple_bind(conn, uname, pword)
 
search_string = "CN=Users,DC=$(host[1]),DC=$(host[2])"
scope = LDAPClient.LDAP_SCOPE_ONELEVEL
chain = LDAPClient.search(conn, search_string, scope, filter="(&(objectClass=person)(&(uid=$(searchstring))))")
 
for entry in LDAPClient.each_entry(chain)
println("Search for $searchstring found user $(entry["name"]) with attributes:")
for attr in LDAPClient.each_attribute(entry)
println(" ", attr)
end
end
 
LDAPClient.unbind(conn)
end
 
searchLDAPusers("Mario", "my-username", "my-password")
</syntaxhighlight>
 
=={{header|NetRexx}}==
Uses the [http://directory.apache.org/api/ Apache LDAP API], connecting to a local [http://directory.apache.org/apacheds/1.5/ ApacheDS] LDAP directory server.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 303 ⟶ 331:
 
return state
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 324 ⟶ 352:
This program drives the <tt>ldapsearch</tt> command and captures the output into an external data queue via ooRexx <tt>rxqueue</tt> facility. The contents of the queue are then read into program variables for further processing.
 
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx */
do
LDAP_URL = 'ldap://localhost:11389'
Line 384 ⟶ 412:
end
exit
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 395 ⟶ 423:
=={{header|Perl}}==
{{Trans|Raku}}
<langsyntaxhighlight lang="perl"># 20210306 Perl programming solution
 
use strict;
Line 416 ⟶ 444:
foreach my $entry ($srch->entries) { $entry->dump }
 
$mesg = $ldap->unbind;</langsyntaxhighlight>
{{out}}
<pre>
Line 434 ⟶ 462:
=={{header|Phix}}==
{{trans|C}}
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">ldap</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 460 ⟶ 488:
<span style="color: #000000;">ldap_unbind</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ld</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
Note the code inside res=LDAP_SUCCESS has not been tested beyond compiling succesfully, see also
Line 472 ⟶ 500:
{{libheader|php-ldap}}
 
<langsyntaxhighlight lang="php"><?php
 
$l = ldap_connect('ldap.example.com');
Line 487 ⟶ 515:
$entries = ldap_get_entries($l, $search);
 
var_dump($entries);</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de ldapsearch (Sn)
(in
(list "ldapsearch" "-xH" "ldap://db.debian.org"
Line 497 ⟶ 525:
(list
(cons 'cn (prog (from "cn: ") (line T)))
(cons 'uid (prog (from "uid: ") (line T))) ) ) )</langsyntaxhighlight>
Test:
<pre>: (ldapsearch "Fischer")
Line 504 ⟶ 532:
=={{header|PowerShell}}==
 
<langsyntaxhighlight lang="python">
Import-Module ActiveDirectory
 
Line 513 ⟶ 541:
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
 
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
Line 521 ⟶ 549:
[http://www.python-ldap.org/doc/html/index.html python-ldap Documentation]
 
<langsyntaxhighlight lang="python">import ldap
 
l = ldap.initialize("ldap://ldap.example.com")
Line 539 ⟶ 567:
finally:
l.unbind()
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>
<lang perl6>
 
# 20190718 Raku programming solution
Line 574 ⟶ 602:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>objectClass -> inetOrgPerson organizationalPerson top person
Line 589 ⟶ 617:
 
A little contrived; this [[REXX]] program drives the <tt>ldapsearch</tt> command.
<langsyntaxhighlight REXXlang="rexx">/* Rexx */
do
LDAP_URL = 'ldap://localhost:11389'
Line 621 ⟶ 649:
end
exit
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 639 ⟶ 667:
 
{{libheader|RubyGems}}
<langsyntaxhighlight lang="ruby">require 'rubygems'
require 'net/ldap'
 
Line 652 ⟶ 680:
results = ldap.search(:filter => filter) # returns an array of Net::LDAP::Entry objects
 
puts results[0][:sn] # ==> "Jackman"</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
Line 661 ⟶ 689:
[rename] files
[view] image files</pre>
<langsyntaxhighlight lang="runbasic">' ---------------------------------------------
' Directory maintenance
' ---------------------------------------------
Line 767 ⟶ 795:
WEND
END FUNCTION
end</langsyntaxhighlight>
Output as seen by the client on the web<pre>
Volume in drive C has no label.
Line 789 ⟶ 817:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import org.apache.directory.api.ldap.model.message.SearchScope
import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}
 
Line 824 ⟶ 852:
new LdapSearch().demonstrateSearch()
 
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 830 ⟶ 858:
 
This is just the basic setup.
<langsyntaxhighlight lang="tcl">set Username "TestUser"
set Filter "((&objectClass=*)(sAMAccountName=$Username))"
set Base "dc=skycityauckland,dc=sceg,dc=com"
set Attrs distinguishedName</langsyntaxhighlight>
 
Now do the actual search.
<langsyntaxhighlight lang="tcl">set result [ldap::search $conn $Base $Filter $Attrs -scope subtree]</langsyntaxhighlight>
If we have only a single result its easy:
<langsyntaxhighlight lang="tcl">if {[llength $result] == 1} {
puts [dict get [lindex $result 0 1] distinguishedName]
}</langsyntaxhighlight>
 
Looping over the result set to output some values.
<langsyntaxhighlight lang="tcl">foreach pair $result {
lassign $pair cn attributes
puts [dict get $attributes distinguishedName]
}</langsyntaxhighlight>
 
If you're bored you can also use this instead:
<langsyntaxhighlight lang="tcl">package require ldapx
set conn [ldapx::connect $BindDN $Password]
$conn traverse $Base $Filter $Attrs e {
puts [$e get distinguishedName]
}</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 860 ⟶ 888:
 
A shell script to drive the <tt>ldapsearch</tt> command.
<langsyntaxhighlight lang="bash">#!/bin/sh
 
LDAP_HOST="localhost"
Line 884 ⟶ 912:
$LDAP_FILTER \
$LDAP_ATTRIBUTES
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 899 ⟶ 927:
=={{header|VBScript}}==
The search string and execution of the string
<langsyntaxhighlight lang="vbscript">strUsername = "TestUser"
strQuery = "<LDAP://dc=skycityauckland,dc=sceg,dc=com>;"_
& "(&(objectclass=*)(samaccountname=" & strUsername & "));distinguishedname;subtree"
Line 905 ⟶ 933:
objCmd.Properties("Page Size")=100
objCmd.CommandText = strQuery
Set objRS = objCmd.Execute</langsyntaxhighlight>
 
Doing something with a single result (this will output the returned users full DN)
<langsyntaxhighlight lang="vbscript">If objRS.RecordCount = 1 Then
WScript.Echo objRS.Fields("DistinguishedName")
End If</langsyntaxhighlight>
 
Doing something with multiple results (this will output each returned users full DN)
<langsyntaxhighlight lang="vbscript">If objRS.RecordCount > 0 Then
For Each objUser in ObjRS
WScript.Echo objRS.Fields("DistinguishedName")
Next
End If</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|C}}
{{libheader|OpenLDAP}}
As it's not currently possible for Wren-cli to access OpenLDAP directly, we embed a Wren script in a C application to complete this task.
 
Note that, in an actual case, one would need to wrap more LDAP functions to process the search results.
<syntaxhighlight lang="wren">/* Active_Directory_Search_for_a_user.wren */
 
var LDAP_SCOPE_SUBTREE = 0x0002
 
foreign class LDAPMessage {
construct new() {}
 
foreign msgfree()
}
 
foreign class LDAP {
construct init(host, port) {}
 
foreign simpleBindS(name, password)
 
foreign searchS(base, scope, filter, attrs, attrsOnly, res)
 
foreign unbind()
}
 
class C {
foreign static getInput(maxSize)
}
 
var name = ""
while (name == "") {
System.write("Enter name : ")
name = C.getInput(40)
}
 
var password = ""
while (password == "") {
System.write("Enter password : ")
password = C.getInput(40)
}
 
var ld = LDAP.init("ldap.somewhere.com", 389)
ld.simpleBindS(name, password)
 
var result = LDAPMessage.new()
ld.searchS(
"dc:somewhere,dc=com",
LDAP_SCOPE_SUBTREE,
"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", // all persons whose names start with joe or shmoe
[], 0, result
)
 
// do stuff with result
 
result.msgfree()
ld.unbind()</syntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include <ldap.h>
#include "wren.h"
 
/* C <=> Wren interface functions */
 
void C_ldapMessageAllocate(WrenVM* vm) {
wrenSetSlotNewForeign(vm, 0, 0, sizeof(LDAPMessage*));
}
 
void C_msgfree(WrenVM* vm) {
LDAPMessage* msg = *(LDAPMessage**)wrenGetSlotForeign(vm, 0);
ldap_msgfree(msg);
}
 
void C_ldapAllocate(WrenVM* vm) {
LDAP** pldap = (LDAP**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(LDAP*));
char *host = (char *)wrenGetSlotString(vm, 1);
int port = (int)wrenGetSlotDouble(vm, 2);
*pldap = ldap_init(host, port);
}
 
void C_simpleBindS(WrenVM* vm) {
LDAP* ldap = *(LDAP**)wrenGetSlotForeign(vm, 0);
const char *name = wrenGetSlotString(vm, 1);
const char *password = wrenGetSlotString(vm, 2);
ldap_simple_bind_s(ldap, name, password);
}
 
void C_searchS(WrenVM* vm) {
LDAP* ldap = *(LDAP**)wrenGetSlotForeign(vm, 0);
const char *base = wrenGetSlotString(vm, 1);
int scope = (int)(ber_int_t)wrenGetSlotDouble(vm, 2);
const char *filter = wrenGetSlotString(vm, 3);
// no need to get attrs from slot 4 as we want all of them
int attrsonly = (int)wrenGetSlotDouble(vm, 5);
LDAPMessage** res = (LDAPMessage**)wrenGetSlotForeign(vm, 6);
ldap_search_s(ldap, base, scope, filter, NULL, attrsonly, res);
}
 
void C_unbind(WrenVM* vm) {
LDAP* ldap = *(LDAP**)wrenGetSlotForeign(vm, 0);
ldap_unbind(ldap);
}
 
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
 
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.finalize = NULL;
if (strcmp(className, "LDAP") == 0) {
methods.allocate = C_ldapAllocate;
} else if (strcmp(className, "LDAPMessage") == 0) {
methods.allocate = C_ldapMessageAllocate;
}
return methods;
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "LDAP") == 0) {
if (!isStatic && strcmp(signature, "simpleBindS(_,_)") == 0) return C_simpleBindS;
if (!isStatic && strcmp(signature, "searchS(_,_,_,_,_,_)") == 0) return C_searchS;
if (!isStatic && strcmp(signature, "unbind()") == 0) return C_unbind;
} else if (strcmp(className, "LDAPMessage") == 0) {
if (!isStatic && strcmp(signature, "msgfree()") == 0) return C_msgfree;
} else if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Active_Directory_Search_for_a_user.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
 
{{omit from|ACL2}}
{{omit from|AWK}}
Line 928 ⟶ 1,161:
{{omit from|Mathematica}}
{{omit from|Maxima}}
{{omit from|ML/I}}
{{omit from|MIPS Assembly|None of the commonly used implementations can access AD functions}}
{{omit from|ML/I}}
{{omit from|PARI/GP}}
{{omit from|PostScript}}
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have network access. -->
{{omit from|Retro}}
{{omit from|TI-83 BASIC}}
{{omit from|TI-89 BASIC}} <!-- Does not have network access. -->
{{omit from|Yorick|Does not have network access.}}
{{omit from|ZX Spectrum Basic|Does not have network access.}}
 
[[Category:Active Directory]]
2,122

edits