def has_permission(self, request, view): if request.method in SAFE_METHODS: return True try: token = get_token_from_request(request) r = AuthRequester() _, is_superuser = r.is_superuser(token) return is_superuser except BaseApiRequestError: return False
def validate_created_by(self, value): if value: return value r = AuthRequester() token = get_token_from_request(self.context['request']) try: _, auth_json = r.get_user_info(token) return auth_json['id'] except BaseApiRequestError: raise serializers.ValidationError( 'Не получается найти user_id по токену, попробуйте позже')
def update_rating(self, request: Request, d_rating: int, auth_json: dict): try: _, token_json = AuthRequester().app_get_token(settings.APP_ID, settings.APP_SECRET) token = token_json['access'] _, user_json = UsersRequester().change_rating(user_id=auth_json['id'], drating=d_rating, app_token=token) return user_json except BaseApiRequestError as e: return
def get_user_info(self, request): token = get_token_from_request(request) try: _, auth_json = AuthRequester().get_user_info(token) except BaseApiRequestError: return Response({'error': 'Проблемы с сервисом авторизации, попробуйте позже'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return auth_json
def get_is_accepted_by_me(self, instance: Place): try: _, user_json = AuthRequester().get_user_info( get_token_from_request(self.context['request'])) return Accept.objects.filter(place_id=instance.id, created_by=user_json['id']).exists() except (KeyError, BaseApiRequestError): return False
def get_my_rating(self, instance: Place): try: _, user_json = AuthRequester().get_user_info( get_token_from_request(self.context['request'])) return Rating.objects.get(place_id=instance.id, created_by=user_json['id']).rating except (KeyError, Rating.DoesNotExist, BaseApiRequestError): return 0
def get_queryset(self): lookup_fields = {} with_deleted = self.request.query_params.get('with_deleted', 'False') with_deleted = with_deleted.lower() == 'true' all_ = Place.objects.with_deleted() if with_deleted else Place.objects only_mine = self.request.query_params.get('only_mine', 'False') only_mine = only_mine.lower() == 'true' if only_mine: r = AuthRequester() token = get_token_from_request(self.request) try: _, auth_json = r.get_user_info(token) lookup_fields['created_by'] = auth_json['id'] except BaseApiRequestError: raise ValidationError( 'Не получается получить юзера по токену, попробуйте позже') name = self.request.query_params.get('name', None) if name: lookup_fields['name__contains'] = name latitude_1 = self.request.query_params.get('lat1', None) longitude_1 = self.request.query_params.get('long1', None) latitude_2 = self.request.query_params.get('lat2', None) longitude_2 = self.request.query_params.get('long2', None) llll = (latitude_1, latitude_2, longitude_1, longitude_2) if all(llll): try: lookup_fields['latitude__gte'] = min(float(latitude_1), float(latitude_2)) lookup_fields['longitude__gte'] = min(float(longitude_1), float(longitude_2)) lookup_fields['latitude__lte'] = max(float(latitude_1), float(latitude_2)) lookup_fields['longitude__lte'] = max(float(longitude_1), float(longitude_2)) except (ValueError, TypeError): raise ValidationError( 'Для фильтрации по сектору карты параметры должны быть числами' ) elif len(list(filter(lambda x: x is not None, llll))) != 0: raise ValidationError( 'Для фильтрации по сектору карты нужны 4 координаты') return all_.filter(**lookup_fields)
def buy_pin(self, request, auth_json): token = get_token_from_request(request) try: _, app_token = AuthRequester().app_get_token(settings.APP_ID, settings.APP_SECRET) _, pin_json = AwardsRequester().get_pin(**request.data, token=token) _, user_json = UsersRequester().buy_pin(pin_id=pin_json['id'], user_id=auth_json['id'], price=pin_json['price'], app_token=app_token['access']) return user_json except TypeError as e: return Response({'error': 'Неправильный формат JSON'}, status=status.HTTP_400_BAD_REQUEST) except UnexpectedResponse as e: return Response(e.body, status=e.code) except BaseApiRequestError: return Response({'error': 'Проблемы с сервисом мест, попробуйте позже'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def add_achievement(self, request: Request, achievement_id: int, auth_json: dict): """ 1 -- создание профиля 2 -- Добавление места 3 -- Оставил рейтинг 4 -- Подтвердил существование 5 -- Удалил существование 6 -- Купил пин """ try: _, token_json = AuthRequester().app_get_token(settings.APP_ID, settings.APP_SECRET) token = token_json['access'] _, user_json = UsersRequester().add_achievement(user_id=auth_json['id'], achievement_id=achievement_id, app_token=token) return user_json except (BaseApiRequestError, UnexpectedResponse): return