def _validate(self, validator, object_to_validate): if not object_to_validate: raise ValidationException("Empty request data") request_data = validator.normalized(object_to_validate) if not validator.validate(object_to_validate) and validator.errors: raise ValidationException(validator.errors) return request_data
def validate(self, partial=False, strict=False): super(Tap, self).validate(partial, strict) if not self.user.is_friend(self.tapped_id): raise ValidationException('Not friends') if Configuration.ENVIRONMENT != 'dev' and self.user.is_tapped( self.tapped_id): raise ValidationException('Already tapped')
def validate(self) -> None: if self.xml_count <= 0: raise ValidationException( 'xml-count arg must be greater 0', 'xml_count_failed' ) if self.zip_count <= 0: raise ValidationException( 'zip-count arg must be greater 0', 'zip_count_failed' )
def validate(self, partial=False, strict=False): super(Invite, self).validate(partial, strict) inviter = self.user invited = self.invited event = self.event if not inviter.is_friend(invited): raise ValidationException('Not friend') if not inviter.is_attending(event): raise ValidationException('Must be attending the event')
def validate_end_date(end_date): try: timezone.datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S") except ValueError: message = 'The end_date param must be a valid date in ' message += 'the format YYYY-MM-DD HH:MM:SS' raise ValidationException(_(message), )
def validate_serial_number(serial_number): try: EnergyTransductor.objects.get(serial_number=serial_number) except EnergyTransductor.DoesNotExist: raise ValidationException( _('This serial_number does not match with any Transductor'), )
def prepare_request_data(self, request): if request.data: return json.loads(request.data) elif request.form: return request.form.to_dict() else: raise ValidationException("Empty request")
def validate(self, partial=False, strict=False): super(Friend, self).validate(partial, strict) if self.user_id == self.friend_id: raise ValidationException('Cannot friend yourself') if Configuration.ENVIRONMENT != 'dev' and self.user.is_friend( self.friend): raise ValidationException('Already friends') if self.friend.is_blocked(self.user): raise ValidationException('Blocked') if not self.accepted and self.friend.is_friend_request_sent( self.user_id): self.accepted = True
def account_verification(access_token): url = 'https://kapi.kakao.com/v1/user/access_token_info' header = {'Authorization': 'Bearer ' + access_token} # status code 400 = Validation Error, 401 code = Token Expiration # response has uid, expiresInMillis, appId response = requests.get(url, headers=header) response_dict = response.json() if response.status_code == 400: raise ValidationException('Accout Verification Validation Error') elif response.status_code == 401: raise ValidationException('Token Expiration') # if signup: # response_dict = KaKaoTalk.get_account_info(access_token) return response_dict
def create(self, validated_data): access_token = validated_data.get('access_token', None) provider = validated_data.get('provider', None) email = validated_data.get('email', None) email_verified = validated_data.get('email_verified', None) print(validated_data) if email is None: raise ValidationException('Email Address is Missing') if provider == 'KT': if email_verified is None: raise ValidationException('Email Verified is Missing') user_verified_token = KaKaoTalk.account_verification(access_token) user_object, _ = StellarUser.objects.get_or_create(email=email) social_object, _ = SocialAccount.objects.get_or_create(uid=user_verified_token['id'], email=email, provider=provider, defaults={'user': user_object, 'email_verified': email_verified if email_verified is not None else False, 'access_token': access_token}) elif provider == 'FB': # I need debug_token response data response_dict = FaceBook.account_verification(access_token) user_object, _ = StellarUser.objects.get_or_create(email=email) social_object, _ = SocialAccount.objects.get_or_create(uid=response_dict['data']['user_id'], email=email, provider=provider, defaults={'user': user_object, 'email_verified': email_verified if email_verified is not None else False, 'access_token': access_token}) else: ValidationException('Not Allowed Providers') if social_object.access_token != access_token: social_object.access_token = access_token social_object.save() return social_object
def run(self): self.initialize_starting_board() king_killed = False while not king_killed: field_chosen, destination = None, None self.show_board() current_player = self.get_current_player() valid_piece_chosen = False while not valid_piece_chosen: print( f"{current_player.get_name()}'s move. Choose a piece to move" ) field_chosen = current_player.choose_a_piece_to_move() valid_piece_chosen = self.get_board().validate_piece_choice( field_chosen, current_player) if valid_piece_chosen: piece_chosen = self.get_board().get_piece_from_square( field_chosen[0], field_chosen[1]) print("You chose to move: " + str(piece_chosen) + " from " + str(field_chosen)) possible_moves = self.get_possible_moves( piece_chosen, field_chosen) if not possible_moves: print("You cannot move this piece!") valid_piece_chosen = False else: print("Possible moves: " + str(possible_moves)) valid_destination_chosen = False while not valid_destination_chosen: try: destination = current_player.choose_a_destination() if destination in possible_moves: valid_destination_chosen = True else: raise ValidationException() except ValidationException: print("Not a valid choice.") continue king_killed, color_loosing = self.get_board().check_is_king_alive( destination) self.get_board().execute_move(field_chosen, destination, piece_chosen) self.check_both_mates(destination) self.check_promotion() self.show_board() for player in self.players: if player.get_color() == color_loosing: looser = player print( f"{looser.get_name()}'s king was killed, {looser} lost the game!")
def check_ticket_patch_logic(self, ticket_id, status, cursor): cursor.execute(self.queries.get_ticket_by_id, (ticket_id, )) ticket = cursor.fetchone() if not ticket: raise IndexError origin_status = ticket["status"] if origin_status == "closed": raise ValidationException( "Mailformed status, you are not aloowed to modify clodes tickets" ) if origin_status == "open": if status not in ["responded", "closed"]: raise ValidationException( "Mailformed status, allowed: {0}".format( ["responsed", "closed"])) elif origin_status == "responsed": if status not in ["waiting_for_response", "closed"]: raise ValidationException( "Mailformed status, allowed: {0}".format( ["waiting_for_response", "closed"])) else: raise InternalServerError( "Unexpected status change: {0}".format(status))
def account_verification(access_token): url = 'https://graph.facebook.com/debug_token' param = { 'input_token': access_token, 'access_token': settings.CONF_FILE['FACEBOOK']['APP_ACCESS_TOKEN'] } response = requests.get(url, params=param) response_dict = response.json() is_valid = response_dict['data']['is_valid'] if not is_valid: raise ValidationException('Invalid Access Token') return response_dict
def post_comment(self, request): data = self.validator.validate_comment_post_schema( self.prepare_request_data(request)) with get_db_cursor(commit=True) as cursor: try: cursor.execute(self.queries.create_comment, data) except IntegrityError: raise ValidationException( "You are not allowed create comments for closed tickets") comment = cursor.fetchone() self.set_to_cache( "ticket_{0}".format(comment["ticket_id"]), self.get_ticket_with_comments(comment["ticket_id"], cursor), ) return json.dumps(comment, default=self.datetime_converter), 201
def validate(self) -> None: if not self.path.is_dir(): raise ValidationException(f'Path: {self.path} is not directory', 'path_failed')
def validate(self, partial=False, strict=False): super(Block, self).validate(partial, strict) if self.user.is_blocked(self.blocked): raise ValidationException('Already blocked')
def validate(self, partial=False, strict=False): super(Message, self).validate(partial, strict) if not self.user.is_friend(self.to_user_id): raise ValidationException('Not friends')
def setup_request(): g.user = None g.group = None if is_request_secure( ) and request.environ.get('wsgi.url_scheme') != 'https': request.environ['wsgi.url_scheme'] = 'https' if request.path.startswith('/api/swagger') or request.path.startswith( '/admin'): agent.ignore_transaction() api_key = request.headers.get('X-Wigo-API-Key') if not api_key and 'key' in request.args: request.args = request.args.copy() api_key = request.args.pop('key') if api_key: g.api_key = api_key api_version = request.headers.get('X-Wigo-API-Version') if not api_version: api_version = '1000000000.0.0' try: g.api_version = Version(api_version) except: raise ValidationException('Invalid version number', 'X-Wigo-API-Version') # check api key auth if request.path.startswith('/api/hooks/'): # webhooks do their own auth pass elif request.path.startswith('/api/swagger'): pass elif request.path.startswith('/api') and api_key != app.config['API_KEY']: abort(403, message='Bad API key') # resolve by lat/long geolocation = request.headers.get('Geolocation') if geolocation: parsed_geo = urlparse(geolocation) if parsed_geo.scheme == 'geo': lat, lon = parsed_geo.path.split(',') lat, lon = float(lat), float(lon) if lat and lon: g.latitude, g.longitude = float(lat), float(lon) try: g.group = Group.find(lat=g.latitude, lon=g.longitude) except DoesNotExist: logger.info( 'could not resolve group from geo, lat={}, lon={}'. format(g.latitude, g.longitude)) city_id = request.headers.get('X-Wigo-City-ID') if city_id: g.group = Group.find(city_id=int(city_id)) group_id = request.headers.get('X-Wigo-Group-ID') if group_id: g.group = Group.find(int(group_id)) # setup the user after the geo lookup, since the user might need to update its group setup_user_by_token()
def validate(self, partial=False, strict=False): super(EventMessage, self).validate(partial, strict) if self.is_new and not self.user.is_attending(self.event): raise ValidationException('Not attending event')
def validate(self, partial=False, strict=False): super(EventAttendee, self).validate(partial, strict) if not self.user.can_see_event(self.event): raise ValidationException('Not invited')