Beispiel #1
0
 def decorated_function(*args, **kwargs):
     anon = current_user.is_anonymous
     if anon or (not current_user.is_admin()):
         EventLogger.log_request(request,
                                 cuid="" if anon else current_user.id,
                                 msg=request.url)
     return f(*args, **kwargs)
Beispiel #2
0
def delete_index(username):
    user = Users.get(username)
    if user:
        current_user.delete_index()
        EventLogger.new_event(msg="index for {} deleted".format(user.id))
        return "index for {} deleted".format(username)
    else:
        return "no user {}".format(username)
Beispiel #3
0
def delete(username):
    user = Users.get(username)
    username = user.username
    user_id = user.id
    logout_user()

    # the current user is now logged out
    try:
        user.delete()
    except Exception as e:
        flash(str(e))
    else:
        flash("user '{}' ({}) deleted".format(username, user_id))
        EventLogger.new_event(msg="{} deleted".format(user_id))
    return redirect(url_for("splash"))
Beispiel #4
0
    def decorated_function(*args, **kwargs):
        event = {"msg": request.url}

        if not current_user.is_anonymous:
            if not current_user.is_admin():
                event.update({
                    "cuid": current_user.id,
                    "profile": current_user.profile
                })
            else:
                # if current user is admin we don't bother logging this event
                return f(*args, **kwargs)

        # If the user is anonymous or a regular user, we log the event
        EventLogger.log_request(request, **event)
        return f(*args, **kwargs)
Beispiel #5
0
def auth_callback():
    state = request.args.get("state")

    if "error" in request.args:
        flash("Error: {}".format(request.args.get("error")))

    if current_user.is_anonymous:
        args = {
            "code": request.args.get("code"),
            "client_id": app.config["STRAVA_CLIENT_ID"],
            "client_secret": app.config["STRAVA_CLIENT_SECRET"]
        }
        client = stravalib.Client()
        try:
            access_token = client.exchange_code_for_token(**args)

        except Exception as e:
            log.error("authorization error:\n{}".format(e))
            flash(str(e))
            return redirect(state)

        user_data = Users.strava_data_from_token(access_token)
        # log.debug("user data: {}".format(user_data))

        try:
            user = Users.add_or_update(**user_data)
        except Exception as e:
            log.exception(e)
            user = None
        if user:
            # remember=True, for persistent login.
            login_user(user, remember=True)
            # log.debug("authenticated {}".format(user))
            EventLogger.new_event(msg="authenticated {}".format(user.id))
        else:
            log.error("user authenication error")
            flash("There was a problem authorizing user")

    return redirect(
        request.args.get("state") or url_for("main", username=user.id))
Beispiel #6
0
def query_activities(username, out_type):
    user = Users.get(username)
    if user:
        options = {
            k: toObj(request.args.get(k))
            for k in request.args if toObj(request.args.get(k))
        }
        if not options:
            options = {"limit": 10}

        anon = current_user.is_anonymous
        if anon or (not current_user.is_admin()):
            EventLogger.log_request(request,
                                    cuid="" if anon else current_user.id,
                                    msg="{} query for {}: {}".format(
                                        out_type, user.id, options))
    else:
        return

    if out_type == "json":
        return jsonify(list(user.query_activities(**options)))

    else:

        def go(user, pool, out_queue):
            options["pool"] = pool
            options["out_queue"] = out_queue
            user.query_activities(**options)
            pool.join()
            out_queue.put(None)
            out_queue.put(StopIteration)

        pool = gevent.pool.Pool(app.config.get("CONCURRENCY"))
        out_queue = gevent.queue.Queue()
        gevent.spawn(go, user, pool, out_queue)
        gevent.sleep(0)
        return Response((sse_out(a) if a else sse_out() for a in out_queue),
                        mimetype='text/event-stream')
Beispiel #7
0
def event_history_init():
    EventLogger.init()
    return redirect(url_for("event_history"))
Beispiel #8
0
def logged_event(event_id):
    return jsonify(EventLogger.get_event(event_id))
Beispiel #9
0
def event_history_raw():
    return jsonify(EventLogger.get_log())
Beispiel #10
0
def event_history():
    events = EventLogger.get_log(int(request.args.get("n", 100)))
    if events:
        return render_template("history.html", events=events)
    return "No history"
Beispiel #11
0
def main(username):
    if current_user.is_authenticated:
        # If a user is logged in from a past session but has no record in our
        #  database (was deleted), we log them out and consider them anonymous
        try:
            assert current_user.id
        except AssertionError:
            logout_user()
        else:
            current_user.update_usage()

    user = None
    key = username if redis.get("Q:" + username) else ""

    if not key:
        # note: 'current_user' is the user that is currently logged in.
        #       'user' is the user we are displaying data for.
        user = Users.get(username)
        if not user:
            flash("user '{}' is not registered with this app".format(username))
            return redirect(url_for('splash'))

    date1 = request.args.get("date1") or request.args.get("after", "")
    date2 = request.args.get("date2") or request.args.get("before", "")
    preset = request.args.get("preset", "")
    limit = request.args.get("limit", "")
    baselayer = request.args.getlist("baselayer")
    ids = request.args.get("id", "")
    group = "multi" if key else request.args.get("group", "")

    if not ids:
        if (not date1) and (not date2):
            if preset:
                try:
                    preset = int(preset)
                except ValueError:
                    flash("'{}' is not a valid preset".format(preset))
                    preset = 7
            elif limit:
                try:
                    limit = int(limit)
                except ValueError:
                    flash("'{}' is not a valid limit".format(limit))
                    limit = 1
            elif group:
                pass
            else:
                limit = 10

    c1 = request.args.get("c1", "")
    c2 = request.args.get("c2", "")
    sz = request.args.get("sz", "")

    lat = request.args.get("lat")
    lng = request.args.get("lng")
    zoom = request.args.get("zoom")
    autozoom = request.args.get("autozoom") in ["1", "true"]

    if (not lat) or (not lng):
        lat, lng = app.config["MAP_CENTER"]
        zoom = app.config["MAP_ZOOM"]
        autozoom = "1"

    if current_user.is_anonymous or (not current_user.is_admin()):
        event = {
            "ip": request.access_route[-1],
            "agent": vars(request.user_agent),
            "msg": Utility.href(request.url, request.full_path)
        }

        if not current_user.is_anonymous:
            event.update({
                "profile": current_user.profile,
                "cuid": current_user.id
            })

        EventLogger.new_event(**event)

    paused = request.args.get("paused") in ["1", "true"]
    return render_template('main.html',
                           user=user,
                           lat=lat,
                           lng=lng,
                           zoom=zoom,
                           ids=ids,
                           group=group,
                           key=key,
                           preset=preset,
                           date1=date1,
                           date2=date2,
                           limit=limit,
                           autozoom=autozoom,
                           paused=paused,
                           baselayer=baselayer,
                           c1=c1,
                           c2=c2,
                           sz=sz)
Beispiel #12
0
def robots_txt():
    EventLogger.log_request(request, cuid="bot", msg=request.user_agent.string)
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'robots.txt')
Beispiel #13
0
log.setLevel(logging.DEBUG)

STREAMS_OUT = ["polyline", "time"]
STREAMS_TO_CACHE = ["polyline", "time"]

sslify = SSLify(app, skips=["webhook_callback"])

# models depend app so we import them afterwards
from models import (Users, Activities, EventLogger, Utility, Webhooks, Index,
                    Payments, db_sql, mongodb, redis)

# initialize MongoDB collections if necessary
collections = mongodb.collection_names()

if "history" not in collections:
    EventLogger.init()

if Activities.name not in collections:
    Activities.init_db()
else:
    Activities.update_ttl()

if Index.name not in collections:
    Index.init_db()
else:
    Index.update_ttl()

if Payments.name not in collections:
    Payments.init_db()

Analytics(app)