Ejemplo n.º 1
0
 def perform_create(self, serializer):
     object_uuid = str(uuid1())
     if self.request.data.get('about_type') == "mission" \
             or 'mission' in self.request.path:
         about = Mission.get(self.kwargs[self.lookup_field])
         quest = Quest.get(about.owner_username)
         url = reverse('mission_updates',
                       kwargs={
                           'object_uuid': self.kwargs[self.lookup_field],
                           'slug': slugify(about.get_mission_title())
                       },
                       request=self.request)
     else:
         # If all else fails assume this update is about the Quest itself
         quest = Quest.get(self.kwargs[self.lookup_field])
         # TODO update quest url generation when we have an updates for
         # quest
         url = None
         about = quest
     serializer.save(quest=quest,
                     about=about,
                     url=url,
                     object_uuid=object_uuid,
                     href=reverse('update-detail',
                                  kwargs={'object_uuid': object_uuid},
                                  request=self.request))
Ejemplo n.º 2
0
    def list(self, request, *args, **kwargs):
        """
        Currently we limit this endpoint to only be accessible to
        owners/accountants of campaigns, this is because it displays all
        donations not just the completed ones. We will eventually want to add
        some functionality to this that will allow people who are not the
        owner/accountant of the campaign to view all completed donations.

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        if "mission" in self.request.path:
            moderators = Mission.get(
                object_uuid=self.kwargs[self.lookup_field])
        else:
            moderators = Quest.get(
                owner_username=self.kwargs[self.lookup_field])
        if not (request.user.username in moderators.get_moderators(
                moderators.owner_username)):
            return Response(
                {
                    "status_code": status.HTTP_403_FORBIDDEN,
                    "detail": "You are not authorized to access "
                    "this page."
                },
                status=status.HTTP_403_FORBIDDEN)
        return super(DonationListCreate, self).list(request, *args, **kwargs)
Ejemplo n.º 3
0
 def create(self, request, *args, **kwargs):
     if self.request.data.get('about_type') == "mission":
         mission = Mission.get(self.kwargs[self.lookup_field])
         quest = Quest.get(mission.owner_username)
         if quest is None:
             return Response(
                 {
                     "status_code":
                     status.HTTP_404_NOT_FOUND,
                     "detail":
                     "Sorry we couldn't find the Quest you were "
                     "attempting to create an update for."
                 },
                 status=status.HTTP_404_NOT_FOUND)
         if quest.owner_username == request.user.username:
             return super(UpdateListCreate,
                          self).create(request, *args, **kwargs)
     if request.user.username not in \
             Quest.get_quest_helpers(self.kwargs[self.lookup_field]):
         return Response(
             {
                 "status_code": status.HTTP_403_FORBIDDEN,
                 "detail": "You are not authorized to access "
                 "this page."
             },
             status=status.HTTP_403_FORBIDDEN)
     return super(UpdateListCreate, self).create(request, *args, **kwargs)
Ejemplo n.º 4
0
def mission_account_signup(request):
    try:
        quest = Quest.get(owner_username=request.user.username)
    except (Mission.DoesNotExist, DoesNotExist):
        return redirect("404_Error")
    except (CypherException, ClientError, IOError):  # pragma: no cover
        return redirect("500_Error")

    return render(request, 'mission/account_setup.html', {"quest": quest})
Ejemplo n.º 5
0
 def get_quest(self, obj):
     request, expand, _, _, _ = gather_request_data(
         self.context, expand_param=self.context.get('expand', None))
     try:
         quest = Quest.get(owner_username=obj.username)
     except(Quest.DoesNotExist, DoesNotExist):
         return None
     if expand == 'true' and quest is not None:
         return QuestSerializer(quest, context={'request': request}).data
     return quest.owner_username
Ejemplo n.º 6
0
 def get_about(self, obj):
     from sb_missions.neo_models import Mission
     from sb_missions.serializers import MissionSerializer
     from sb_quests.neo_models import Quest
     from sb_quests.serializers import QuestSerializer
     if obj.about_type == "mission":
         return MissionSerializer(Mission.get(obj.about_id)).data
     elif obj.about_type == "quest":
         return QuestSerializer(Quest.get(obj.about_id)).data
     else:
         return None
Ejemplo n.º 7
0
 def get_moderators(cls, owner_username):
     from sb_quests.neo_models import Quest
     quest = Quest.get(owner_username)
     moderators = cache.get("%s_moderators" % quest.owner_username)
     if moderators is None:
         query = 'MATCH (quest:Quest {owner_username: "******"})<-' \
                 '[:MODERATOR_OF]-(pleb:Pleb) ' \
                 'RETURN pleb.username' % owner_username
         res, col = db.cypher_query(query)
         moderators = [row[0] for row in res]
         cache.set("%s_moderators" % quest.owner_username, moderators)
     return moderators
Ejemplo n.º 8
0
def get_search_html(request, object_uuid):
    try:
        quest = Quest.get(object_uuid)
    except (CypherException, IOError):
        return Response('Server Error', status=500)
    rendered_html = render_to_string(
        "saga_search_block.html",
        QuestSerializer(quest, context={
            'request': request
        }).data)

    return Response({'html': rendered_html}, status=200)
Ejemplo n.º 9
0
 def perform_create(self, serializer):
     donor = Pleb.get(self.request.user.username)
     if "/v1/missions/" in self.request.path:
         mission = Mission.get(object_uuid=self.kwargs[self.lookup_field])
         quest = Mission.get_quest(
             object_uuid=self.kwargs[self.lookup_field])
     else:
         mission = None
         quest = Quest.get(owner_username=self.kwargs[self.lookup_field])
     serializer.save(mission=mission,
                     donor=donor,
                     quest=quest,
                     owner_username=donor.username)
Ejemplo n.º 10
0
 def get_total_donation_amount(self):
     from sb_quests.neo_models import Quest
     quest = Quest.get(owner_username=self.owner_username)
     query = 'MATCH (c:Mission {object_uuid:"%s"})<-' \
             '[:CONTRIBUTED_TO]-(d:Donation) ' \
             'RETURN sum(d.amount) - (sum(d.amount) * ' \
             '(%f + %f) + count(d) * 30)' \
             % (self.object_uuid, quest.application_fee,
                settings.STRIPE_TRANSACTION_PERCENT)
     res, _ = db.cypher_query(query)
     if res.one:
         return '{:,.2f}'.format(float(res.one) / 100)
     else:
         return "0.00"
Ejemplo n.º 11
0
    def get(self, request, object_uuid=None, slug=None):
        try:
            mission_obj = Mission.get(object_uuid)
        except (Mission.DoesNotExist, DoesNotExist):
            return redirect("404_Error")
        except (CypherException, ClientError, IOError):
            return redirect("500_Error")
        mission_dict = MissionSerializer(mission_obj,
                                         context={
                                             'request': request
                                         }).data

        return render(
            request, self.template_name, {
                "mission":
                mission_dict,
                "quest":
                QuestSerializer(Quest.get(mission_obj.owner_username)).data
            })
Ejemplo n.º 12
0
def quest(request, username):
    try:
        quest_obj = Quest.get(owner_username=username)
    except (CypherException, IOError, Quest.DoesNotExist, DoesNotExist):
        return redirect("404_Error")
    return redirect('profile_page', pleb_username=quest_obj.owner_username)
Ejemplo n.º 13
0
 def get_quest(cls, object_uuid):
     from sb_quests.neo_models import Quest
     return Quest.get(owner_username=Mission.get(
         object_uuid=object_uuid).owner_username)
Ejemplo n.º 14
0
def js_settings(request):
    data = {
        'api': {
            'google_maps': environ.get('GOOGLE_MAPS_JS'),
            'stripe': settings.STRIPE_PUBLIC_KEY,
            'liveaddress': settings.ADDRESS_AUTH_ID,
            'stripe_transaction_fee': settings.STRIPE_TRANSACTION_PERCENT
        },
        'google_maps': environ.get('GOOGLE_MAPS_JS'),
        'user': {},
        'static_url': settings.STATIC_URL,
        "default_profile_pic": static('images/sage_coffee_grey-01.png'),
        'version': environ.get("SHA1", ""),
        'quest_promo_key': settings.PROMOTION_KEYS[0],
        'url_regex': settings.URL_REGEX
    }
    try:
        if request.user.is_authenticated():
            data['user']['type'] = "auth"
            data['user']['username'] = request.user.username
            try:
                pleb = Pleb.get(request.user.username)
                data['profile'] = PlebSerializerNeo(pleb,
                                                    context={
                                                        "request": request,
                                                        "expand": True
                                                    }).data
                # Private not available in the serializer
                data['profile']['stripe_account'] = pleb.stripe_account
                data['profile']['stripe_customer_id'] = pleb.stripe_account
                if data['profile']['quest'] is not None:
                    quest = Quest.get(pleb.username)
                    data['profile']['quest'] = QuestSerializer(quest).data
                    if "/quests/%s/" % quest.owner_username in request.path or \
                            "/quests/%s/" % quest.object_uuid in request.path:
                        data['profile']['quest']['is_owner'] = True
                    data['profile']['quest']['available_missions'] = False
                    if quest.account_type == "free":
                        data['profile']['quest']['free_quest'] = True
                        if len(quest.missions) >= settings.FREE_MISSIONS:
                            data['profile']['quest'][
                                'available_missions'] = True
                    stripe.api_key = settings.STRIPE_SECRET_KEY
                    stripe.api_version = settings.STRIPE_API_VERSION
                    if "quest" in request.path:
                        # If we're in a place where we're telling the user
                        # that their quest is inactive lets indicate that the
                        # quest has a card on file so they can activate
                        if quest.stripe_default_card_id is not None:
                            data['profile']['quest']['card_on_file'] = True
                        else:
                            data['profile']['quest']['card_on_file'] = False
                        data['profile']['quest'][
                            'account_type'] = quest.account_type
                    if "quest" in request.path and "billing" in request.path:
                        # Private not available in the serializer
                        data['profile']['quest']['card'] = None
                        data['profile']['quest']['subscription'] = None
                        if quest.stripe_customer_id:
                            customer = stripe.Customer.retrieve(
                                quest.stripe_customer_id)
                            if quest.stripe_default_card_id:
                                credit_card = customer.sources.retrieve(
                                    quest.stripe_default_card_id)
                                data['profile']['quest']['card'] = {
                                    "brand": credit_card['brand'],
                                    "last4": credit_card['last4'],
                                    "exp_month": credit_card['exp_month'],
                                    "exp_year": credit_card['exp_year']
                                }
                            if quest.stripe_subscription_id is not None:
                                subscription = customer.subscriptions.retrieve(
                                    quest.stripe_subscription_id)

                                data['profile']['quest']['subscription'] = {
                                    "current_period_end":
                                    subscription['current_period_end'],
                                    "current_period_start":
                                    subscription['current_period_start'],
                                    "amount":
                                    subscription['plan']['amount']
                                }
            except (CypherException, IOError, Pleb.DoesNotExist, DoesNotExist):
                data['profile'] = None
        else:
            data['user']['type'] = "anon"

    except AttributeError:
        data['user']['type'] = "anon"

    js_settings_output = "var SB_APP_SETTINGS = "
    js_settings_output += json.dumps(data)
    js_settings_output += ";"

    return {
        'js_settings': js_settings_output,
    }
Ejemplo n.º 15
0
    def update(self, instance, validated_data):
        """
        Only profile_pic and wallpaper_pic are allowed to be updated using
        this endpoint. This is because any other editing of the pleb
        that occurs should also update the user so use v1/users/
        to update anything else in the pleb.

        :param instance:
        :param validated_data:
        :return:
        """
        stripe.api_key = settings.STRIPE_SECRET_KEY
        stripe.api_version = settings.STRIPE_API_VERSION
        request, _, _, _, _ = gather_request_data(self.context)
        address = request.data.get('address')
        if address is not None:
            address_serializer = AddressSerializer(
                data=address, context={"request": request})
            address_serializer.is_valid(raise_exception=True)
            address = address_serializer.save()
            query = 'MATCH (a:Pleb) ' \
                    'OPTIONAL MATCH (a)-[r:LIVES_IN]-(:Address) ' \
                    'DELETE r'
            res, _ = db.cypher_query(query)
            instance.address.connect(address)
            instance.determine_reps()

        update_time = request.data.get('update_time', False)
        first_name = validated_data.get('first_name', instance.first_name)
        last_name = validated_data.get('last_name', instance.last_name)
        customer_token = validated_data.pop('customer_token',
                                            instance.customer_token)
        email = validated_data.get('email', instance.email).lower()
        user_obj = User.objects.get(username=instance.username)
        if first_name != user_obj.first_name:
            instance.first_name = first_name
            user_obj.first_name = first_name
        if last_name != user_obj.last_name:
            instance.last_name = last_name
            user_obj.last_name = last_name
        if email != user_obj.email:
            instance.email = email.lower().strip()
            user_obj.email = email.lower().strip()
            if instance.get_quest():
                quest = Quest.get(instance.username, cache_buster=True)
                if quest.stripe_customer_id:
                    customer = \
                        stripe.Customer.retrieve(quest.stripe_customer_id)
                    customer.email = email.lower().strip()
                    customer.save()
        if user_obj.check_password(validated_data.get('password', "")) is True:
            user_obj.set_password(validated_data.get(
                'new_password', validated_data.get('password', "")))
            update_session_auth_hash(self.context.get('request'), user_obj)
        user_obj.save()
        profile_pic = validated_data.get('profile_pic')
        if profile_pic is not None and profile_pic != "":
            instance.profile_pic = validated_data.get('profile_pic',
                                                      instance.profile_pic)
        wallpaper_pic = validated_data.get('wallpaper_pic')
        if wallpaper_pic is not None and wallpaper_pic != "":
            instance.wallpaper_pic = validated_data.get('wallpaper_pic',
                                                        instance.wallpaper_pic)
        instance.occupation_name = validated_data.get('occupation_name',
                                                      instance.occupation_name)
        instance.employer_name = validated_data.get('employer_name',
                                                    instance.employer_name)
        instance.reputation_update_seen = validated_data.get(
            'reputation_update_seen', instance.reputation_update_seen)
        if customer_token is not None:
            # Customers must provide a credit card for us to create a customer
            # with stripe. Get the credit card # and create a customer instance
            # so we can charge it in the future.
            if instance.stripe_customer_id is None:
                try:
                    customer = stripe.Customer.create(
                        description="Customer %s" % instance.username,
                        card=customer_token,
                        email=instance.email.lower().strip()
                    )
                    instance.stripe_customer_id = customer['id']
                    instance.stripe_default_card_id = customer[
                        'sources']['data'][0]['id']
                except stripe.error.CardError as e:
                    body = e.json_body
                    err = body['error']
                    logger.exception("Stripe Card Creation Error ")
                    logger.critical(err)
                    raise serializers.ValidationError(
                        "We were unable to store your card's information")
            else:
                customer = stripe.Customer.retrieve(
                    instance.stripe_customer_id)
                card = customer.sources.create(source=customer_token)
                instance.stripe_default_card_id = card['id']
        instance.stripe_default_card_id = validated_data.get(
            'stripe_default_card_id', instance.stripe_default_card_id)
        if update_time:
            instance.last_counted_vote_node = instance.vote_from_last_refresh

        instance.save()
        instance.update_quest()
        cache.delete(instance.username)
        return super(PlebSerializerNeo, self).update(instance, validated_data)
Ejemplo n.º 16
0
 def test_get_not_cached(self):
     cache.delete("%s_quest" % self.owner.username)
     res = Quest.get(self.owner.username)
     self.assertEqual(self.quest.owner_username, res.owner_username)
Ejemplo n.º 17
0
 def test_get_cached(self):
     cache.set("%s_quest" % self.owner.username, self.quest)
     res = Quest.get(self.owner.username)
     self.assertEqual(self.quest, res)