pywintypes.com error when running pyad.adgroup on flask

620 Views Asked by At

I am creating a simple app in Python 3.5.2 that authenticates users via Active Directory and applies additional rules based on a user's group membership. The app can successfully authenticate users using the win32security package, and tries to obtain group membership info using pyad.

My problem: I get a pywintypes.com_error message when running the code on my Flask app, preventing me from getting group membership info.

When I run the backend code separately on an iPython console, it works fine. I am able to query group membership. However, when it is part of a Flask app, an error pops out. I have isolated the problem to this part of the code (DN information masked):

group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,
                                 DC=test,DC=domain,DC=com,DC=somecountry')
group_members = sum([member.get_attribute("sAMAccountName")
                    for member in group.get_members()],[])

Has anyone encountered this before? I cannot think of why the code won't run in Flask (though I have just started learning Flask) but it will run in the console.

Code Reference:

I have 3 Python files for my Flask app and an html file in the templates folder.

run.py

from app import app
import os

app.secret_key = os.urandom(16)
app.run(debug=True)

init.py

from flask import Flask

app = Flask(__name__)
from app import views

views.py

from app import app
from flask import Flask, flash, render_template, request, session

import win32security as win32
from pyad import adgroup

@app.route("/")
def home():
    if not session.get("logged_in"):
        return render_template("login.html")
    else:
        return "You are currently logged in."

@app.route("/login", methods=["GET","POST"])
def login():
    #initialize variables
    username = request.form["username"]
    password = request.form["password"]
    DOMAIN = "test.domain.com.somecountry"
    error = None

    group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,DC=test,DC=domain,DC=com,DC=somecountry')
    group_members = sum([member.get_attribute("sAMAccountName") for member in group.get_members()],[])

    if username in group_members:
        try:
            token = win32.LogonUser(username, DOMAIN, password,
                                    win32.LOGON32_LOGON_NETWORK,
                                    win32.LOGON32_PROVIDER_DEFAULT)
            is_auth = bool(token)

            if is_auth:
                session["logged_in"] = True
        except:
            error = "Incorrect credentials. Please try again."
    else:
        error = "You are not permitted to access this."

    return render_template("login.html", error=error)

login.html

<!doctype html>
<title>Login Test</title>
{% block body %}
{% if session["logged_in"] %}
<p>You are currently logged in.</p>
{% else %}
<form action="/login" method="POST">
    <input type="username" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <input type="submit" value="Log In">
</form>
<li>{{error}}</li>
{% endif %}
{% endblock %}

This is the error traceback:

Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\user\Documents\test\app\views.py", line 23, in login
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,DC=test,DC=domain,DC=com,DC=somecountry')
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 131, in from_dn
return cls(distinguished_name, None, options)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 88, in __init__
self.__set_adsi_obj()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 76, in __set_adsi_obj
self._ldap_adsi_obj = self.adsi_provider.getObject('', self.__ads_path)
File "<COMObject ADsNameSpaces>", line 2, in getObject

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221020), None)
1

There are 1 best solutions below

0
On

I was able to mitigate this error by running my same code in a python2 32bit environment.

Not sure if this is an option, but worth a shot.