/usr/lib/python2.7/dist-packages/twext/who/directory.py is in calendarserver 5.2+dfsg-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | # -*- test-case-name: twext.who.test.test_directory -*-
##
# Copyright (c) 2006-2014 Apple Inc. All rights reserved.
#
# 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.
##
"""
Generic directory service base implementation
"""
__all__ = [
"DirectoryService",
"DirectoryRecord",
]
from uuid import UUID
from zope.interface import implementer
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet.defer import succeed, fail
from twext.who.idirectory import QueryNotSupportedError, NotAllowedError
from twext.who.idirectory import FieldName, RecordType
from twext.who.idirectory import Operand
from twext.who.idirectory import IDirectoryService, IDirectoryRecord
from twext.who.expression import MatchExpression
from twext.who.util import uniqueResult, describe
@implementer(IDirectoryService)
class DirectoryService(object):
"""
Generic implementation of L{IDirectoryService}.
This is a complete implementation of L{IDirectoryService}, with support for
the query operands in L{Operand}.
The C{recordsWith*} methods are all implemented in terms of
L{recordsWithFieldValue}, which is in turn implemented in terms of
L{recordsFromExpression}.
L{recordsFromQuery} is also implemented in terms of
{recordsFromExpression}.
L{recordsFromExpression} (and therefore most uses of the other methods)
will always fail with a L{QueryNotSupportedError}.
A subclass should therefore override L{recordsFromExpression} with an
implementation that handles any queries that it can support and its
superclass' implementation with any query it cannot support.
A subclass may override L{recordsFromQuery} if it is to support additional
operands.
L{updateRecords} and L{removeRecords} will fail with L{NotAllowedError}
when asked to modify data.
A subclass should override these methods if is to allow editing of
directory information.
@cvar recordType: a L{Names} class or compatible object (eg.
L{ConstantsContainer}) which contains the L{NamedConstant}s denoting
the record types that are supported by this directory service.
@cvar fieldName: a L{Names} class or compatible object (eg.
L{ConstantsContainer}) which contains the L{NamedConstant}s denoting
the record field names that are supported by this directory service.
@cvar normalizedFields: a L{dict} mapping of (ie. L{NamedConstant}s
contained in the C{fieldName} class variable) to callables that take
a field value (a L{unicode}) and return a normalized field value (also
a L{unicode}).
"""
recordType = RecordType
fieldName = FieldName
normalizedFields = {
FieldName.guid: lambda g: UUID(g).hex,
FieldName.emailAddresses: lambda e: bytes(e).lower(),
}
def __init__(self, realmName):
"""
@param realmName: a realm name
@type realmName: unicode
"""
self.realmName = realmName
def __repr__(self):
return (
"<{self.__class__.__name__} {self.realmName!r}>"
.format(self=self)
)
def recordTypes(self):
return self.recordType.iterconstants()
def recordsFromExpression(self, expression, records=None):
"""
Finds records matching a single expression.
@note: The implementation in L{DirectoryService} always raises
L{QueryNotSupportedError}.
@note: This L{DirectoryService} adds a C{records} keyword argument to
the interface defined by L{IDirectoryService}.
This allows the implementation of
L{DirectoryService.recordsFromQuery} to narrow the scope of records
being searched as it applies expressions.
This is therefore relevant to subclasses, which need to support the
added parameter, but not to users of L{IDirectoryService}.
@param expression: an expression to apply
@type expression: L{object}
@param records: a set of records to limit the search to. C{None} if
the whole directory should be searched.
@type records: L{set} or L{frozenset}
@return: The matching records.
@rtype: deferred iterable of L{IDirectoryRecord}s
@raises: L{QueryNotSupportedError} if the expression is not
supported by this directory service.
"""
return fail(QueryNotSupportedError(
"Unknown expression: {0}".format(expression)
))
@inlineCallbacks
def recordsFromQuery(self, expressions, operand=Operand.AND):
expressionIterator = iter(expressions)
try:
expression = expressionIterator.next()
except StopIteration:
returnValue(())
results = set((yield self.recordsFromExpression(expression)))
for expression in expressions:
if operand == Operand.AND:
if not results:
# No need to bother continuing here
returnValue(())
records = results
else:
records = None
recordsMatchingExpression = frozenset((
yield self.recordsFromExpression(expression, records=records)
))
if operand == Operand.AND:
results &= recordsMatchingExpression
elif operand == Operand.OR:
results |= recordsMatchingExpression
else:
raise QueryNotSupportedError(
"Unknown operand: {0}".format(operand)
)
returnValue(results)
def recordsWithFieldValue(self, fieldName, value):
return self.recordsFromExpression(MatchExpression(fieldName, value))
@inlineCallbacks
def recordWithUID(self, uid):
returnValue(uniqueResult(
(yield self.recordsWithFieldValue(FieldName.uid, uid))
))
@inlineCallbacks
def recordWithGUID(self, guid):
returnValue(uniqueResult(
(yield self.recordsWithFieldValue(FieldName.guid, guid))
))
def recordsWithRecordType(self, recordType):
return self.recordsWithFieldValue(FieldName.recordType, recordType)
@inlineCallbacks
def recordWithShortName(self, recordType, shortName):
returnValue(uniqueResult((yield self.recordsFromQuery((
MatchExpression(FieldName.recordType, recordType),
MatchExpression(FieldName.shortNames, shortName),
)))))
def recordsWithEmailAddress(self, emailAddress):
return self.recordsWithFieldValue(
FieldName.emailAddresses,
emailAddress,
)
def updateRecords(self, records, create=False):
for record in records:
return fail(NotAllowedError("Record updates not allowed."))
return succeed(None)
def removeRecords(self, uids):
for uid in uids:
return fail(NotAllowedError("Record removal not allowed."))
return succeed(None)
@implementer(IDirectoryRecord)
class DirectoryRecord(object):
"""
Generic implementation of L{IDirectoryService}.
This is an incomplete implementation of L{IDirectoryRecord}.
L{groups} will always fail with L{NotImplementedError} and L{members} will
do so if this is a group record.
A subclass should override these methods to support group membership and
complete this implementation.
@cvar requiredFields: an iterable of field names that must be present in
all directory records.
"""
requiredFields = (
FieldName.uid,
FieldName.recordType,
FieldName.shortNames,
)
def __init__(self, service, fields):
for fieldName in self.requiredFields:
if fieldName not in fields or not fields[fieldName]:
raise ValueError("{0} field is required.".format(fieldName))
if FieldName.isMultiValue(fieldName):
values = fields[fieldName]
if len(values) == 0:
raise ValueError(
"{0} field must have at least one value."
.format(fieldName)
)
for value in values:
if not value:
raise ValueError(
"{0} field must not be empty.".format(fieldName)
)
if (
fields[FieldName.recordType] not in
service.recordType.iterconstants()
):
raise ValueError(
"Record type must be one of {0!r}, not {1!r}.".format(
tuple(service.recordType.iterconstants()),
fields[FieldName.recordType],
)
)
# Normalize fields
normalizedFields = {}
for name, value in fields.items():
normalize = service.normalizedFields.get(name, None)
if normalize is None:
normalizedFields[name] = value
continue
if FieldName.isMultiValue(name):
normalizedFields[name] = tuple((normalize(v) for v in value))
else:
normalizedFields[name] = normalize(value)
self.service = service
self.fields = normalizedFields
def __repr__(self):
return (
"<{self.__class__.__name__} ({recordType}){shortName}>".format(
self=self,
recordType=describe(self.recordType),
shortName=self.shortNames[0],
)
)
def __eq__(self, other):
if IDirectoryRecord.implementedBy(other.__class__):
return (
self.service == other.service and
self.fields == other.fields
)
return NotImplemented
def __ne__(self, other):
eq = self.__eq__(other)
if eq is NotImplemented:
return NotImplemented
return not eq
def __getattr__(self, name):
try:
fieldName = self.service.fieldName.lookupByName(name)
except ValueError:
raise AttributeError(name)
try:
return self.fields[fieldName]
except KeyError:
raise AttributeError(name)
def description(self):
description = [self.__class__.__name__, ":"]
for name, value in self.fields.items():
if hasattr(name, "description"):
name = name.description
else:
name = str(name)
if hasattr(value, "description"):
value = value.description
else:
value = str(value)
description.append("\n ")
description.append(name)
description.append(" = ")
description.append(value)
return "".join(description)
def members(self):
if self.recordType == RecordType.group:
return fail(
NotImplementedError("Subclasses must implement members()")
)
return succeed(())
def groups(self):
return fail(NotImplementedError("Subclasses must implement groups()"))
|