aboutsummaryrefslogtreecommitdiff
path: root/lib/d2/config/__init__.py
blob: 98fecfb4a2fd3c8c9e4aa985d81ca65c8056e5aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import os
import sys
import ldap
import logging
import logging.handlers
from collections import namedtuple
from dodai import Configure
from d2 import db, util
try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict


class LdapConnector(object):

    VERSION_DEFAULT = 2
    ARGS = ['con', 'base_dn']

    def __init__(self):
        self._make_tuple = namedtuple('D2Ldap', self.ARGS)

    def __call__(self, sections):
        if 'ldap' in sections:
            self._set_certfile(sections)
            con = self._initialize(sections)
            self._set_version(sections, con)
            self._bind(sections, con)
            return self._make_tuple(con, sections['ldap']['base_dn'])

    def _set_certfile(self, sections):
        if 'certfile' in sections['ldap']:
            certfile = util.expand_path(sections['ldap']['certfile'])
            if os.path.exists(certfile):
                ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, certfile)

    def _initialize(self, sections):
        con = ldap.initialize(sections['ldap']['server'])
        con.set_option(ldap.OPT_X_TLS_DEMAND, True)
        con.set_option(ldap.OPT_REFERRALS, 0)
        return con

    def _set_version(self, sections, con):
        if 'version' in sections['ldap'] and \
                sections['ldap']['version']:
            try:
                version = int(sections['ldap']['version'])
            except ValueError:
                pass
            else:
                if version >= ldap.VERSION_MIN and version <= ldap.VERSION_MAX:
                    con.protocol_version = version
        con.protocol_version = self.VERSION_DEFAULT

    def _bind(self, sections, con):
        try:
             # Bind with username and password
             con.bind_s(sections['ldap']['username'],
                        sections['ldap']['password'])
        except ldap.INVALID_CREDENTIALS:
            print "Your username or password is incorrect."
            sys.exit()
        except ldap.LDAPError, e:
            if type(e.message) == dict and e.message.has_key('desc'):
                print e.message['desc']
            else:
                print e

class Config(object):

    def __init__(self, project, configure, ldap_connector):
        self.project = project
        self._configure = configure(self.project)
        self._ldap_connector = ldap_connector
        self._program_ = None
        self._sections_ = None
        self._db_ = None
        self._ldap_ = None
        self._log_ = None

    @property
    def program(self):
        if not self._program_:
            self._program_ = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        return self._program_

    @property
    def sections(self):
        if not self._sections_:
            sections = self._configure.files.load()
            self._sections_ = OrderedDict()
            for section, data in sections.items():
                self._sections_[section] = OrderedDict()
                for key, value in data.items():
                    self._sections_[section][key] = value
        return self._sections_

    @property
    def db(self):
        if not self._db_:
            self._configure.databases.add(self.sections)
            self._db_ = self._configure.databases.load('db')
            # Set the schema on the db objects if any exist
            if ('schema' in self.sections['db'] and
                    self.sections['db']['schema']):
                for name, obj in db.Base.metadata.tables.items():
                    setattr(obj, 'schema', self.sections['db']['schema'])
        return self._db_

    @property
    def ldap(self):
        if not self._ldap_:
            self._ldap_ = self._ldap_connector(self.sections)
        return self._ldap_

    @property
    def data_directory(self):
        return self.sections['directories']['data']

    @property
    def template_directory(self):
        return self.sections['web_server']['template_directory']

    @property
    def port(self):
        return int(self.sections['web_server']['port'])

    @property
    def static_directory(self):
        return self.sections['web_server']['static_directory']

    @property
    def index_directory(self):
        return self.sections['directories']['index']

    @property
    def log(self):
        if not self._log_:
            self._configure.logs.set_log_level(
                        self.sections['log']['level'])
            self._log_ = self._configure.logs.load(self.program)
            self._configure.logs.attach_file_handler(self._log_,
                        self.sections['log']['log_file'])
            self._configure.logs.attach_screen_handler(self._log_)
        return self._log_

    @classmethod
    def load(cls, project='d2', configure=None, ldap_connector=None):
        configure = configure or Configure
        ldap_connector = ldap_connector or LdapConnector()
        return cls(project, configure, ldap_connector)