Esempio n. 1
0
 def new_from_request(cls, request):
     instance = cls()
     instance.uuid = uuid1mc()  # Don't wait for database commit to generate this
     instance.created_at = datetime.utcnow()
     instance.referrer = unicode_http_header(request.referrer)[:2083] if request.referrer else None
     instance.utm_source = request.args.get('utm_source', u'')[:250] or None
     instance.utm_medium = request.args.get('utm_medium', u'')[:250] or None
     instance.utm_term = request.args.get('utm_term', u'')[:250] or None
     instance.utm_content = request.args.get('utm_content', u'')[:250] or None
     instance.utm_id = request.args.get('utm_id', u'')[:250] or None
     instance.utm_campaign = request.args.get('utm_campaign', u'')[:250] or None
     instance.gclid = request.args.get('gclid', u'')[:250] or None
     instance.active_at = datetime.utcnow()
     instance.events = []
     return instance
Esempio n. 2
0
 def __init__(self, *args, **kwargs):
     self.id = uuid1mc()
     super(DiscountCoupon, self).__init__(*args, **kwargs)
Esempio n. 3
0
def load_user_data(user):
    """
    All pre-request utilities, run after g.user becomes available.

    Part 1: Load anon user:

    1. If there's g.user and session['anon_user'], it loads that anon_user and tags with user=g.user, then removes anon
    2. If there's no g.user and no session['anon_user'], sets session['anon_user'] = '******'
    3. If there's no g.user and there is session['anon_user'] = '******', creates a new anon user, then saves to cookie
    4. If there's no g.user and there is session['anon_user'] != 'test', loads g.anon_user

    Part 2: Are we in kiosk mode? Is there a preview campaign?
    Part 3: Look up user's IP address location as geonameids for use in targeting.
    """
    g.anon_user = None  # Could change below
    g.event_data = {}   # Views can add data to the current pageview event
    g.esession = None
    g.viewcounts = {}
    g.impressions = session.pop('impressions', {})  # Retrieve from cookie session if present there
    g.campaign_views = []
    g.jobpost_viewed = None, None
    g.bgroup = None
    now = datetime.utcnow()

    if request.endpoint not in ('static', 'baseframe.static'):
        # Loading an anon user only if we're not rendering static resources
        if user:
            if 'au' in session and session['au'] is not None and not unicode(session['au']).startswith(u'test'):
                anon_user = AnonUser.query.get(session['au'])
                if anon_user:
                    anon_user.user = user
            session.pop('au', None)
        else:
            if not session.get('au'):
                session['au'] = u'test-' + unicode(uuid1mc())
                g.esession = EventSessionBase.new_from_request(request)
                g.event_data['anon_cookie_test'] = session['au']
            elif session['au'] == 'test':  # Legacy test cookie, original request now lost
                g.anon_user = AnonUser()
                db.session.add(g.anon_user)
                g.esession = EventSession.new_from_request(request)
                g.esession.anon_user = g.anon_user
                db.session.add(g.esession)
                # We'll update session['au'] below after database commit
            elif unicode(session['au']).startswith('test-'):  # Newer redis-backed test cookie
                # This client sent us back our test cookie, so set a real value now
                g.anon_user = AnonUser()
                db.session.add(g.anon_user)
                g.esession = EventSession.new_from_request(request)
                g.esession.anon_user = g.anon_user
                db.session.add(g.esession)
                g.esession.load_from_cache(session['au'], UserEvent)
                # We'll update session['au'] below after database commit
            else:
                anon_user = AnonUser.query.get(session['au'])
                if not anon_user:
                    # XXX: We got a fake value? This shouldn't happen
                    g.event_data['anon_cookie_test'] = session['au']
                    session['au'] = u'test-' + unicode(uuid1mc())  # Try again
                    g.esession = EventSessionBase.new_from_request(request)
                else:
                    g.anon_user = anon_user

    # Prepare event session if it's not already present
    if g.user or g.anon_user and not g.esession:
        g.esession = EventSession.get_session(uuid=session.get('es'), user=g.user, anon_user=g.anon_user)
    if g.esession:
        session['es'] = g.esession.uuid

    # Don't commit here. It flushes SQLAlchemy's session cache and forces
    # fresh database hits. Let after_request commit. (Commented out 30-03-2016)
    # db.session.commit()
    g.db_commit_needed = True

    if g.anon_user:
        session['au'] = g.anon_user.id
        session.permanent = True
        if 'impressions' in session:
            # Run this in the foreground since we need this later in the request for A/B display consistency.
            # This is most likely being called from the UI-non-blocking sniffle.gif anyway.
            save_impressions(g.esession.id, session.pop('impressions').values(), now)

    # We have a user, now look up everything else

    if session.get('kiosk'):
        g.kiosk = True
    else:
        g.kiosk = False
    g.peopleflow_url = session.get('peopleflow')

    if 'preview' in request.args:
        preview_campaign = Campaign.get(request.args['preview'])
    else:
        preview_campaign = None

    g.preview_campaign = preview_campaign

    # Look up user's location
    if app.geoip:
        ipaddr = session.get('ipaddr')
        ipts = session.get('ipts')
        now = datetime.utcnow()
        if (not ipts or
                ipaddr != request.environ['REMOTE_ADDR'] or
                'geonameids' not in session or
                (ipts < now - timedelta(days=7))):
            # IP has changed or timed out or wasn't saved to the user's session. Look up location
            ipaddr = request.environ['REMOTE_ADDR']
            try:
                ipdata = app.geoip.city(ipaddr)
                geonameids = [item.geoname_id
                    for sublist in [[ipdata.city], ipdata.subdivisions, [ipdata.country], [ipdata.continent]]
                    for item in sublist
                    if item.geoname_id]
            except AddressNotFoundError:
                # Private IP range (127.0.0.1, etc). Should only happen in dev mode
                geonameids = []
            session['ipaddr'] = ipaddr
            session['geonameids'] = geonameids
            session['ipts'] = now
            g.user_geonameids = geonameids
        else:
            g.user_geonameids = session['geonameids']
    else:
        g.user_geonameids = []
Esempio n. 4
0
def load_user_data(user):
    """
    All pre-request utilities, run after g.user becomes available.

    Part 1: Load anon user:

    1. If there's g.user and session['anon_user'], it loads that anon_user and tags with user=g.user, then removes anon
    2. If there's no g.user and no session['anon_user'], sets session['anon_user'] = '******'
    3. If there's no g.user and there is session['anon_user'] = '******', creates a new anon user, then saves to cookie
    4. If there's no g.user and there is session['anon_user'] != 'test', loads g.anon_user

    Part 2: Are we in kiosk mode? Is there a preview campaign?
    Part 3: Look up user's IP address location as geonameids for use in targeting.
    """
    g.anon_user = None  # Could change below
    g.event_data = {}   # Views can add data to the current pageview event
    g.esession = None
    g.viewcounts = {}
    g.impressions = session.pop('impressions', {})  # Retrieve from cookie session if present there
    g.campaign_views = []
    g.jobpost_viewed = None, None
    g.bgroup = None
    now = datetime.utcnow()

    if request.endpoint not in ('static', 'baseframe.static'):
        # Loading an anon user only if we're not rendering static resources
        if user:
            if 'au' in session and session['au'] is not None and not unicode(session['au']).startswith(u'test'):
                anon_user = AnonUser.query.get(session['au'])
                if anon_user:
                    anon_user.user = user
            session.pop('au', None)
        else:
            if not session.get('au'):
                session['au'] = u'test-' + unicode(uuid1mc())
                g.esession = EventSessionBase.new_from_request(request)
                g.event_data['anon_cookie_test'] = session['au']
            elif session['au'] == 'test':  # Legacy test cookie, original request now lost
                g.anon_user = AnonUser()
                db.session.add(g.anon_user)
                g.esession = EventSession.new_from_request(request)
                g.esession.anon_user = g.anon_user
                db.session.add(g.esession)
                # We'll update session['au'] below after database commit
            elif unicode(session['au']).startswith('test-'):  # Newer redis-backed test cookie
                # This client sent us back our test cookie, so set a real value now
                g.anon_user = AnonUser()
                db.session.add(g.anon_user)
                g.esession = EventSession.new_from_request(request)
                g.esession.anon_user = g.anon_user
                db.session.add(g.esession)
                g.esession.load_from_cache(session['au'], UserEvent)
                # We'll update session['au'] below after database commit
            else:
                anon_user = AnonUser.query.get(session['au'])
                if not anon_user:
                    # XXX: We got a fake value? This shouldn't happen
                    g.event_data['anon_cookie_test'] = session['au']
                    session['au'] = u'test-' + unicode(uuid1mc())  # Try again
                    g.esession = EventSessionBase.new_from_request(request)
                else:
                    g.anon_user = anon_user

    # Prepare event session if it's not already present
    if g.user or g.anon_user and not g.esession:
        g.esession = EventSession.get_session(uuid=session.get('es'), user=g.user, anon_user=g.anon_user)
    if g.esession:
        session['es'] = g.esession.uuid

    # Don't commit here. It flushes SQLAlchemy's session cache and forces
    # fresh database hits. Let after_request commit. (Commented out 30-03-2016)
    # db.session.commit()
    g.db_commit_needed = True

    if g.anon_user:
        session['au'] = g.anon_user.id
        session.permanent = True
        if 'impressions' in session:
            # Run this in the foreground since we need this later in the request for A/B display consistency.
            # This is most likely being called from the UI-non-blocking sniffle.gif anyway.
            save_impressions(g.esession.id, session.pop('impressions').values(), now)

    # We have a user, now look up everything else

    if session.get('kiosk'):
        g.kiosk = True
    else:
        g.kiosk = False
    g.peopleflow_url = session.get('peopleflow')

    if 'preview' in request.args:
        preview_campaign = Campaign.get(request.args['preview'])
    else:
        preview_campaign = None

    g.preview_campaign = preview_campaign

    # Look up user's location
    if app.geoip:
        ipaddr = session.get('ipaddr')
        ipts = session.get('ipts')
        now = datetime.utcnow()
        if (not ipts or
                ipaddr != request.environ['REMOTE_ADDR'] or
                'geonameids' not in session or
                (ipts < now - timedelta(days=7))):
            # IP has changed or timed out or wasn't saved to the user's session. Look up location
            ipaddr = request.environ['REMOTE_ADDR']
            try:
                ipdata = app.geoip.city(ipaddr)
                geonameids = [item.geoname_id
                    for sublist in [[ipdata.city], ipdata.subdivisions, [ipdata.country], [ipdata.continent]]
                    for item in sublist
                    if item.geoname_id]
            except AddressNotFoundError:
                # Private IP range (127.0.0.1, etc). Should only happen in dev mode
                geonameids = []
            session['ipaddr'] = ipaddr
            session['geonameids'] = geonameids
            session['ipts'] = now
            g.user_geonameids = geonameids
        else:
            g.user_geonameids = session['geonameids']
    else:
        g.user_geonameids = []
Esempio n. 5
0
 def __init__(self, *args, **kwargs):
     self.id = uuid1mc()
     super(DiscountCoupon, self).__init__(*args, **kwargs)