<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import importlib
import datetime

from django.conf import settings
from django.db import models
from django.db import transaction
from django.db.models.signals import post_save
from django.core.exceptions import ValidationError
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.template.defaultfilters import slugify
from model_utils import Choices
from model_utils.fields import StatusField
from model_utils.models import TimeStampedModel
from model_utils.managers import InheritanceManager, QueryManager

from litedesk.lib.active_directory.session import Session
from litedesk.lib.active_directory.classes.base import Company, User as ActiveDirectoryUser
from audit.models import Trackable, UntrackableChangeError
from syncremote.models import Synchronizable

import tasks

log = logging.getLogger(__name__)


if not hasattr(settings, 'PROVISIONABLE_SERVICES'):
    settings.PROVISIONABLE_SERVICES = []


class ServiceMeta(object):
    def __init__(self, class_path_string):
        module_name, class_name = class_path_string.rsplit('.', 1)
        module = importlib.import_module(module_name)
        klass = getattr(module, class_name)
        self.model_class = klass
        self.meta = klass._meta

    @property
    def slug(self):
        return self.model_class.service_slug()

    @property
    def name(self):
        return self.meta.verbose_name

    @property
    def model(self):
        return self.model_class


class ActiveDirectory(models.Model):
    url = models.CharField(max_length=300)
    domain = models.CharField(max_length=200)
    ou = models.CharField(max_length=200)
    username = models.CharField(max_length=80)
    password = models.CharField(max_length=1000)

    @property
    def full_url(self):
        return 'ldap://%s' % self.url

    @property
    def dn(self):
        params = ['DC=%s' % component for component in self.url.split('.')]
        params.insert(0, 'cn=Users')
        params.insert(0, 'cn=%s' % self.username)
        return ','.join(params)

    def make_session(self):
        return Session(self.full_url, self.dn, self.password)

    def find_company(self):
        session = self.make_session()
        try:
            query_results = Company.search(session, query='(ou=%s)' % self.ou)
            return query_results[0]
        except IndexError:
            return None

    def find_user(self, username):
        try:<commit_msg>Changed protocol to LDAPS TelekomLabs-DCO-1.1-Signed-off-by: <NAME> <<EMAIL>> (github: ElmoVanKielmo)<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import importlib
import datetime

from django.conf import settings
from django.db import models
from django.db import transaction
from django.db.models.signals import post_save
from django.core.exceptions import ValidationError
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.template.defaultfilters import slugify
from model_utils import Choices
from model_utils.fields import StatusField
from model_utils.models import TimeStampedModel
from model_utils.managers import InheritanceManager, QueryManager

from litedesk.lib.active_directory.session import Session
from litedesk.lib.active_directory.classes.base import Company, User as ActiveDirectoryUser
from audit.models import Trackable, UntrackableChangeError
from syncremote.models import Synchronizable

import tasks

log = logging.getLogger(__name__)


if not hasattr(settings, 'PROVISIONABLE_SERVICES'):
    settings.PROVISIONABLE_SERVICES = []


class ServiceMeta(object):
    def __init__(self, class_path_string):
        module_name, class_name = class_path_string.rsplit('.', 1)
        module = importlib.import_module(module_name)
        klass = getattr(module, class_name)
        self.model_class = klass
        self.meta = klass._meta

    @property
    def slug(self):
        return self.model_class.service_slug()

    @property
    def name(self):
        return self.meta.verbose_name

    @property
    def model(self):
        return self.model_class


class ActiveDirectory(models.Model):
    url = models.CharField(max_length=300)
    domain = models.CharField(max_length=200)
    ou = models.CharField(max_length=200)
    username = models.CharField(max_length=80)
    password = models.CharField(max_length=1000)

    @property
    def full_url(self):
        return 'ldaps://%s' % self.url

    @property
    def dn(self):
        params = ['DC=%s' % component for component in self.url.split('.')]
        params.insert(0, 'cn=Users')
        params.insert(0, 'cn=%s' % self.username)
        return ','.join(params)

    def make_session(self):
        return Session(self.full_url, self.dn, self.password)

    def find_company(self):
        session = self.make_session()
        try:
            query_results = Company.search(session, query='(ou=%s)' % self.ou)
            return query_results[0]
        except IndexError:
            return None

    def find_user(self, username):
        try:
{'fraction_non_alphanumeric': 0.08803857520609737, 'fraction_numerical': 0.009021620780836834, 'mean_word_length': 3.7383935151068535, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, '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': '6235757', 'n_tokens_mistral': 1871, 'n_tokens_neox': 1801, 'n_words': 539}