Python3 LDAP query to get name and email of a specific group - python

I would like to get the users' name and email of a specific group when querying an LDAP server using ldap3 Python library.
I have been trying the following command, but I am not getting also the email address.
c.search(search_base=LDAP_BASE,search_filter=("(&(objectclass=group)(cn=test-group))"),attributes=["*"])
Any idea how to get have this filter to retrieve the desired data?
This query is not retrieving also the email address.
Thank you.

If everyone needs the same query, here is the answer:
# Firstly find out the DN associated with LDAP group
c.search(base_dn, '(sAMAccountName="test-group")',
search_scope=SUBTREE, attributes=['distinguishedName', 'member'])
dn_json = json.loads(c.response_to_json())
distinguished_name = dn_json["entries"][0]["attributes"]["distinguishedName"]
# Retrieve data based on DN
c.search(base_dn, '(&(objectclass=user)(memberOf={}))'.format(distinguished_name),
attributes=["givenName", "sn", "mail"])
user_data = json.loads(c.response_to_json())
for index in range(len(user_data["entries"])):
first_name = user_data["entries"][index]["attributes"]["givenName"]
surname = user_data["entries"][index]["attributes"]["sn"]
mail = user_data["entries"][index]["attributes"]["mail"]

Related

Having issues with accessing activity tables though Oracle Eloqua's API in python

So I am working with Eloqua's API gets in python and was successfully able to connect to a varity of endpoints using this method, but am having trouble connecting to the Activity tables (see referenced documentation)
Here is the code the I am trying to run:
id = 123
startDate = 1656685075
endDate = 1659363475
type = 'emailOpen'
url_eloqua = f'http://secure.p04.eloqua.com/API/REST/1.0/data/activities/contact/{id}?type={type}&startDate={startDate}&endDate={endDate}'
print(url_eloqua)
user_eloqua = dbutils.secrets.get(scope = "abc", key = "Eloqua_User")
password_eloqua = dbutils.secrets.get(scope = "abc", key = "Eloqua_Pswd")
results = requests.get(url_eloqua, auth=HTTPBasicAuth(user_eloqua, password_eloqua), headers={'Content-Type':'application/json'}).json()
results
And here is the response that I am getting both in postman and in python:
http://secure.p04.eloqua.com/API/REST/1.0/data/activities/contact/123?type=emailOpen&startDate=1656685075&endDate=1659363475
Out[65]: {'Message': 'There was an error processing the request.',
'StackTrace': '',
'ExceptionType': ''}
Does anyone know what I am doing wrong here? I could really use some support in getting this to work. It lookes to be formated correctly and the general format matches other endpoints build that have successfully produced and output. The id is made up here but the real id is associated with a confirmed id in Eloqua.
Nevermind. My issue was that I was associated the wrong id. Was inputing the activity id instead of the contact id.

How to check if data exist in firebase. (KivyMD Python)

I'm new to Python and KivyMD. Also to working with Databases. I want to check if the data provided by the user using the KivyMD App is already in the Firebase Realtime Database. These are the data in the firebase.
The Code
def send_data(self, email):
from firebase import firebase
firebase = firebase.FirebaseApplication("https://infinity-mode-default-rtdb.firebaseio.com/", None)
data = {
'Email' : email
}
if email.split() == []:
cancel_btn_checkpoint_dialogue = MDFlatButton(text='Retry', on_release=self.close_checkpoint_dialogue)
self.checkpoint_dialog = MDDialog(title='Access Denied', text="Invalid Username"),
buttons=[cancel_btn_checkpoint_dialogue])
self.checkpoint_dialog.open()
else:
firebase.post('Users', data)
If the user enters an existing value in the database, that value should not be saved in the database. Also a Dialog box should be shown that the email is already in use. If the value provided by the user is not in the database it should be saved. Please help me to do this.
Did you try with firebase_admin?
I check my data with like this:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
cred = credentials.Certificate(
"firestore-cred.json"
)
firebase_admin.initialize_app(cred)
db = firestore.client()
data = {
"Email" : email
}
query_email = db.collection(u'Users') \
.where(u"Email",u"==",data["Email"]) \
.get()
if query_email:
# exists
...
else:
# does not exist
...
If user email does not exist, query_email is going to be empty list.
Do not forget that query_email is not json data. You can convert it json with to_dict():
email_query_result_as_json = query_email[0].to_dict()
I'm guessing you use python-firebase which so far has very little documentation. So I'll try to do my best based on the package source...
You have to use firebase.get method to retrieve a dictionary with the current data stored for a given user, then check if that data contains the information you are going to add (untested, since firebase doesn't even import on my machine):
record = firebase.get('/Users', 'id')
if not record.get('Email'):
firebase.post('/Users/'+'id', data)
Try using the dataSnapshot.exist() method or the snapshot.hasChild method, they work in python, I'm not 100% sure whether they work in python but it is worth a go.

Querying Cloud Datastore - Returning all submissions from currently logged in user

I am trying to retrieve all entities that a user has submitted and have tried to do this by using the user's email address as the filter, but I receive this error when querying the datastore:
ValueError: Name 'test#example.com' cannot contain period characters
Query:
email = users.get_current_user().email()
q = WorkRequest.query().filter(email)
results = q.fetch(10)
Can anyone help?
You have not structured the query properly. Try this:
mail = users.get_current_user().email()
q = WorkRequest.query(WorkRequest.email == mail)
results = q.fetch(10)

Adding AD group with python-ldap

I am trying to create group within AD with no success, below is my code:
import ldap
import ldap.modlist as modlist
LDAPserver = 'hidden'
LDAPlogin = 'hidden'
LDAPpassword = 'hidden'
l = ldap.initialize('ldap://' + LDAPserver)
l.simple_bind_s(LDAPlogin, LDAPpassword)
dn = 'OU=someunit,OU=someunit,OU=someunit,OU=someunit,DC=my-company,DC=local'
attrs = {}
attrs['objectclass'] = ['top','Group']
attrs['cn'] = 'group name to be created'
attrs['description'] = 'Test Group'
ldif = modlist.addModlist(attrs)
l.add_s(dn,ldif)
l.unbind_s()
Following snippet gives me an error:
ldap.INSUFFICIENT_ACCESS: {'info': '00000005: SecErr: DSID-031521D0, problem 4003
(INSUFF_ACCESS_RIGHTS), data 0\n', 'desc': 'Insufficient access'}
However, using same credentials I can create group with some UI tools like LDAP Admin
so I suppose that I have proper permissions to create groups, but still no success with python-ldap.
I can also query existing groups and fetch its members via script.
I believe that the problem is in my attributes, maybe Active Directory need some different values to be inserted into attrs variable. AD is running under Win Server 2012 R2.
Any help would be appreciated :)
The dn should actually be CN=<groupname> + base_dn, so in your case something like
dn = 'CN=groupname,OU=someunit,OU=someunit,OU=someunit,OU=someunit,DC=my-company,DC=local'
Please try to replace LDAPlogin to a full bind dn value such as
"cn=hidden,dc=example,dc=com"

How to retrieve the latest modified tasks using REST API?

I am creating a integration tool to integrate with rally and my web application. I decided to use Python to run in my web-server to retrieve the contents from rally.
In one of the scenario, I need to get the last modified task from a story. I don't know the ID, Name or anything, but I know the story name. Using the story name, how can I get the last modified task(s)?
Here's an example of how to set up Kyle's query in pyral:
server = "rally1.rallydev.com"
user = "user#company.com"
password = "topsecret"
workspace = "My Workspace"
project = "My Project"
rally = Rally(server, user, password, workspace=workspace, project=project)
rally.enableLogging("rally.history.showtasks")
fields = "FormattedID,State,Name,WorkProduct,Name,LastUpdateDate",
criterion = 'Workproduct.Name = "My Tasks User Story"'
response = rally.get('Task', fetch=fields, query=criterion, order="LastUpdateDate Desc",pagesize=200, limit=400)
most_current_task = response.next()
print "%-8.8s %-52.52s %s" % (most_current_task.FormattedID, most_current_task.Name, most_current_task.State)
I'm not super familiar with how to use pyral but you should be able to get what you'd like by querying against the task wsapi endpoint like so:
/slm/webservice/1.40/task.js?query=(WorkProduct.Name = "Story Name")&order=LastUpdateDate DESC
Now you just need to get pyral to generate that request. :-)

Categories

Resources