Example #1
0
    def handle(self, *args, **options):
        user = first(User.objects.filter(username='******')[:1])

        if user:
            user.delete()

        user = User(username='******', email='demo')
        user.set_password('demo')
        user.save()

        site = first(Site.objects.filter(identifier='demo')[:1])

        if site:
            site.delete()

        site = Site(name='Sample demo for Wham', identifier='demo', secret_key='asdf1234', url='http://example.com')
        site.save()
        site.users.add(user)
        site.save()

        for x in range(1, 10):
            email = 'user' + str(x) + '@example.com'
            authenticated_site_user = AuthenticatedSiteUser(user_id=str(x), email=email, username='******' + str(x), number_of_visits=9, number_of_sessions=9)
            authenticated_site_user.save()

            site_user = SiteUser(site=site, authenticated_site_user=authenticated_site_user, sf_user_id=Site.generate_identifier(), number_of_visits=9, number_of_sessions=9)
            site_user.save()

            for y in range(1, 10):
                created_datetime = (timezone.now() - timedelta(minutes=y + randint(1, 9)))

                visit = Visit(created=created_datetime, site_user=site_user, ip_address='127.0.0.1', user_id=str(x), email=email, username='******' + str(x), url='http://example.com/' + str(randint(44, 88)) + '.html', referrer='http://google.com/')
                visit.save()

                if y == 1:
                    site_user.first_visit = visit
                    authenticated_site_user.first_visit = visit

                    session = Session(visit=visit)
                    session.save()
                    site_user.first_session = session
                    authenticated_site_user.first_session = session
                elif y == 9:
                    site_user.last_visit = visit
                    authenticated_site_user.last_visit = visit

                    session = Session(visit=visit)
                    session.save()
                    site_user.last_session = session
                    authenticated_site_user.last_session = session

            site_user.save()
            authenticated_site_user.save()

        self.stdout.write('Demo data is loaded.')
Example #2
0
def log(request):
    wham = json.loads(request.body)
    site_identifier = wham.get("siteIdentifier", None)

    if not site_identifier:
        return {"success": False, "error_code": "missing_site_identifier"}

    site = first(Site.objects.filter(identifier=site_identifier)[:1])

    if not site:
        return {"success": False, "error_code": "invalid_site_identifier"}

    origin = request.META.get("HTTP_ORIGIN", None)

    if not origin:
        return {"success": False, "error_code": "missing_site_origin"}

    origin_domain = urlparse(origin).netloc
    site_domain = urlparse(site.url).netloc

    if not settings.DEBUG and origin_domain != site_domain:
        logger.error(
            "Invalid origin domain %s for site domain %s for site id %s" % (origin_domain, site_domain, site.id)
        )
        return {"success": False, "error_code": "invalid_site_origin"}

    # TODO: Check for encrypted user information
    # TODO: Decrypt information as necessary

    sf_user_id = wham.get("id", None)

    if not sf_user_id:
        return {"success": False, "error_code": "missing_identifier"}

    url = wham.get("url", None)
    referrer = wham.get("referrer", None)

    user_dict = wham.get("user", {})
    user_id = user_dict.get("id", None)
    email = user_dict.get("email", None)
    username = user_dict.get("username", None)

    site_user = None

    if user_id != None:
        # Get the SiteUser by user id.
        site_user = first(
            SiteUser.objects.select_related("authenticated_site_user").filter(
                site=site, authenticated_site_user__user_id=user_id
            )[:1]
        )

        if site_user:
            previous_site_user = first(
                SiteUser.objects.select_related("authenticated_site_user").filter(site=site, sf_user_id=sf_user_id)[:1]
            )

            if (
                previous_site_user
                and previous_site_user.authenticated_site_user is None
                and site_user.sf_user_id != previous_site_user.sf_user_id
            ):
                # User was previously unauthenticated, but then authenticates.
                # Associate the unauthenticated SiteUser with the authenticated user id.
                previous_site_user.authenticated_site_user = site_user.authenticated_site_user
                previous_site_user.save()
        else:
            site_user = first(
                SiteUser.objects.select_related("authenticated_site_user").filter(site=site, sf_user_id=sf_user_id)[:1]
            )

            if site_user and site_user.authenticated_site_user and site_user.authenticated_site_user.user_id != user_id:
                # User is authenticated, but user id does not match what is expected based on sf_user_id.
                # Create new AuthenticatedSiteUser and SiteUser with new sf_user_id.
                authenticated_site_user = AuthenticatedSiteUser(user_id=user_id, email=email, username=username)
                authenticated_site_user.save()

                sf_user_id = str(uuid4())
                site_user = SiteUser(site=site, sf_user_id=sf_user_id, authenticated_site_user=authenticated_site_user)
            else:
                authenticated_site_user = AuthenticatedSiteUser(user_id=user_id, email=email, username=username)
                authenticated_site_user.save()

                if not site_user:
                    site_user = SiteUser(site=site, sf_user_id=sf_user_id)

                site_user.authenticated_site_user = authenticated_site_user
    else:
        # Get the SiteUser by sf_user_id.
        site_user = first(
            SiteUser.objects.select_related("authenticated_site_user").filter(site=site, sf_user_id=sf_user_id)[:1]
        )

        if site_user and site_user.authenticated_site_user and site_user.authenticated_site_user.user_id != user_id:
            # User for the sf_user_id has been authenticated, but the user id has changed.
            # Create a new sf_user_id and SiteUser.
            sf_user_id = str(uuid4())
            site_user = SiteUser(site=site, sf_user_id=sf_user_id)

        if not site_user:
            site_user = SiteUser(site=site, sf_user_id=sf_user_id)

    site_user.save()
    visit = Visit(
        site_user=site_user,
        ip_address=_get_client_ip(request),
        user_id=user_id,
        email=email,
        username=username,
        url=url,
        referrer=referrer,
    )
    visit.save()

    authenticated_site_user = site_user.authenticated_site_user

    # Determine if this is a new session.
    if not site_user.last_visit or site_user.last_visit.created < (timezone.now() - timedelta(minutes=30)):
        session = Session(visit=visit)
        session.save()

        # Set session metadata for non-authenticated site users.
        if not site_user.first_session:
            site_user.first_session = session

        site_user.last_session = session
        site_user.number_of_sessions = site_user.number_of_sessions + 1

        # Set session metadata for authenticated site users.
        if authenticated_site_user:
            if not authenticated_site_user.first_session:
                authenticated_site_user.first_session = session
                authenticated_site_user.number_of_sessions = 1
            else:
                authenticated_site_user.number_of_sessions = authenticated_site_user.number_of_sessions + 1

            authenticated_site_user.last_session = session

    # Set visit metadata for non-authenticated site users.
    if not site_user.first_visit:
        site_user.first_visit = visit

    site_user.last_visit = visit
    site_user.number_of_visits = site_user.number_of_visits + 1
    site_user.save()

    # Set visit metadata for authenticated site users.
    if authenticated_site_user:
        if not authenticated_site_user.first_visit:
            authenticated_site_user.first_visit = visit
            authenticated_site_user.number_of_visits = 1
        else:
            authenticated_site_user.number_of_visits = authenticated_site_user.number_of_visits + 1

        authenticated_site_user.last_visit = visit
        authenticated_site_user.save()

    return {"success": True, "id": site_user.sf_user_id}
Example #3
0
def site(request, site_identifier):
    site = Site.get_by_site_identifier(site_identifier)
    query = Q()
    filters = {}

    if request.method == 'POST':
        if 'segment' in request.POST:
            # TODO: Store the filters into a segmentation model
            # Segment model has pickled version of Q() crazyness, total count the last time the segment ran, last time it ran, FK to site
            qs = convert_to_querystring(request.POST)

            return redirect('%s?%s' % (request.path, qs))
        else:
            raise Exception('Incorrect POST')

    (query, filters) = _get_filter_query(request)
    # print query
    # print filters

    # TODO: Abiliity to change time period.
    time_period = (timezone.now() - timedelta(days=30))
    filtered_authenticated_site_users = AuthenticatedSiteUser.get_filtered_authenticated_site_users(site, time_period, query)

    page_size = 10
    paginator = Paginator(filtered_authenticated_site_users, page_size)
    authenticated_site_users_count = paginator.count

    if filters:
        authenticated_site_users_count = AuthenticatedSiteUser.get_authenticated_site_users_count(site, time_period)

    site_users_count = SiteUser.get_site_users_count(site)

    page = request.GET.get('p')
    try:
        paginated_authenticated_site_users = paginator.page(page)
    except PageNotAnInteger:
        paginated_authenticated_site_users = paginator.page(1)
    except EmptyPage:
        paginated_authenticated_site_users = paginator.page(paginator.num_pages)

    authenticated_site_users_counts_dict = {}
    authenticated_site_users_counts = []

    for user in filtered_authenticated_site_users:
        date = user.last_visit_created.date()

        if date in authenticated_site_users_counts_dict:
            authenticated_site_users_counts_dict[date] = authenticated_site_users_counts_dict[date] + 1
        else:
            authenticated_site_users_counts_dict[date] = 1

    site_users_counts_dict = Visit.get_filtered_site_users_grouped_by_date(site, time_period)
    site_users_counts = []

    numdays = 30
    date_list = [ datetime.today().date() - timedelta(days=x) for x in range(0, numdays) ]

    for date in date_list:
        if date in site_users_counts_dict:
            site_users_counts.append(site_users_counts_dict[date])
        else:
            site_users_counts.append(0)

        if date in authenticated_site_users_counts_dict:
            authenticated_site_users_counts.append(authenticated_site_users_counts_dict[date])
        else:
            authenticated_site_users_counts.append(0)

    highest_site_user_count = max(authenticated_site_users_counts + site_users_counts)

    return {
        'TEMPLATE': 'www/site.html',
        'site': site,
        'filters': filters,
        'paginated_authenticated_site_users': paginated_authenticated_site_users,
        'filtered_authenticated_site_users_count': paginator.count,
        'filtered_authenticated_site_users_ratio': (float(paginator.count) / float(authenticated_site_users_count)) * 100 if authenticated_site_users_count else 0,
        'authenticated_site_users_count': authenticated_site_users_count,
        'site_users_count': site_users_count,
        'authenticated_site_users_ratio': (float(authenticated_site_users_count) / float(site_users_count)) * 100 if site_users_count else 0,
        'days': range(1, 30),
        'authenticated_site_users_counts': authenticated_site_users_counts,
        'site_users_counts': site_users_counts,
        'highest_site_user_count': highest_site_user_count,
    }