def authenticate(data): """ Checks for a valid combination of ``unit_id`` and ``secret_key`` values in `data`. Also removes the ``secret_key`` for enhanced security. """ invalid = pipe | 'Authentication failed ({0}).' | InvalidRequest valid, error = validate( required('unit_id', valid_int), required('secret_key', valid_string), )(data) if not valid: raise invalid(error) unit = unless(CarUnit.DoesNotExist, CarUnit.objects.get)( unit_id=data['unit_id'], secret_key=data['secret_key'], ) if not unit: raise invalid('wrong "unit_id" and/or "secret_key"') if not unit.enabled: raise invalid('unit is disabled') return data.iteritems() > where(KEY != 'secret_key') | dict
def valid_car_id(val, field): return validate( partial(valid_int, field=field), partial(field_validator, test=lambda val: Car.objects.filter(id=val).exists(), message='{field}: Car with id "{value}" does not exist', field=field))(val)
def valid_car_id(val, field): return validate( partial(valid_int, field=field), partial(field_validator, test=lambda val: Car.objects.filter(id=val).exists(), message='{field}: Car with id "{value}" does not exist', field=field) )(val)
def test_validate_valid(self): d = 42 valid, error = validate( check(X > 20), check(X == 42), )(d) self.assertTrue(valid) self.assertFalse(error)
def test_validate_invalid(self): d = 42 valid, error = validate( check(X > 20), check(X < 30, "value should be < 24"), check(lambda: 1 / 0, "this won't happen..."), )(d) self.assertEqual(valid, False) self.assertEqual(error, "value should be < 24")
def valid_user_id(val, field): """ Validates that `val` is a valid user_id. We check in all users, not only MetrocarUsers, because maybe a service technician doesn't have to be a MetrocarUser (?). It's an easy fix if wasn't so, anyway. """ return validate( partial(valid_int, field=field), partial(field_validator, test=user_exists, message='User with id "{value}" does not exist', field=field), partial(field_validator, test=user_is_active, message='User with id "{value}" is not active', field=field), )(val)
def validate_request(rules, data): valid, error = validate(rules)(data) if not valid: raise InvalidRequest(error) return data
def test_invalid(self): data = {'some_field': []} self.assertEqual(validate( optional('some_field', valid_int), )(data), (False, '"some_field" should be an integer, not "[]"'))
def test_missing(self): data = {} self.assertEqual(validate( optional('some_field', valid_int), )(data), OK)
def test_valid(self): data = {'some_field': 3} self.assertEqual(validate( optional('some_field', valid_int), )(data), OK)
def test_missing(self): data = {} self.assertEqual(validate( required('some_field', valid_int), )(data), (False, 'missing "some_field" field'))