1 3
import uuid
2

3
# Django
4 3
from django.db import models
5 3
from django.core.exceptions import ValidationError, ObjectDoesNotExist
6 3
from django.utils.timezone import now
7

8
# Django-CRUM
9 3
from crum import get_current_user
10

11
# CyBorgBackup
12 3
from cyborgbackup.main.utils.encryption import encrypt_field
13 3
from cyborgbackup.main.utils.common import parse_yaml_or_json
14

15 3
__all__ = ['prevent_search', 'VarsDictProperty', 'BaseModel', 'CreatedModifiedModel',
16
           'PasswordFieldsModel', 'PrimordialModel', 'CommonModel',
17
           'CommonModelNameNotUnique', 'NotificationFieldsModel',
18
           'VERBOSITY_CHOICES']
19

20 3
VERBOSITY_CHOICES = [
21
    (0, '0 (Normal)'),
22
    (1, '1 (Verbose)'),
23
    (2, '2 (More Verbose)'),
24
    (3, '3 (Debug)'),
25
    (4, '4 (Connection Debug)'),
26
    (5, '5 (WinRM Debug)'),
27
]
28

29

30 3
class VarsDictProperty(object):
31
    '''
32
    Retrieve a string of variables in YAML or JSON as a dictionary.
33
    '''
34

35 3
    def __init__(self, field='variables', key_value=False):
36 3
        self.field = field
37 3
        self.key_value = key_value
38

39 3
    def __get__(self, obj, type=None):
40 0
        if obj is None:
41 0
            return self
42 0
        v = getattr(obj, self.field)
43 0
        if hasattr(v, 'items'):
44 0
            return v
45 0
        v = v.encode('utf-8')
46 0
        return parse_yaml_or_json(v)
47

48 3
    def __set__(self, obj, value):
49 0
        raise AttributeError('readonly property')
50

51

52 3
class BaseModel(models.Model):
53
    '''
54
    Base model class with common methods for all models.
55
    '''
56

57 3
    class Meta:
58 3
        abstract = True
59

60 3
    def __unicode__(self):
61 0
        if 'name' in self.__dict__:
62 0
            return u'%s-%s' % (self.name, self.pk)
63
        else:
64 0
            return u'%s-%s' % (self._meta.verbose_name, self.pk)
65

66 3
    def clean_fields(self, exclude=None):
67
        '''
68
        Override default clean_fields to support methods for cleaning
69
        individual model fields.
70
        '''
71 3
        exclude = exclude or []
72 3
        errors = {}
73 3
        try:
74 3
            super(BaseModel, self).clean_fields(exclude)
75 0
        except ValidationError as e:
76 0
            errors = e.update_error_dict(errors)
77 3
        for f in self._meta.fields:
78 3
            if f.name in exclude:
79 3
                continue
80 3
            if hasattr(self, 'clean_%s' % f.name):
81 0
                try:
82 0
                    setattr(self, f.name, getattr(self, 'clean_%s' % f.name)())
83 0
                except ValidationError as e:
84 0
                    errors[f.name] = e.messages
85 3
        if errors:
86 0
            raise ValidationError(errors)
87

88 3
    def update_fields(self, **kwargs):
89 0
        save = kwargs.pop('save', True)
90 0
        update_fields = []
91 0
        for field, value in kwargs.items():
92 0
            if getattr(self, field) != value:
93 0
                setattr(self, field, value)
94 0
                update_fields.append(field)
95 0
        if save and update_fields:
96 0
            self.save(update_fields=update_fields)
97 0
        return update_fields
98

99

100 3
class CreatedModifiedModel(BaseModel):
101
    '''
102
    Common model with created/modified timestamp fields.  Allows explicitly
103
    specifying created/modified timestamps in certain cases (migrations, job
104
    events), calculates automatically if not specified.
105
    '''
106

107 3
    class Meta:
108 3
        abstract = True
109

110 3
    created = models.DateTimeField(
111
        default=None,
112
        editable=False,
113
    )
114 3
    modified = models.DateTimeField(
115
        default=None,
116
        editable=False,
117
    )
118

119 3
    def save(self, *args, **kwargs):
120 3
        update_fields = kwargs.get('update_fields', [])
121
        # Manually perform auto_now_add and auto_now logic.
122 3
        if not self.pk and not self.created:
123 3
            self.created = now()
124 3
            if 'created' not in update_fields:
125 3
                update_fields.append('created')
126 3
        if 'modified' not in update_fields or not self.modified:
127 3
            self.modified = now()
128 3
            update_fields.append('modified')
129 3
        super(CreatedModifiedModel, self).save(*args, **kwargs)
130

131

132 3
class PasswordFieldsModel(BaseModel):
133
    '''
134
    Abstract base class for a model with password fields that should be stored
135
    as encrypted values.
136
    '''
137

138 3
    PASSWORD_FIELDS = ()
139

140 3
    class Meta:
141 3
        abstract = True
142

143 3
    def _password_field_allows_ask(self, field):
144 0
        return False
145

146 3
    def save(self, *args, **kwargs):
147 0
        new_instance = not bool(self.pk)
148
        # If update_fields has been specified, add our field names to it,
149
        # if it hasn't been specified, then we're just doing a normal save.
150 0
        update_fields = kwargs.get('update_fields', [])
151
        # When first saving to the database, don't store any password field
152
        # values, but instead save them until after the instance is created.
153
        # Otherwise, store encrypted values to the database.
154
        # for field in self.PASSWORD_FIELDS:
155
        #    if new_instance:
156
        #        value = getattr(self, field, '')
157
        #        setattr(self, '_saved_%s' % field, value)
158
        #        setattr(self, field, '')
159
        #    else:
160
        #        #ask = self._password_field_allows_ask(field)
161
        #        #self.encrypt_field(field, ask)
162
        #        self.mark_field_for_save(update_fields, field)
163
        # super(PasswordFieldsModel, self).save(*args, **kwargs)
164
        # After saving a new instance for the first time, set the password
165
        # fields and save again.
166 0
        if new_instance:
167 0
            update_fields = []
168 0
            for field in self.PASSWORD_FIELDS:
169 0
                saved_value = getattr(self, '_saved_%s' % field, '')
170 0
                setattr(self, field, saved_value)
171 0
                self.mark_field_for_save(update_fields, field)
172

173 0
            self.save(update_fields=update_fields)
174

175 3
    def encrypt_field(self, field, ask):
176 0
        encrypted = encrypt_field(self, field, ask)
177 0
        setattr(self, field, encrypted)
178

179 3
    def mark_field_for_save(self, update_fields, field):
180 0
        if field not in update_fields:
181 0
            update_fields.append(field)
182

183

184 3
class PrimordialModel(CreatedModifiedModel):
185
    '''
186
    Common model for all object types that have these standard fields
187
    must use a subclass CommonModel or CommonModelNameNotUnique though
188
    as this lacks a name field.
189
    '''
190

191 3
    class Meta:
192 3
        abstract = True
193

194 3
    created_by = models.ForeignKey(
195
        'main.User',
196
        related_name='%s(class)s_created+',
197
        default=None,
198
        null=True,
199
        editable=False,
200
        on_delete=models.SET_NULL,
201
    )
202 3
    modified_by = models.ForeignKey(
203
        'main.User',
204
        related_name='%s(class)s_modified+',
205
        default=None,
206
        null=True,
207
        editable=False,
208
        on_delete=models.SET_NULL,
209
    )
210 3
    uuid = models.UUIDField(
211
        max_length=36,
212
        default=uuid.uuid4,
213
        editable=False
214
    )
215

216 3
    def save(self, *args, **kwargs):
217 3
        update_fields = kwargs.get('update_fields', [])
218 3
        self.uuid = uuid.uuid4()
219 3
        if 'uuid' not in update_fields:
220 3
            update_fields.append('uuid')
221 3
        user = get_current_user()
222 3
        if user and not user.id:
223 0
            user = None
224 3
        if not self.pk and not self.created_by:
225 3
            self.created_by = user
226 3
            if 'created_by' not in update_fields:
227 3
                update_fields.append('created_by')
228 3
        self.modified_by = user
229 3
        if 'modified_by' not in update_fields:
230 3
            update_fields.append('modified_by')
231 3
        super(PrimordialModel, self).save(*args, **kwargs)
232

233 3
    def clean_description(self):
234
        # Description should always be empty string, never null.
235 0
        return self.description or ''
236

237 3
    def validate_unique(self, exclude=None):
238 3
        super(PrimordialModel, self).validate_unique(exclude=exclude)
239 3
        model = type(self)
240 3
        if not hasattr(model, 'SOFT_UNIQUE_TOGETHER'):
241 3
            return
242 0
        errors = []
243 0
        for ut in model.SOFT_UNIQUE_TOGETHER:
244 0
            kwargs = {}
245 0
            for field_name in ut:
246 0
                kwargs[field_name] = getattr(self, field_name, None)
247 0
            try:
248 0
                obj = model.objects.get(**kwargs)
249 0
            except ObjectDoesNotExist:
250 0
                continue
251 0
            if not (self.pk and self.pk == obj.pk):
252 0
                errors.append(
253
                    '%s with this (%s) combination already exists.' % (
254
                        model.__name__,
255
                        ', '.join(set(ut) - {'polymorphic_ctype'})
256
                    )
257
                )
258 0
        if errors:
259 0
            raise ValidationError(errors)
260

261

262 3
class CommonModel(PrimordialModel):
263
    ''' a base model where the name is unique '''
264

265 3
    class Meta:
266 3
        abstract = True
267

268 3
    name = models.CharField(
269
        max_length=512,
270
        unique=True,
271
    )
272

273

274 3
class CommonModelNameNotUnique(PrimordialModel):
275
    ''' a base model where the name is not unique '''
276

277 3
    class Meta:
278 3
        abstract = True
279

280 3
    name = models.CharField(
281
        max_length=512,
282
        unique=False,
283
    )
284

285

286 3
class NotificationFieldsModel(BaseModel):
287

288 3
    class Meta:
289 3
        abstract = True
290

291 3
    notification_templates_error = models.ManyToManyField(
292
        "NotificationTemplate",
293
        blank=True,
294
        related_name='%(class)s_notification_templates_for_errors'
295
    )
296

297 3
    notification_templates_success = models.ManyToManyField(
298
        "NotificationTemplate",
299
        blank=True,
300
        related_name='%(class)s_notification_templates_for_success'
301
    )
302

303 3
    notification_templates_any = models.ManyToManyField(
304
        "NotificationTemplate",
305
        blank=True,
306
        related_name='%(class)s_notification_templates_for_any'
307
    )
308

309

310 3
def prevent_search(relation):
311
    """
312
    Used to mark a model field or relation as "restricted from filtering"
313
    e.g.,
314

315
    class AuthToken(BaseModel):
316
        user = prevent_search(models.ForeignKey(...))
317
        sensitive_data = prevent_search(models.CharField(...))
318

319
    The flag set by this function is used by
320
    `awx.api.filters.FieldLookupBackend` to blacklist fields and relations that
321
    should not be searchable/filterable via search query params
322
    """
323 3
    setattr(relation, '__prevent_search__', True)
324 3
    return relation

Read our documentation on viewing source code .

Loading