Esempio n. 1
0
def github_logout(request):
    """Handle Github logout."""
    access_token = request.session.pop('access_token', '')
    handle = request.session.pop('handle', '')
    redirect_uri = request.GET.get('redirect_uri', '/')
    geolocation_data = {}
    ip_address = '24.210.224.38' if settings.DEBUG else get_real_ip(request)

    if ip_address:
        geolocation_data = get_location_from_ip(ip_address)

    if access_token:
        revoke_token(access_token)
        request.session.pop('access_token_last_validated')

    try:
        # If the profile exists, clear the github access token.
        profile = Profile.objects.get(handle=handle)
        profile.github_access_token = ''
        profile.save()

        # record a useraction for this
        UserAction.objects.create(profile=profile,
                                  action='Logout',
                                  metadata={},
                                  ip_address=ip_address,
                                  location_data=geolocation_data)
    except Profile.DoesNotExist:
        pass

    request.session.modified = True
    response = redirect(redirect_uri)
    response.set_cookie('last_github_auth_mutation', int(time.time()))
    return response
Esempio n. 2
0
def github_callback(request):
    """Handle the Github authentication callback."""
    # Get request parameters to handle authentication and the redirect.
    code = request.GET.get('code', None)
    redirect_uri = request.GET.get('redirect_uri')

    if not code or not redirect_uri:
        raise Http404

    # Get OAuth token and github user data.
    access_token = get_github_user_token(code)
    github_user_data = get_github_user_data(access_token)
    handle = github_user_data.get('login')
    ip_address = '24.210.224.38' if settings.DEBUG else get_real_ip(request)
    geolocation_data = {}

    if ip_address:
        geolocation_data = get_location_from_ip(ip_address)

    if handle:
        # Create or update the Profile with the github user data.
        user_profile, _ = Profile.objects.update_or_create(
            handle=handle,
            defaults={
                'data': github_user_data or {},
                'email': get_github_primary_email(access_token),
                'github_access_token': access_token
            })

        # Update the user's session with handle and email info.
        session_data = {
            'handle': user_profile.handle,
            'email': user_profile.email,
            'access_token': user_profile.github_access_token,
            'profile_id': user_profile.pk,
            'name': user_profile.data.get('name', None),
            'access_token_last_validated': timezone.now().isoformat(),
        }
        for k, v in session_data.items():
            request.session[k] = v

        # record a useraction for this
        UserAction.objects.create(profile=user_profile,
                                  action='Login',
                                  metadata={},
                                  ip_address=ip_address,
                                  location_data=geolocation_data)

    response = redirect(redirect_uri)
    response.set_cookie('last_github_auth_mutation', int(time.time()))
    return response
Esempio n. 3
0
def preprocess(request):
    """Handle inserting pertinent data into the current context."""

    # make lbcheck super lightweight
    if request.path == '/lbcheck':
        return {}

    chat_url = get_chat_url(front_end=True)
    chat_access_token = ''
    chat_id = ''

    user_is_authenticated = request.user.is_authenticated
    profile = request.user.profile if user_is_authenticated and hasattr(
        request.user, 'profile') else None
    if user_is_authenticated and profile and profile.pk:
        # what actions to take?
        record_join = not profile.last_visit
        record_visit = not profile.last_visit or profile.last_visit < (
            timezone.now() -
            timezone.timedelta(seconds=RECORD_VISIT_EVERY_N_SECONDS))
        if record_visit:
            try:
                profile.last_visit = timezone.now()
                profile.save()
            except Exception as e:
                logger.exception(e)
            try:
                from dashboard.tasks import profile_dict
                profile_dict.delay(profile.pk)
            except Exception as e:
                logger.exception(e)
            metadata = {
                'useragent': request.META['HTTP_USER_AGENT'],
                'referrer': request.META.get('HTTP_REFERER', None),
                'path': request.META.get('PATH_INFO', None),
            }
            ip_address = get_ip(request)
            UserAction.objects.create(
                user=request.user,
                profile=profile,
                action='Visit',
                location_data=get_location_from_ip(ip_address),
                ip_address=ip_address,
                utm=_get_utm_from_cookie(request),
                metadata=metadata,
            )

        if record_join:
            Activity.objects.create(profile=profile, activity_type='joined')

        chat_access_token = profile.gitcoin_chat_access_token
        chat_id = profile.chat_id
    # handles marketing callbacks
    if request.GET.get('cb'):
        callback = request.GET.get('cb')
        handle_marketing_callback(callback, request)

    header_msg, footer_msg, nav_salt = get_sitewide_announcements()

    context = {
        'STATIC_URL':
        settings.STATIC_URL,
        'MEDIA_URL':
        settings.MEDIA_URL,
        'chat_url':
        chat_url,
        'chat_id':
        chat_id,
        'chat_access_token':
        chat_access_token,
        'github_handle':
        request.user.username.lower() if user_is_authenticated else False,
        'email':
        request.user.email if user_is_authenticated else False,
        'name':
        request.user.get_full_name() if user_is_authenticated else False,
        'last_chat_status':
        request.user.profile.last_chat_status if
        (hasattr(request.user, 'profile')
         and user_is_authenticated) else False,
        'raven_js_version':
        settings.RAVEN_JS_VERSION,
        'raven_js_dsn':
        settings.SENTRY_JS_DSN,
        'release':
        settings.RELEASE,
        'env':
        settings.ENV,
        'header_msg':
        header_msg,
        'nav_salt':
        nav_salt,
        'footer_msg':
        footer_msg,
        'INFURA_V3_PROJECT_ID':
        settings.INFURA_V3_PROJECT_ID,
        'giphy_key':
        settings.GIPHY_KEY,
        'youtube_key':
        settings.YOUTUBE_API_KEY,
        'orgs':
        profile.organizations if profile else [],
        'profile_id':
        profile.id if profile else '',
        'hotjar':
        settings.HOTJAR_CONFIG,
        'ipfs_config': {
            'host': settings.JS_IPFS_HOST,
            'port': settings.IPFS_API_PORT,
            'protocol': settings.IPFS_API_SCHEME,
            'root': settings.IPFS_API_ROOT,
        },
        'chat_persistence_frequency':
        90 * 1000,
        'access_token':
        profile.access_token if profile else '',
        'is_staff':
        request.user.is_staff if user_is_authenticated else False,
        'is_moderator':
        profile.is_moderator if profile else False,
        'is_alpha_tester':
        profile.is_alpha_tester if profile else False,
        'persona_is_funder':
        profile.persona_is_funder if profile else False,
        'persona_is_hunter':
        profile.persona_is_hunter if profile else False,
        'profile_url':
        profile.url if profile else False,
        'quests_live':
        settings.QUESTS_LIVE,
    }
    context['json_context'] = json.dumps(context)
    context['last_posts'] = cache.get_or_set('last_posts', fetchPost, 5000)

    if context['github_handle']:
        context['unclaimed_tips'] = Tip.objects.filter(
            receive_txid='',
            username__iexact=context['github_handle'],
            web3_type='v3',
        ).send_happy_path().cache(timeout=60)
        context['unclaimed_kudos'] = KudosTransfer.objects.filter(
            receive_txid='',
            username__iexact="@" + context['github_handle'],
            web3_type='v3',
        ).send_happy_path().cache(timeout=60)

        if not settings.DEBUG:
            context['unclaimed_tips'] = context['unclaimed_tips'].filter(
                network='mainnet').cache(timeout=60)
            context['unclaimed_kudos'] = context['unclaimed_kudos'].filter(
                network='mainnet').cache(timeout=60)

    return context
Esempio n. 4
0
def preprocess(request):
    """Handle inserting pertinent data into the current context."""

    # make lbcheck super lightweight
    if request.path == '/lbcheck':
        return {}

    from marketing.utils import get_stat
    try:
        num_slack = int(get_stat('slack_users'))
    except Exception:
        num_slack = 0
    if num_slack > 1000:
        num_slack = f'{str(round((num_slack) / 1000, 1))}k'

    user_is_authenticated = request.user.is_authenticated
    profile = request.user.profile if user_is_authenticated and hasattr(
        request.user, 'profile') else None
    email_subs = profile.email_subscriptions if profile else None
    email_key = email_subs.first(
    ).priv if user_is_authenticated and email_subs and email_subs.exists(
    ) else ''
    if user_is_authenticated and profile and profile.pk:
        # what actions to take?
        record_join = not profile.last_visit
        record_visit = not profile.last_visit or profile.last_visit < (
            timezone.now() -
            timezone.timedelta(seconds=RECORD_VISIT_EVERY_N_SECONDS))
        if record_visit:
            ip_address = get_ip(request)
            profile.last_visit = timezone.now()
            try:
                profile.as_dict = json.loads(json.dumps(profile.to_dict()))
                profile.save()
            except Exception as e:
                logger.exception(e)
            metadata = {
                'useragent': request.META['HTTP_USER_AGENT'],
                'referrer': request.META.get('HTTP_REFERER', None),
                'path': request.META.get('PATH_INFO', None),
            }
            UserAction.objects.create(
                user=request.user,
                profile=profile,
                action='Visit',
                location_data=get_location_from_ip(ip_address),
                ip_address=ip_address,
                utm=_get_utm_from_cookie(request),
                metadata=metadata,
            )

        if record_join:
            Activity.objects.create(profile=profile, activity_type='joined')

    # handles marketing callbacks
    if request.GET.get('cb'):
        callback = request.GET.get('cb')
        handle_marketing_callback(callback, request)

    chat_unread_messages = False

    if profile and profile.chat_id:
        try:
            from chat.tasks import get_driver
            chat_driver = get_driver()

            chat_unreads_request = chat_driver.teams.get_team_unreads_for_user(
                profile.chat_id)

            if 'message' not in chat_unreads_request:
                for teams in chat_unreads_request:
                    if teams['msg_count'] > 0 or teams['mention_count'] > 0:
                        chat_unread_messages = True
                        break
        except Exception as e:
            logger.error(str(e))

    context = {
        'STATIC_URL': settings.STATIC_URL,
        'MEDIA_URL': settings.MEDIA_URL,
        'num_slack': num_slack,
        'chat_unread_messages': chat_unread_messages,
        'github_handle':
        request.user.username if user_is_authenticated else False,
        'email': request.user.email if user_is_authenticated else False,
        'name':
        request.user.get_full_name() if user_is_authenticated else False,
        'raven_js_version': settings.RAVEN_JS_VERSION,
        'raven_js_dsn': settings.SENTRY_JS_DSN,
        'release': settings.RELEASE,
        'env': settings.ENV,
        'INFURA_V3_PROJECT_ID': settings.INFURA_V3_PROJECT_ID,
        'email_key': email_key,
        'orgs': profile.organizations if profile else [],
        'profile_id': profile.id if profile else '',
        'hotjar': settings.HOTJAR_CONFIG,
        'ipfs_config': {
            'host': settings.JS_IPFS_HOST,
            'port': settings.IPFS_API_PORT,
            'protocol': settings.IPFS_API_SCHEME,
            'root': settings.IPFS_API_ROOT,
        },
        'access_token': profile.access_token if profile else '',
        'is_staff': request.user.is_staff if user_is_authenticated else False,
        'is_moderator': profile.is_moderator if profile else False,
        'persona_is_funder': profile.persona_is_funder if profile else False,
        'persona_is_hunter': profile.persona_is_hunter if profile else False,
        'profile_url': profile.url if profile else False,
        'quests_live': settings.QUESTS_LIVE,
    }
    context['json_context'] = json.dumps(context)

    if context['github_handle']:
        context['unclaimed_tips'] = Tip.objects.filter(
            expires_date__gte=timezone.now(),
            receive_txid='',
            username__iexact=context['github_handle'],
            web3_type='v3',
        ).send_happy_path()
        context['unclaimed_kudos'] = KudosTransfer.objects.filter(
            receive_txid='',
            username__iexact="@" + context['github_handle'],
            web3_type='v3',
        ).send_happy_path()

        if not settings.DEBUG:
            context['unclaimed_tips'] = context['unclaimed_tips'].filter(
                network='mainnet')
            context['unclaimed_kudos'] = context['unclaimed_kudos'].filter(
                network='mainnet')

    return context
Esempio n. 5
0
def record_visit(self,
                 user_pk,
                 profile_pk,
                 ip_address,
                 visitorId,
                 useragent,
                 referrer,
                 path,
                 session_key,
                 utm,
                 retry: bool = True) -> None:
    """
    :param self: Self
    :param user_pk: user primary
    :param profile_pk: profile primary
    :param ip_address: get_ip(request)
    :param visitorId: request.COOKIES.get("visitorId", None)
    :param useragent: request.META['HTTP_USER_AGENT']
    :param referrer: request.META.get('HTTP_REFERER', None)
    :param path: request.META.get('PATH_INFO', None)
    :param session_key: request.session._session_key
    :param utm: _get_utm_from_cookie(request)
    :return: None
    """

    user = User.objects.filter(pk=user_pk).first() if user_pk else None
    profile = Profile.objects.filter(
        pk=profile_pk).first() if profile_pk else None
    if user and profile:
        try:
            profile.last_visit = timezone.now()
            profile.save()
        except Exception as e:
            logger.exception(e)

        # enqueue profile_dict recalc
        profile_dict.delay(profile.pk)

        try:
            metadata = {
                'visitorId': visitorId,
                'useragent': useragent,
                'referrer': referrer,
                'path': path,
                'session_key': session_key,
            }
            UserAction.objects.create(
                user=user,
                profile=profile,
                action='Visit',
                location_data=get_location_from_ip(ip_address),
                ip_address=ip_address,
                utm=utm,
                metadata=metadata,
            )

            # if the user is from a bad jurisdiction, block themm.
            # or is named after an entity that is banned, block them
            from dashboard.utils import should_be_blocked
            if should_be_blocked(profile.handle):
                from dashboard.models import BlockedUser
                BlockedUser.objects.create(
                    handle=profile.handle,
                    comments='should_be_blocked',
                    active=True,
                    user=user,
                )
        except Exception as e:
            logger.exception(e)
Esempio n. 6
0
def preprocess(request):
    """Handle inserting pertinent data into the current context."""

    # make lbcheck super lightweight
    if request.path == '/lbcheck':
        return {}

    from marketing.utils import get_stat
    try:
        num_slack = int(get_stat('slack_users'))
    except Exception:
        num_slack = 0
    if num_slack > 1000:
        num_slack = f'{str(round((num_slack) / 1000, 1))}k'

    user_is_authenticated = request.user.is_authenticated
    profile = request.user.profile if user_is_authenticated and hasattr(request.user, 'profile') else None
    email_subs = profile.email_subscriptions if profile else None
    email_key = email_subs.first().priv if user_is_authenticated and email_subs and email_subs.exists() else ''
    if user_is_authenticated and profile and profile.pk:
        record_visit = not profile.last_visit or profile.last_visit < (
            timezone.now() - timezone.timedelta(seconds=RECORD_VISIT_EVERY_N_SECONDS)
        )
        if record_visit:
            ip_address = get_ip(request)
            profile.last_visit = timezone.now()
            profile.save()
            UserAction.objects.create(
                user=request.user,
                profile=profile,
                action='Visit',
                location_data=get_location_from_ip(ip_address),
                ip_address=ip_address,
                utm=_get_utm_from_cookie(request),
            )
    context = {
        'STATIC_URL': settings.STATIC_URL,
        'MEDIA_URL': settings.MEDIA_URL,
        'num_slack': num_slack,
        'github_handle': request.user.username if user_is_authenticated else False,
        'email': request.user.email if user_is_authenticated else False,
        'name': request.user.get_full_name() if user_is_authenticated else False,
        'sentry_address': settings.SENTRY_ADDRESS,
        'raven_js_version': settings.RAVEN_JS_VERSION,
        'raven_js_dsn': settings.SENTRY_JS_DSN,
        'release': settings.RELEASE,
        'env': settings.ENV,
        'email_key': email_key,
        'profile_id': profile.id if profile else '',
        'hotjar': settings.HOTJAR_CONFIG,
        'ipfs_config': {
            'host': settings.JS_IPFS_HOST,
            'port': settings.IPFS_API_PORT,
            'protocol': settings.IPFS_API_SCHEME,
            'root': settings.IPFS_API_ROOT,
        },
        'access_token': profile.access_token if profile else '',
        'is_staff': request.user.is_staff if user_is_authenticated else False,
        'is_moderator': profile.is_moderator if profile else False,
    }
    context['json_context'] = json.dumps(context)

    if context['github_handle']:
        context['unclaimed_tips'] = Tip.objects.filter(
            expires_date__gte=timezone.now(),
            receive_txid='',
            username__iexact=context['github_handle'],
            web3_type='v3',
        ).send_happy_path()
        context['unclaimed_kudos'] = KudosTransfer.objects.filter(
            receive_txid='', username__iexact="@" + context['github_handle'], web3_type='v3',
        ).send_happy_path()

        if not settings.DEBUG:
            context['unclaimed_tips'] = context['unclaimed_tips'].filter(network='mainnet')
            context['unclaimed_kudos'] = context['unclaimed_kudos'].filter(network='mainnet')

    return context
Esempio n. 7
0
def preprocess(request):
    """Handle inserting pertinent data into the current context."""

    # make lbcheck super lightweight

    if request.path == '/lbcheck':
        return {}

    ptoken = None

    search_url = ''
    user_is_authenticated = request.user.is_authenticated
    profile = request.user.profile if user_is_authenticated and hasattr(
        request.user, 'profile') else None
    if user_is_authenticated and profile and profile.pk:
        # what actions to take?
        record_join = not profile.last_visit
        record_visit = not profile.last_visit or profile.last_visit < (
            timezone.now() -
            timezone.timedelta(seconds=RECORD_VISIT_EVERY_N_SECONDS))
        if record_visit:
            try:
                profile.last_visit = timezone.now()
                profile.save()
            except Exception as e:
                logger.exception(e)
            try:
                from dashboard.tasks import profile_dict
                profile_dict.delay(profile.pk)
            except Exception as e:
                logger.exception(e)
            metadata = {
                'visitorId': request.COOKIES.get("visitorId", None),
                'useragent': request.META['HTTP_USER_AGENT'],
                'referrer': request.META.get('HTTP_REFERER', None),
                'path': request.META.get('PATH_INFO', None),
                'session_key': request.session._session_key,
            }
            ip_address = get_ip(request)
            UserAction.objects.create(
                user=request.user,
                profile=profile,
                action='Visit',
                location_data=get_location_from_ip(ip_address),
                ip_address=ip_address,
                utm=_get_utm_from_cookie(request),
                metadata=metadata,
            )

        if record_join:
            Activity.objects.create(profile=profile, activity_type='joined')

        ptoken = PersonalToken.objects.filter(
            token_owner_profile=profile).first()

    # Check if user's location supports pTokens
    try:
        current_location = profile.locations[-1]
        is_location_blocked_for_ptokens = current_location['country_code'] == settings.PTOKEN_BLOCKED_REGION['country_code'] \
            and current_location['region'] == settings.PTOKEN_BLOCKED_REGION['region']
    except:
        # If user is not logged in
        is_location_blocked_for_ptokens = False

    # handles marketing callbacks
    if request.GET.get('cb'):
        callback = request.GET.get('cb')
        handle_marketing_callback(callback, request)

    header_msg, footer_msg, nav_salt = get_sitewide_announcements()

    try:
        onboard_tasks = JSONStore.objects.get(key='onboard_tasks').data
    except JSONStore.DoesNotExist:
        onboard_tasks = []

    # town square wall post max length
    max_length_offset = abs(
        ((request.user.profile.created_on if hasattr(request.user, 'profile')
          and request.user.is_authenticated else timezone.now()) -
         timezone.now()).days)
    max_length = 600 + max_length_offset

    context = {
        'STATIC_URL':
        settings.STATIC_URL,
        'MEDIA_URL':
        settings.MEDIA_URL,
        'max_length':
        max_length,
        'max_length_offset':
        max_length_offset,
        'search_url':
        f'{settings.BASE_URL}user_lookup',
        'base_url':
        settings.BASE_URL,
        'github_handle':
        request.user.username.lower() if user_is_authenticated else False,
        'email':
        request.user.email if user_is_authenticated else False,
        'name':
        request.user.get_full_name() if user_is_authenticated else False,
        'raven_js_version':
        settings.RAVEN_JS_VERSION,
        'raven_js_dsn':
        settings.SENTRY_JS_DSN,
        'release':
        settings.RELEASE,
        'env':
        settings.ENV,
        'header_msg':
        header_msg,
        'nav_salt':
        nav_salt,
        'footer_msg':
        footer_msg,
        'INFURA_V3_PROJECT_ID':
        settings.INFURA_V3_PROJECT_ID,
        'giphy_key':
        settings.GIPHY_KEY,
        'youtube_key':
        settings.YOUTUBE_API_KEY,
        'fortmatic_live_key':
        settings.FORTMATIC_LIVE_KEY,
        'fortmatic_test_key':
        settings.FORTMATIC_TEST_KEY,
        'orgs':
        profile.organizations if profile else [],
        'profile_id':
        profile.id if profile else '',
        'is_pro':
        profile.is_pro if profile else False,
        'hotjar':
        settings.HOTJAR_CONFIG,
        'ipfs_config': {
            'host': settings.JS_IPFS_HOST,
            'port': settings.IPFS_API_PORT,
            'protocol': settings.IPFS_API_SCHEME,
            'root': settings.IPFS_API_ROOT,
        },
        'access_token':
        profile.access_token if profile else '',
        'is_staff':
        request.user.is_staff if user_is_authenticated else False,
        'is_moderator':
        profile.is_moderator if profile else False,
        'is_alpha_tester':
        profile.is_alpha_tester if profile else False,
        'user_groups':
        list(profile.user_groups) if profile else False,
        'persona_is_funder':
        profile.persona_is_funder if profile else False,
        'persona_is_hunter':
        profile.persona_is_hunter if profile else False,
        'pref_do_not_track':
        profile.pref_do_not_track if profile else False,
        'profile_url':
        profile.url if profile else False,
        'quests_live':
        settings.QUESTS_LIVE,
        'onboard_tasks':
        onboard_tasks,
        'ptoken_abi':
        settings.PTOKEN_ABI,
        'ptoken_factory_address':
        settings.PTOKEN_FACTORY_ADDRESS,
        'ptoken_factory_abi':
        settings.PTOKEN_FACTORY_ABI,
        'ptoken_address':
        ptoken.token_address if ptoken else '',
        'ptoken_id':
        ptoken.id if ptoken else None,
        'is_location_blocked_for_ptokens':
        is_location_blocked_for_ptokens,
        'match_payouts_abi':
        settings.MATCH_PAYOUTS_ABI,
        'match_payouts_address':
        settings.MATCH_PAYOUTS_ADDRESS,
        'mautic_id':
        profile.mautic_id if profile else None,
    }
    context['json_context'] = json.dumps(context)
    context['last_posts'] = cache.get_or_set('last_posts', fetchPost, 5000)

    if context['github_handle']:
        context['unclaimed_tips'] = Tip.objects.filter(
            receive_txid='',
            username__iexact=context['github_handle'],
            web3_type='v3',
        ).send_happy_path().cache(timeout=60)
        context['unclaimed_kudos'] = KudosTransfer.objects.filter(
            receive_txid='',
            username__iexact="@" + context['github_handle'],
            web3_type='v3',
        ).send_happy_path().cache(timeout=60)

        if not settings.DEBUG:
            context['unclaimed_tips'] = context['unclaimed_tips'].filter(
                network='mainnet').cache(timeout=60)
            context['unclaimed_kudos'] = context['unclaimed_kudos'].filter(
                network='mainnet').cache(timeout=60)

    return context