<commit_before>#!/usr/bin/python

# -*- coding: utf-8 -*-

# Copyright (C) 2009-2012:
#    <NAME>, <EMAIL>
#    <NAME>, <EMAIL>
#    <NAME>, <EMAIL>
#    <NAME>, <EMAIL>
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken.  If not, see <http://www.gnu.org/licenses/>.

"""
This class is for linking the WebUI with active directory,
like check passwords, or get photos.
"""

import os

try:
    import ldap
except ImportError:
    ldap = None

from shinken.log import logger
from shinken.basemodule import BaseModule


properties = {
    'daemons': ['webui', 'skonf'],
    'type': 'ad_webui'
    }


# called by the plugin manager
def get_instance(plugin):
    logger.debug("[Active Directory UI] Get an Active Directory/OpenLdap UI module for plugin %s" % plugin.get_name())
    if not ldap:
        raise Exception('The module python-ldap is not found. Please install it.')
    instance = AD_Webui(plugin)
    return instance


class AD_Webui(BaseModule):
    def __init__(self, modconf):
        BaseModule.__init__(self, modconf)
        self.ldap_uri = getattr(modconf, 'ldap_uri', None)
        self.username = getattr(modconf, 'username', '')
        self.password = getattr(modconf, 'password', '')
        self.basedn = getattr(modconf, 'basedn', '')
        # If we got no uri, we bailout...
        if not self.ldap_uri:
            self.active = False
        else:
            self.active = True
        self.con = None
        # Switch between active directory and OpenLdap mode
        self.mode = getattr(modconf, 'mode', 'ad')
        if self.mode not in ['ad', 'openldap']:
            raise Exception('WebUI Auth ldap module error, mode is not in ad or openldap')

        self.retrieveAttributes = {
            'ad' : ["userPrincipalName", "thumbnailPhoto", "samaccountname", "email"],
            'openldap' : ["cn", "jpegphoto", "uid", "mail"]
            }[self.mode]
        self.photo_attr = {
            'ad' : 'thumbnailPhoto',
            'openldap' : 'jpegPhoto'
            }[self.mode]
        self.name_id = {
            'ad' : 'userPrincipalName',
            'openldap' : 'uid'
            }[self.mode]
        self.auth_key = {
            'ad' : 'userPrincipalName',
            'openldap' : 'dn'
            }[self.mode]
        self.search_format = {
            'ad' : "(| (samaccountname=%s)(mail=%s))",
            'openldap' : "(| (uid=%s)(mail=%s))"
            }[self.mode]
        

    # Try to connect if we got true parameter
    def init(self):
        if not self.active:
            return
#        self.connect()

    def connect(self):
        logger.debug("[Active Directory UI] Trying to initialize the AD/Ldap connection")
        self.con = ldap.initialize(self.ldap_uri)
        self.con.set_option(ldap.OPT_REFERRALS, 0)

        logger.debug("[Active Directory UI] Trying to connect to AD/Ldap %s with user %s  on baseDN %s" % (self.ldap_uri, self.username, self.basedn))
        # Any errors will throw an ldap.LDAPError exception
        # or related exception so you can ignore the result
        self.con.simple_bind_s(self.username, self.password)
        logger.info("[Active Directory UI] AD/Ldap Connection done")


    def disconnect(self):
        self.con = None


    # To load the webui application
    def load(self, app):
        self.app = app


    # Give the entry for a contact
    def find_contact_entry(self, contact):
        if not self.active:
            return None

        if not contact:
            return None

        # First we try to connect, because there is no "KEEP ALIVE" option
        # available, so we will get a drop after one day...
        self.connect()

        logger.info("[Active Directory UI] AD/LDAP: search for contact %s" % contact.get_name())
        searchScope = ldap.SCOPE_SUBTREE
        ## retrieve all attributes
        #retrieveAttributes = ["userPrincipalName", "thumbnailPhoto", "samaccountname", "email"]

        cname = contact.get_name()
        email = contact.email
        searchFilter = self.search_format % (cname, email)
        logger.info("[Active Directory UI] Filter %s" % str(searchFilter))
        try:
            ldap_result_id = self.con.search(self.basedn, searchScope, searchFilter, self.retrieveAttributes)
            result_set = []
            while 1:
                result_type, result_data = self.con.result(ldap_result_id, 0)
                if (result_data == []):
                    logger.warning("[Active Directory UI] No result for %s" % cname)
                    return None
<commit_msg>Add: manage the future synchronizer daemon<commit_after>#!/usr/bin/python

# -*- coding: utf-8 -*-

# Copyright (C) 2009-2012:
#    <NAME>, <EMAIL>
#    <NAME>, <EMAIL>
#    <NAME>, <EMAIL>
#    <NAME>, <EMAIL>
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken.  If not, see <http://www.gnu.org/licenses/>.

"""
This class is for linking the WebUI with active directory,
like check passwords, or get photos.
"""

import os

try:
    import ldap
except ImportError:
    ldap = None

from shinken.log import logger
from shinken.basemodule import BaseModule


properties = {
    'daemons': ['webui', 'skonf', 'synchronizer'],
    'type': 'ad_webui'
    }


# called by the plugin manager
def get_instance(plugin):
    logger.debug("[Active Directory UI] Get an Active Directory/OpenLdap UI module for plugin %s" % plugin.get_name())
    if not ldap:
        raise Exception('The module python-ldap is not found. Please install it.')
    instance = AD_Webui(plugin)
    return instance


class AD_Webui(BaseModule):
    def __init__(self, modconf):
        BaseModule.__init__(self, modconf)
        self.ldap_uri = getattr(modconf, 'ldap_uri', None)
        self.username = getattr(modconf, 'username', '')
        self.password = getattr(modconf, 'password', '')
        self.basedn = getattr(modconf, 'basedn', '')
        # If we got no uri, we bailout...
        if not self.ldap_uri:
            self.active = False
        else:
            self.active = True
        self.con = None
        # Switch between active directory and OpenLdap mode
        self.mode = getattr(modconf, 'mode', 'ad')
        if self.mode not in ['ad', 'openldap']:
            raise Exception('WebUI Auth ldap module error, mode is not in ad or openldap')

        self.retrieveAttributes = {
            'ad' : ["userPrincipalName", "thumbnailPhoto", "samaccountname", "email"],
            'openldap' : ["cn", "jpegphoto", "uid", "mail"]
            }[self.mode]
        self.photo_attr = {
            'ad' : 'thumbnailPhoto',
            'openldap' : 'jpegPhoto'
            }[self.mode]
        self.name_id = {
            'ad' : 'userPrincipalName',
            'openldap' : 'uid'
            }[self.mode]
        self.auth_key = {
            'ad' : 'userPrincipalName',
            'openldap' : 'dn'
            }[self.mode]
        self.search_format = {
            'ad' : "(| (samaccountname=%s)(mail=%s))",
            'openldap' : "(| (uid=%s)(mail=%s))"
            }[self.mode]
        

    # Try to connect if we got true parameter
    def init(self):
        if not self.active:
            return
#        self.connect()

    def connect(self):
        logger.debug("[Active Directory UI] Trying to initialize the AD/Ldap connection")
        self.con = ldap.initialize(self.ldap_uri)
        self.con.set_option(ldap.OPT_REFERRALS, 0)

        logger.debug("[Active Directory UI] Trying to connect to AD/Ldap %s with user %s  on baseDN %s" % (self.ldap_uri, self.username, self.basedn))
        # Any errors will throw an ldap.LDAPError exception
        # or related exception so you can ignore the result
        self.con.simple_bind_s(self.username, self.password)
        logger.info("[Active Directory UI] AD/Ldap Connection done")


    def disconnect(self):
        self.con = None


    # To load the webui application
    def load(self, app):
        self.app = app


    # Give the entry for a contact
    def find_contact_entry(self, contact):
        if not self.active:
            return None

        if not contact:
            return None

        # First we try to connect, because there is no "KEEP ALIVE" option
        # available, so we will get a drop after one day...
        self.connect()

        # In the synchronizer the object can be a dict
        if isinstance(contact, dict):
            cname = contact.get('contact_name', '')
            email = contact.get('email', '')
        else:
            cname = contact.get_name()
            email = contact.email

        logger.info("[Active Directory UI] AD/LDAP: search for contact %s" % cname)
        searchScope = ldap.SCOPE_SUBTREE
        ## retrieve all attributes
        #retrieveAttributes = ["userPrincipalName", "thumbnailPhoto", "samaccountname", "email"]

        searchFilter = self.search_format % (cname, email)
        logger.info("[Active Directory UI] Filter %s" % str(searchFilter))
        try:
            ldap_result_id = self.con.search(self.basedn, searchScope, searchFilter, self.retrieveAttributes)
            result_set = []
            while 1:
                result_type, result_data = self.con.result(ldap_result_id, 0)
                if (result_data == []):
                    logger.warning("[Active Directory UI] No result for %s" % cname)
                    return None

{'fraction_non_alphanumeric': 0.10975725844835793, 'fraction_numerical': 0.0024750118990956686, 'mean_word_length': 2.3792216146670957, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3344289', 'n_tokens_mistral': 3151, 'n_tokens_neox': 3051, 'n_words': 991}