def decorated_func(*args, **kws):
            if 'Authorization' in request.headers:
                header_key = 'Authorization'
            else:
                abort(401)
            data = str(request.headers[header_key])

            if not data.startswith('Basic'):
                raise ValidationException("Basic authorization required")

            coded_string = str.replace(str(data), 'Basic ', '')
            decoded = base64.b64decode(coded_string).decode('utf-8')
            string_split = decoded.split(':')
            if len(string_split) < 2:
                msg = ("Basic auth must be base-64 "
                       "encoded in 'lockId:password' format")
                raise AuthorizationException(msg)

            lock_id, secret = string_split[0], ':'.join(string_split[1:])
            try:
                secret_hashed = DB.child("Locks").child(
                    lock_id).get().val().get('secret')
            except BaseException:
                raise AuthorizationException("Lock could not be found")

            if not security_utils.check_password(secret, secret_hashed):
                raise AuthorizationException("Invalid secret supplied")
            return f(lock_id, *args, **kws)
Example #2
0
def _get_password_from_db(lock_id, password_id):
    passwords = get_lock(lock_id).get('passwords', {})

    for pw_id, found_password in passwords.items():
        if pw_id == password_id:
            return found_password
    raise ValidationException(
        "Password id could not be found belonging to the lock id")
Example #3
0
 def _deserialize(self, value, attr, obj, **kwargs):
     message = "Invalid value for {}. Make sure it is one of {}".format(
         value, self.values
     )
     try:
         return self.klass(value)
     except Exception:
         raise ValidationException(message)
Example #4
0
 def validate_active_days(type, active_days):
     validation_error_template = (
         "Active days should be an empty list for password type {}")
     if type == PasswordType.OTP \
             and active_days is not None \
             and len(active_days) > 0:
         raise ValidationException(
             validation_error_template.format(type.value))
def verify_password(lock_id, input_password: Optional[str]) -> Password:
    if input_password is None:
        raise ValidationException("A password must be supplied")

    passwords_list = _get_sorted_passwords(lock_id)

    for password in passwords_list:
        if check_password(input_password, password.hashed_password):
            return password
    raise AuthorizationException("Invalid or inactive password supplied")
Example #6
0
def update_password(lock_id: str, password_id: str,
                    update_request: Dict[str, str]) -> PasswordMetadata:
    if len(update_request.keys()) == 0:
        raise ValidationException("Fields to update weren't supplied")
    password = get_password(lock_id, password_id)
    password.update(update_request)

    DB.child("Locks").child(lock_id).child("passwords").child(
        password_id).update(password.serialize())
    return get_password_metadata(lock_id, password_id)
 def wrapper(*args, **kwargs):
     request_form = request.form.to_dict()
     if len(request_form) == 0 and request.get_json() and len(
             request.get_json()) > 0:
         request_form = request.get_json()
     is_valid = all(f in request_form for f in required_fields)
     if not is_valid:
         raise ValidationException(
             "Missing arguments, required fields: {}".format(
                 required_fields, ))
     return function(request_form, **kwargs)
Example #8
0
def _cached_get(ticker: str) -> List[dict]:
    try:
        data = client.get_ticker_price(ticker=ticker,
                                       fmt="json",
                                       frequency=settings.RESAMPLE_FREQUENCY,
                                       startDate=str(date.fromtimestamp(0)),
                                       endDate=str(date.today()))
        return data
    except RestClientError as e:
        response = e.args[0].response
        if response.headers['Content-Type'] == 'application/json':
            json_body = json.loads(response.text)
            if 'not found' in (details := json_body['detail']):
                raise ValidationException(message=details) from e
            else:
                raise
        def wrapper(*args, **kwargs):
            try:
                result, code = function(*args, **kwargs)
                marshaled_result = marshal(result, resp_parser.resource_fields)

                missing_fields = [
                    req for req in resp_parser.required
                    if (req not in marshaled_result
                        or marshaled_result[req] is None)
                ]
                if len(missing_fields) > 0:
                    raise ValidationException(
                        "Response is missing required field(s): {}".format(
                            missing_fields))
                return marshaled_result, code
            except AppException as e:
                return e.to_dict(), e.status_code
Example #10
0
def create_or_update_user_lock(uid, user_locks, should_overwrite=False):
    invalid_ids = []
    for lock_id in user_locks.owned_lock_ids:
        if DB.child("Locks").child(lock_id).get().val() is None:
            invalid_ids.append(lock_id)

    if len(invalid_ids) > 0:
        raise ValidationException("Invalid lock ids: {}".format(invalid_ids))

    if not should_overwrite:
        user_lock_entry = DB.child("UserLocks").child(uid).get().val()
        prev_locks = user_lock_entry.get(
            'ownedLockIds') if user_lock_entry else []

        combined_locks = list(set(prev_locks).union(user_locks.owned_lock_ids))
        user_locks.owned_lock_ids = combined_locks
    DB.child("UserLocks").child(uid).set(user_locks.serialize())
    return user_locks.serialize()
Example #11
0
def validate_mandatory(data):
    """Takes an object of required fields and ensures none of the values
    are null.

    Args:
        data (obj): An object of mandatory fields and their provided values.

    Raises:
        ValidationException: If any of the supplied fields are null.

    """
    missing_params = []
    for key, value in data.items():
        if not value or value == '':
            missing_params.append(key)
    if missing_params:
        raise ValidationException(
            MISSING_PARAMETERS_ERROR_MSG.format(
                params=", ".join(missing_params)))
def validate_boolean_param(param):
    if not type(param) is bool:
        raise ExceptionUtils.handle_param_exception(ValidationException(ParamsError.INVALID_TYPE.value.format(
            'Boolean type expected', bool)))
Example #13
0
 def validate_expiration(type, expiration):
     if type == PasswordType.OTP \
             and expiration is not None \
             and expiration != -1:
         raise ValidationException(
             "OTP passwords should not have an expiration specified")
Example #14
0
 def _deserialize(self, value, attr, obj, **kwargs):
     try:
         return timezone(value)
     except Exception as e:
         raise ValidationException("Invalid timezone: {}".format(value))
def validate_date_param(param):
    if datetime.fromisoformat(param).date() < datetime.now().date():
        raise ExceptionUtils.handle_param_exception(ValidationException(ParamsError.INVALID_VALUE.value.format(
            'Date value must be equal or greater than the current date')))
def validate_none_value(param):
    if not type(param) is bool:
        raise ExceptionUtils.handle_param_exception(ValidationException(ParamsError.INVALID_TYPE.value.format(
            'The requires_login field must be boolean', bool)))
def validate_text_param(param):
    if len(param) < 3 or param is None:
        raise ExceptionUtils.handle_param_exception(ValidationException(ParamsError.INVALID_VALUE.value.format(
            'Text value must be greater than 3 characters')))