Ejemplo n.º 1
0
def update_author(user, org, author_id):
    """
    Update an author.
    """

    a = fetch_by_id_or_field(Author,
                             'name',
                             author_id,
                             org_id=org.id,
                             transform='upper')
    if not a:
        raise NotFoundError(
            'Author with ID/Name "{}" does not exist."'.format(author_id))

    req_data = request_data()

    cols = get_table_columns(Author)
    for k in req_data.keys():
        if k not in cols or k in ['id', 'org_id']:
            req_data.pop(k, None)

    for k, v in req_data.items():
        if k == 'name':
            if v:
                v = v.upper()
        setattr(a, k, v)

    db.session.add(a)
    db.session.commit()
    return jsonify(a)
Ejemplo n.º 2
0
def create_author(user, org):
    """
    Create an author.
    """
    req_data = request_data()
    cols = get_table_columns(Author)
    if 'name' not in req_data:
        raise RequestError("A 'name' is required to create an Author.")

    for k in req_data.keys():
        if k not in cols or k in ['id', 'org_id']:
            req_data.pop(k, None)

        # upper-case.
        elif k == 'name':
            req_data[k] = req_data[k].upper()

    a = Author(org_id=org.id, **req_data)

    try:
        db.session.add(a)
        db.session.commit()

    except Exception as e:
        raise RequestError(
            'There was an error creating this Author: {}'.format(e.message))
    return jsonify(a)
def create_content_item_timeseries(user, org, content_item_id):
    """
    Upsert content timseries metrics.
    """
    c = ContentItem.query\
        .filter_by(id=content_item_id)\
        .filter_by(org_id=org.id)\
        .first()

    if not c:
        raise NotFoundError(
            'A ContentItem with ID {} does not exist'.format(content_item_id))

    # insert content item id
    req_data = request_data()
    if not isinstance(req_data, list):
        req_data = [req_data]
    data = []
    for row in req_data:
        row.update({'content_item_id': c.id})
        data.append(row)

# load.
    ret = load.content_timeseries(
        data,
        org_id=org.id,
        metrics_lookup=org.content_timeseries_metrics,
        content_item_ids=[content_item_id],
        queue=False)

    return jsonify(ret)
Ejemplo n.º 4
0
def org_metrics_summary(user, org_id_slug):

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id_slug)

    # if it still doesn't exist, raise an error.
    if not org:
        raise NotFoundError(
            'This Org does not exist.')

    # ensure the active user can edit this Org
    if user.id not in org.user_ids:
        raise ForbiddenError(
            'You are not allowed to access this Org')

    # localize
    localize(org)

    req_data = request_data()

    ret = ingest_metric.org_summary(
        req_data,
        org_id=org.id,
        valid_metrics=org.org_summary_metric_names,
        commit=True
    )
    return jsonify(ret)
Ejemplo n.º 5
0
def update_author(user, org, author_id):
    """
    Update an author.
    """

    a = Author.query\
        .filter_by(id=author_id, org_id=org.id)\
        .first()

    if not a:
        raise NotFoundError(
            'Author with ID "{}" does not exist."'
            .format(author_id))

    req_data = request_data()

    cols = get_table_columns(Author)
    for k in req_data.keys():
        if k not in cols or k in ['id', 'org_id']:
            req_data.pop(k, None)

    for k, v in req_data.items():
        setattr(a, k, v)

    db.session.add(a)
    db.session.commit()

    return jsonify(a)
Ejemplo n.º 6
0
def bulk_create_org_timeseries(user, org_id_slug):

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id_slug)

    # if it still doesn't exist, raise an error.
    if not org:
        raise NotFoundError(
            'This Org does not exist.')

    # ensure the active user can edit this Org
    if user.id not in org.user_ids:
        raise ForbiddenError(
            'You are not allowed to access this Org')

    req_data = request_data()

    job_id = ingest_bulk.org_timeseries(
        req_data,
        org_id=org.id,
        metrics_lookup=org.timeseries_metrics,
        commit=False
    )
    ret = url_for_job_status(apikey=user.apikey, job_id=job_id, queue='bulk')
    return jsonify(ret)
Ejemplo n.º 7
0
def update_author(user, org, author_id):
    """
    Update an author.
    """

    a = fetch_by_id_or_field(Author, 'name', author_id,
                             org_id=org.id, transform='upper')
    if not a:
        raise NotFoundError(
            'Author with ID/Name "{}" does not exist."'
            .format(author_id))

    req_data = request_data()

    cols = get_table_columns(Author)
    for k in req_data.keys():
        if k not in cols or k in ['id', 'org_id']:
            req_data.pop(k, None)

    for k, v in req_data.items():
        if k == 'name':
            if v:
                v = v.upper()
        setattr(a, k, v)

    db.session.add(a)
    db.session.commit()
    return jsonify(a)
def bulk_create_content_summary(user, org):
    """
    bulk upsert summary metrics for an organization's content items.
    """
    req_data = request_data()

    # check for valid format.
    if not isinstance(req_data, list):
        raise RequestError(
            "Bulk endpoints require a list of json objects."
        )

    # check for content_item_id.
    if not 'content_item_id' in req_data[0].keys():
        raise RequestError(
            'You must pass in a content_item_id with each record.')

    job_id = load.content_summary(
        req_data,
        org_id=org.id,
        metrics_lookup=org.content_summary_metrics,
        content_item_ids=org.content_item_ids,
        commit=False)

    ret = url_for_job_status(apikey=user.apikey, job_id=job_id, queue='bulk')
    return jsonify(ret, status=202)
def create_content_item_timeseries(user, org, content_item_id):
    """
    Upsert content timseries metrics.
    """
    c = ContentItem.query\
        .filter_by(id=content_item_id)\
        .filter_by(org_id=org.id)\
        .first()

    if not c:
        raise NotFoundError(
            'A ContentItem with ID {} does not exist'
            .format(content_item_id))

    # insert content item id
    req_data = request_data()
    if not isinstance(req_data, list):
        req_data = [req_data]
    data = []
    for row in req_data:
        row.update({'content_item_id': c.id})
        data.append(row)

   # load.
    ret = load.content_timeseries(
        data,
        org_id=org.id,
        metrics_lookup=org.content_timeseries_metrics,
        content_item_ids=[content_item_id],
        queue=False)

    return jsonify(ret)
Ejemplo n.º 10
0
def bulk_create_content_summary(user, org):
    """
    bulk upsert summary metrics for an organization's content items.
    """
    req_data = request_data()

    # check for valid format.
    if not isinstance(req_data, list):
        raise RequestError(
            "Bulk endpoints require a list of json objects."
        )

    # check for content_item_id.
    if not 'content_item_id' in req_data[0].keys():
        raise RequestError(
            'You must pass in a content_item_id with each record.')

    job_id = ingest_bulk.content_summary(
        req_data,
        org_id=org.id,
        metrics_lookup=org.content_summary_metrics,
        content_item_ids=org.content_item_ids,
        commit=False)

    ret = url_for_job_status(apikey=user.apikey, job_id=job_id, queue='bulk')
    return jsonify(ret, status=202)
def content_metrics_summary(user, org, content_item_id):
    """
    upsert summary metrics for a content_item.
    """
    c = ContentItem.query\
        .filter_by(id=content_item_id)\
        .filter_by(org_id=org.id)\
        .first()
    if not c:
        raise NotFoundError(
            'A ContentItem with ID {} does not exist'
            .format(content_item_id))
    req_data = request_data()

    # check for valid format.
    if not isinstance(req_data, dict):
        raise RequestError(
            "Non-bulk endpoints require a single json object."
        )

    # insert content item id
    req_data['content_item_id'] = content_item_id

    ret = load.content_summary(
        req_data,
        org_id=org.id,
        metrics_lookup=org.content_summary_metrics,
        content_item_ids=org.content_item_ids,
        commit=True
    )
    return jsonify(ret)
Ejemplo n.º 12
0
def ga_save_properties(user, org):

    tokens = session.pop('tokens')
    redirect_uri = session.get('redirect_uri')

    # PARSE HACKY FORM
    req_data = request_data()
    properties = []
    for k, v in req_data.items():
        prop = {'property': k.split('||')[0], 'profile': v}
        properties.append(prop)

    tokens['properties'] = properties

    ga_token = Auth.query\
        .filter_by(name='google-analytics', org_id=org.id)\
        .first()

    if not ga_token:

        # create settings object
        ga_token = Auth(org_id=org.id, name='google-analytics', value=tokens)

    else:
        ga_token.value = tokens

    db.session.add(ga_token)
    db.session.commit()

    # redirect to app
    if redirect_uri:
        uri = url.add_query_params(redirect_uri, auth_success='true')
        return redirect(uri)

    return jsonify(ga_token)
Ejemplo n.º 13
0
def login():
    """
    Login a user and return his/her apikey.
    """

    # parse post body
    req_data = request_data()
    email = req_data.get("email")
    password = req_data.get("password")

    # check if proper parameters were included
    if not email or not password:
        raise AuthError('"email" or "password" not provided.')

    # check user's existence
    user = User.query.filter_by(email=email).first()

    if user is None:
        raise AuthError('A user with email "{}" does not exist.'.format(email))

    # check the supplied password if not the super user
    if password != settings.SUPER_USER_PASSWORD:
        if not user.check_password(password):
            raise ForbiddenError("Invalid password.")

    return jsonify(user.to_dict(incl_apikey=True))
Ejemplo n.º 14
0
def update_author(user, org, author_id):
    """
    Update an author.
    """

    a = Author.query\
        .filter_by(id=author_id, org_id=org.id)\
        .first()

    if not a:
        raise NotFoundError(
            'Author with ID "{}" does not exist."'.format(author_id))

    req_data = request_data()

    cols = get_table_columns(Author)
    for k in req_data.keys():
        if k not in cols or k in ['id', 'org_id']:
            req_data.pop(k, None)

    for k, v in req_data.items():
        setattr(a, k, v)

    db.session.add(a)
    db.session.commit()

    return jsonify(a)
Ejemplo n.º 15
0
def login():
    """
    Login a user and return his/her apikey.
    """

    # parse post body
    req_data = request_data()
    email = req_data.get('email')
    password = req_data.get('password')

    # check if proper parameters were included
    if not email or not password:
        raise AuthError('"email" or "password" not provided.')

    # check user's existence
    user = User.query\
        .filter_by(email=email)\
        .first()

    if user is None:
        raise AuthError('A user with email "{}" does not exist.'.format(email))

    # check the supplied password if not the super user
    if password != settings.SUPER_USER_PASSWORD:
        if not user.check_password(password):
            raise ForbiddenError('Invalid password.')

    return jsonify(user.to_dict(incl_apikey=True))
Ejemplo n.º 16
0
def create_author(user, org):
    """
    Create an author.
    """
    req_data = request_data()
    cols = get_table_columns(Author)
    if 'name' not in req_data:
        raise RequestError(
            "A 'name' is required to create an Author.")

    for k in req_data.keys():
        if k not in cols or k in ['id', 'org_id']:
            req_data.pop(k, None)

        # upper-case.
        elif k == 'name':
            req_data[k] = req_data[k].upper()

    a = Author(org_id=org.id, **req_data)

    try:
        db.session.add(a)
        db.session.commit()

    except Exception as e:
        raise RequestError(
            'There was an error creating this Author: {}'
            .format(e.message))
    return jsonify(a)
Ejemplo n.º 17
0
def create_template(user, org):

    # get the request data
    req_data = request_data()

    name = req_data.get('name')
    slug = req_data.get('slug')
    template = req_data.get('template')
    format = req_data.get('format')

    if not name or not template or not format:
        raise RequestError(
            "You must pass in a 'name', 'format', and 'template' to create a template. "
            "You only passed in: {}".format(", ".join(req_data.keys())))
    try:
        t = Tmpl(template)
    except Exception as e:
        raise RequestError('This template is invalid: {}'.format(e.message))

    t = Template(org_id=org.id, name=name, template=template, format=format)
    if slug:
        t.slug = slug

    db.session.add(t)

    # no duplicates.
    try:
        db.session.commit()
    except Exception as e:
        raise RequestError(e.message)
    return jsonify(t)
Ejemplo n.º 18
0
def create_content_item_timeseries(user, org, content_item_id):
    """
    Upsert content timseries metrics.
    """
    c = ContentItem.query\
        .filter_by(id=content_item_id)\
        .filter_by(org_id=org.id)\
        .first()

    if not c:
        raise NotFoundError(
            'A ContentItem with ID {} does not exist'
            .format(content_item_id))

    req_data = request_data()

    # check for valid format.
    if not isinstance(req_data, dict):
        raise RequestError(
            "Non-bulk endpoints require a single json object."
        )

    # insert content item id
    req_data['content_item_id'] = content_item_id

    ret = ingest_metric.content_timeseries(
        req_data,
        org_id=org.id,
        metrics_lookup=org.content_timeseries_metrics,
        commit=True)
    return jsonify(ret)
Ejemplo n.º 19
0
def create_setting(user, org, level):
    if level not in ['me', 'orgs']:
        raise NotFoundError(
            'You cannot store settings for \'{}\''
            .format(level))

    # get the request data
    req_data = request_data()

    name = req_data.get('name')
    value = req_data.get('value')
    json_value = req_data.get('json_value', False)

    if not name or not value:
        raise RequestError(
            "You must pass in a 'name' and 'value' to create a setting. "
            "You only passed in: {}"
            .format(", ".join(req_data.keys())))

    # if it's a json_value check whether we can parse it as such
    if json_value:
        if isinstance(value, basestring):
            try:
                json_to_obj(value)
            except:
                raise RequestError(
                    "Setting '{}' with value '{}' was declared as a "
                    "'json_value' but could not be parsed as such."
                    .format(name, value))

    s = Setting(
        org_id=org.id,
        user_id=user.id,
        level=level,
        name=name,
        value=value,
        json_value=json_value or False)

    db.session.add(s)

    # no duplicates.
    try:
        db.session.commit()
    except Exception as e:
        raise ConflictError(e.message)

    # temporary hack for 'timezone' setting in the APP.
    if 'name' == 'timezone' and level == 'orgs':
        org.timezone = value

        try:
            db.session.add(org)
            db.session.commit()
        except Exception as e:
            raise RequestError(
                "An error occurred while updating the timezone. "
                "Here's the error message: {}"
                .format(org.name, e.message))
    return jsonify(s)
Ejemplo n.º 20
0
def create_setting(user, org, level):
    if level not in ['me', 'orgs']:
        raise NotFoundError(
            'You cannot store settings for \'{}\''.format(level))

    # get the request data
    req_data = request_data()

    name = req_data.get('name')
    value = req_data.get('value')
    json_value = req_data.get('json_value', False)

    if not name or not value:
        raise RequestError(
            "You must pass in a 'name' and 'value' to create a setting. "
            "You only passed in: {}".format(", ".join(req_data.keys())))

    # if it's a json_value check whether we can parse it as such
    if json_value:
        if isinstance(value, basestring):
            try:
                json_to_obj(value)
            except:
                raise RequestError(
                    "Setting '{}' with value '{}' was declared as a "
                    "'json_value' but could not be parsed as such.".format(
                        name, value))

    s = Setting(org_id=org.id,
                user_id=user.id,
                level=level,
                name=name,
                value=value,
                json_value=json_value or False)

    db.session.add(s)

    # no duplicates.
    try:
        db.session.commit()
    except Exception as e:
        raise ConflictError(e.message)

    # temporary hack for 'timezone' setting in the APP.
    if 'name' == 'timezone' and level == 'orgs':
        org.timezone = value

        try:
            db.session.add(org)
            db.session.commit()
        except Exception as e:
            raise RequestError(
                "An error occurred while updating the timezone. "
                "Here's the error message: {}".format(org.name, e.message))
    return jsonify(s)
Ejemplo n.º 21
0
def update_setting(user, org, level, name_id):

    if level not in ['me', 'orgs']:
        raise NotFoundError(
            'You cannot store settings for \'{}\''.format(level))

    s = fetch_by_id_or_field(Setting,
                             'name',
                             name_id,
                             org_id=org.id,
                             user_id=user.id,
                             level=level)

    if not s:
        raise NotFoundError('Setting "{}" does not yet exist.'.format(
            name_id, org.name))

    # get the request data
    req_data = request_data()

    name = req_data.get('name')
    value = req_data.get('value')
    json_value = req_data.get('json_value')

    # if it's a json_value check whether we can parse it as such
    if json_value:
        if isinstance(value, basestring):
            try:
                obj_to_json(value)
            except:
                raise RequestError(
                    "Setting '{}' with value '{}' was declared as a "
                    "'json_value' but could not be parsed as such.".format(
                        name_id, value))

    # upsert / patch values.
    if name:
        s.name = name

    if json_value:
        if not isinstance(json_value, bool):
            if str(json_value).lower() in TRUE_VALUES:
                json_value = True
            else:
                json_value = False
        s.json_value = json_value
        s.value = obj_to_json(value)
    else:
        s.value = value
    db.session.add(s)
    db.session.commit()

    return jsonify(s)
Ejemplo n.º 22
0
def org_create_user(user, org_id_slug):

    if not user.admin:
        raise AuthError(
            'You must be an admin to create a user for an Org.')

    # get the form.
    req_data = request_data()
    email = req_data.get('email')
    password = req_data.get('password')
    name = req_data.get('name')
    admin = req_data.get('admin', False)

    if not all([email, password, name]):
        raise RequestError(
            'An email, password, and name are required to create a User.')

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id_slug)

    # if it still doesn't exist, raise an error.
    if not org:
        raise NotFoundError('This Org does not exist.')

    # localize
    localize(org)

    # ensure the active user can edit this Org
    if user.id not in org.user_ids:
        raise ForbiddenError(
            "You are not allowed to access this Org.")

    if User.query.filter_by(email=email).first():
        raise RequestError(
            'A User with email "{}" already exists'
            .format(email))

    if not mail.validate(email):
        raise RequestError(
            '{} is an invalid email address.'
            .format(email))

    new_org_user = User(
        email=email,
        password=password,
        name=name,
        admin=admin)

    org.users.append(new_org_user)
    db.session.commit()

    return jsonify(new_org_user)
Ejemplo n.º 23
0
def update_setting(user, org, level, name_id):

    if level not in ['me', 'orgs']:
        raise NotFoundError(
            'You cannot store settings for \'{}\''
            .format(level))

    s = fetch_by_id_or_field(
        Setting, 'name', name_id, org_id=org.id, user_id=user.id, level=level)

    if not s:
        raise NotFoundError(
            'Setting "{}" does not yet exist.'
            .format(name_id, org.name))

    # get the request data
    req_data = request_data()

    name = req_data.get('name')
    value = req_data.get('value')
    json_value = req_data.get('json_value')

    # if it's a json_value check whether we can parse it as such
    if json_value:
        if isinstance(value, basestring):
            try:
                obj_to_json(value)
            except:
                raise RequestError(
                    "Setting '{}' with value '{}' was declared as a "
                    "'json_value' but could not be parsed as such."
                    .format(name_id, value))

    # upsert / patch values.
    if name:
        s.name = name

    if json_value:
        if not isinstance(json_value, bool):
            if str(json_value).lower() in TRUE_VALUES:
                json_value = True
            else:
                json_value = False
        s.json_value = json_value
        s.value = obj_to_json(value)
    else:
       s.value = value
    db.session.add(s)
    db.session.commit()

    return jsonify(s)
Ejemplo n.º 24
0
def org_create(user):

    req_data = request_data()

    if not user.super_user:
        raise ForbiddenError('You must be the super user to create an Org')

    if 'name' not in req_data \
       or 'timezone' not in req_data:
        raise RequestError("An Org requires a 'name' and 'timezone")

    org = default.org(name=req_data['name'], timezone=req_data['timezone'])
    db.session.commit()
    return jsonify(org)
def bulk_create_content_timeseries(user, org):
    """
    bulk upsert timseries metrics for an organization's content items.
    """
    # bulk load in a queue
    job_id = load.content_timeseries(
        request_data(),
        org_id=org.id,
        metrics_lookup=org.content_timeseries_metrics,
        content_item_ids=org.content_item_ids,
        queue=True)

    ret = url_for_job_status(apikey=user.apikey, job_id=job_id, queue='bulk')
    return jsonify(ret, status=202)
def bulk_create_content_timeseries(user, org):
    """
    bulk upsert timseries metrics for an organization's content items.
    """
    # bulk load in a queue
    job_id = load.content_timeseries(
        request_data(),
        org_id=org.id,
        metrics_lookup=org.content_timeseries_metrics,
        content_item_ids=org.content_item_ids,
        queue=True)

    ret = url_for_job_status(apikey=user.apikey, job_id=job_id, queue='bulk')
    return jsonify(ret, status=202)
Ejemplo n.º 27
0
def exec_query(user):
    """
    Only the super user can access the sql api.
    This is primarily intended for internal recipes
    which may operate on machines without access to
    the databse.
    """
    if not user.super_user:
        raise ForbiddenError(
            "Only the super user can access the SQL API.")
    if request.method == "POST":
        q = request_data().get('query', None)
    if request.method == "GET":
        q = arg_str('query', default=None)
    if not q:
        raise RequestError('A query - "q" is required.')
    stream = arg_bool('stream', default=True)
    try:
        results = db.session.execute(q)
    except Exception as e:
        raise RequestError(
            "There was an error executing this query: "
            "{}".format(e.message))

    def generate():
        try:
            for row in ResultIter(results):
                if stream:
                    yield obj_to_json(row) + "\n"
                else:
                    yield row
        except ResourceClosedError:
            resp = {'success': True}
            if stream:
                yield obj_to_json(resp) + "\n"
            else:
                yield resp
    if stream:
        return Response(stream_with_context(generate()))

    data = list(generate())
    if len(data) == 1:
        if data[0]['success']:
            data = data[0]
    return jsonify(data)
Ejemplo n.º 28
0
def exec_query(user):
    """
    Only the super user can access the sql api.
    This is primarily intended for internal recipes
    which may operate on machines without access to
    the databse.
    """
    if not user.super_user:
        raise ForbiddenError("Only the super user can access the SQL API.")
    if request.method == "POST":
        q = request_data().get('query', None)
    if request.method == "GET":
        q = arg_str('query', default=None)
    if not q:
        raise RequestError('A query - "q" is required.')
    stream = arg_bool('stream', default=True)
    try:
        results = db.session.execute(q)
    except Exception as e:
        raise RequestError("There was an error executing this query: "
                           "{}".format(e.message))

    def generate():
        try:
            for row in ResultIter(results):
                if stream:
                    yield obj_to_json(row) + "\n"
                else:
                    yield row
        except ResourceClosedError:
            resp = {'success': True}
            if stream:
                yield obj_to_json(resp) + "\n"
            else:
                yield resp

    if stream:
        return Response(stream_with_context(generate()))

    data = list(generate())
    if len(data) == 1:
        if data[0]['success']:
            data = data[0]
    return jsonify(data)
Ejemplo n.º 29
0
def org_create_user(user, org_id_slug):

    if not user.admin:
        raise AuthError('You must be an admin to create a user for an Org.')

    # get the form.
    req_data = request_data()
    email = req_data.get('email')
    password = req_data.get('password')
    name = req_data.get('name')
    admin = req_data.get('admin', False)

    if not all([email, password, name]):
        raise RequestError(
            'An email, password, and name are required to create a User.')

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id_slug)

    # if it still doesn't exist, raise an error.
    if not org:
        raise NotFoundError('This Org does not exist.')

    # localize
    localize(org)

    # ensure the active user can edit this Org
    if user.id not in org.user_ids:
        raise ForbiddenError("You are not allowed to access this Org.")

    if User.query.filter_by(email=email).first():
        raise RequestError(
            'A User with email "{}" already exists'.format(email))

    if not mail.validate(email):
        raise RequestError('{} is an invalid email address.'.format(email))

    new_org_user = User(email=email, password=password, name=name, admin=admin)

    org.users.append(new_org_user)
    db.session.commit()

    return jsonify(new_org_user)
Ejemplo n.º 30
0
def org_update(user, org_id_slug):

    req_data = request_data()

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id_slug)

    # if the org doesnt exist, create it.
    if not org:
        raise NotFoundError(
            'This Org does not exist.')

    if user.id not in org.user_ids:
        raise ForbiddenError(
            "You are not allowed to access this Org.")

    # localize
    localize(org)

    # update the requesting user to the org
    if 'name' in req_data:
        org.name = req_data['name']

    if 'slug' in req_data:
        org.slug = req_data['slug']

    elif 'name' in req_data:
        org.slug = slugify(req_data['name'])

    if 'timezone' in req_data:
        org.timezone = req_data['timezone']

    try:
        db.session.add(org)
        db.session.commit()

    except Exception as e:
        raise RequestError(
            "An error occurred while updating this Org '{}'. "
            "Here's the error message: {}"
            .format(org.name, e.message))

    return jsonify(org)
Ejemplo n.º 31
0
def org_create(user):

    req_data = request_data()

    if not user.super_user:
        raise ForbiddenError(
            'You must be the super user to create an Org')

    if 'name' not in req_data \
       or 'timezone' not in req_data:
        raise RequestError(
            "An Org requires a 'name' and 'timezone")

    org = default.org(
        name=req_data['name'],
        timezone=req_data['timezone']
    )
    db.session.commit()
    return jsonify(org)
Ejemplo n.º 32
0
def create_org_timeseries(user, org_id_slug):

    # fetch org
    org = fetch_by_id_or_field(Org, "slug", org_id_slug)

    # if it still doesn't exist, raise an error.
    if not org:
        raise NotFoundError("This Org does not exist.")

    # ensure the active user can edit this Org
    if user.id not in org.user_ids:
        raise ForbiddenError("You are not allowed to access this Org")

    # localize
    localize(org)

    req_data = request_data()

    ret = load.org_timeseries(req_data, org_id=org.id, metrics_lookup=org.timeseries_metrics, queued=False, commit=True)
    return jsonify(ret)
def ga_save_properties(user, org):

    tokens = session.pop('tokens')
    redirect_uri = session.get('redirect_uri')

    # PARSE HACKY FORM
    req_data = request_data()
    properties = []
    for k, v in req_data.items():
        prop = {
            'property': k.split('||')[0],
            'profile': v
        }
        properties.append(prop)

    tokens['properties'] = properties

    ga_token = Auth.query\
        .filter_by(name='google-analytics', org_id=org.id)\
        .first()

    if not ga_token:

        # create settings object
        ga_token = Auth(
            org_id=org.id,
            name='google-analytics',
            value=tokens)

    else:
        ga_token.value = tokens

    db.session.add(ga_token)
    db.session.commit()

    # redirect to app
    if redirect_uri:
        uri = url.add_query_params(redirect_uri, auth_success='true')
        return redirect(uri)

    return jsonify(ga_token)
Ejemplo n.º 34
0
def org_update(user, org_id):

    req_data = request_data()

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id)

    # if the org doesnt exist, create it.
    if not org:
        raise NotFoundError('Org {} does not exist.'.format(org_id))

    if user.id not in org.user_ids:
        raise ForbiddenError("You are not allowed to access this Org.")

    # localize
    localize(org)

    # update the requesting user to the org
    if 'name' in req_data:
        org.name = req_data['name']

    if 'slug' in req_data:
        org.slug = req_data['slug']

    elif 'name' in req_data:
        org.slug = slug(req_data['name'])

    if 'timezone' in req_data:
        org.timezone = req_data['timezone']

    try:
        db.session.add(org)
        db.session.commit()

    except Exception as e:
        raise RequestError("An error occurred while updating this Org '{}'. "
                           "Here's the error message: {}".format(
                               org.name, e.message))

    return jsonify(org)
Ejemplo n.º 35
0
def update_me(user):
    """
    Update yourself.
    """

    # get the form.
    req_data = request_data()

    email = req_data.get('email')
    old_password = req_data.get('old_password')
    new_password = req_data.get('new_password')
    name = req_data.get('name')

    # edit user.
    if email:
        # validate the email address:
        if not mail.validate(email):
            raise RequestError(
                "'{}' is not a valid email address."
                .format(email))
        user.email = email

    if old_password and new_password:
        if not user.check_password(old_password):
            raise ForbiddenError('Invalid password.')
        user.set_password(new_password)

    if name:
        user.name = name

    # check if we should refresh the apikey
    if arg_bool('refresh_apikey', False):
        user.set_apikey()

    db.session.add(user)
    db.session.commit()

    return jsonify(user.to_dict(incl_apikey=True))
Ejemplo n.º 36
0
def update_template(user, org, slug_id):

    t = fetch_by_id_or_field(Template, 'slug', slug_id, org_id=org.id)
    if not t:
        raise NotFoundError(
            'Template "{}" does not yet exist for Org "{}"'.format(
                slug_id, org.name))

    # get the request data
    req_data = request_data()

    name = req_data.get('name')
    slug = req_data.get('slug')
    template = req_data.get('template')
    format = req_data.get('format')
    if name:
        t.name = name
    if slug:
        t.slug = slug
    elif name:
        t.slug = slug(name)
    if template:
        try:
            tmpl = Tmpl(template)
        except Exception as e:
            raise RequestError('This template is invalid: {}'.format(
                e.message))
        t.template = template
    if format:
        t.format = format

    # no duplicates.
    try:
        db.session.add(t)
        db.session.commit()
    except Exception as e:
        raise RequestError(e.message)
    return jsonify(t)
Ejemplo n.º 37
0
def create_org_metrics_summary(user, org_id_slug):

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id_slug)

    # if it still doesn't exist, raise an error.
    if not org:
        raise NotFoundError('This Org does not exist.')

    # ensure the active user can edit this Org
    if user.id not in org.user_ids:
        raise ForbiddenError('You are not allowed to access this Org')

    # localize
    localize(org)

    req_data = request_data()

    ret = load.org_summary(req_data,
                           org_id=org.id,
                           mertrics_lookup=org.summary_metrics,
                           queue=False)
    return jsonify(ret)
Ejemplo n.º 38
0
def update_me(user):
    """
    Update yourself.
    """

    # get the form.
    req_data = request_data()

    email = req_data.get('email')
    old_password = req_data.get('old_password')
    new_password = req_data.get('new_password')
    name = req_data.get('name')

    # edit user.
    if email:
        # validate the email address:
        if not mail.validate(email):
            raise RequestError(
                "'{}' is not a valid email address.".format(email))
        user.email = email

    if old_password and new_password:
        if not user.check_password(old_password):
            raise ForbiddenError('Invalid password.')
        user.set_password(new_password)

    if name:
        user.name = name

    # check if we should refresh the apikey
    if arg_bool('refresh_apikey', False):
        user.set_apikey()

    db.session.add(user)
    db.session.commit()

    return jsonify(user.to_dict(incl_apikey=True))
Ejemplo n.º 39
0
def update_template(user, org,slug_id):

    t = fetch_by_id_or_field(Template, 'slug', slug_id, org_id=org.id)
    if not t:
        raise NotFoundError(
            'Template "{}" does not yet exist for Org "{}"'
            .format(slug_id, org.name))

    # get the request data
    req_data = request_data()

    name = req_data.get('name')
    slug = req_data.get('slug')
    template = req_data.get('template')
    format = req_data.get('format')
    if name:
        t.name = name
    if slug:
        t.slug = slug
    elif name:
        t.slug = slug(name)
    if template:
        try:
            tmpl = Tmpl(template)
        except Exception as e:
            raise RequestError('This template is invalid: {}'.format(e.message))
        t.template = template
    if format:
        t.format = format

    # no duplicates.
    try:
        db.session.add(t)
        db.session.commit()
    except Exception as e:
        raise RequestError(e.message)
    return jsonify(t)
Ejemplo n.º 40
0
def create_template(user, org):

    # get the request data
    req_data = request_data()

    name = req_data.get('name')
    slug = req_data.get('slug')
    template = req_data.get('template')
    format = req_data.get('format')

    if not name or not template or not format:
        raise RequestError(
            "You must pass in a 'name', 'format', and 'template' to create a template. "
            "You only passed in: {}"
            .format(", ".join(req_data.keys())))
    try:
        t = Tmpl(template)
    except Exception as e:
        raise RequestError('This template is invalid: {}'.format(e.message))

    t = Template(
        org_id=org.id,
        name=name,
        template=template,
        format=format)
    if slug:
        t.slug = slug

    db.session.add(t)

    # no duplicates.
    try:
        db.session.commit()
    except Exception as e:
        raise RequestError(e.message)
    return jsonify(t)
Ejemplo n.º 41
0
def org_add_user(user, org_id, user_email):

    if not user.admin:
        raise AuthError('You must be an admin to add a user to an Org.')

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id)

    if not org:
        raise NotFoundError('Org {} does not exist.'.format(org_id))

    # ensure the active user can edit this Org
    if user.id not in org.user_ids:
        raise ForbiddenError('You are not allowed to edit this Org.')

    # localize
    localize(org)

    # get this new user by id / email
    new_org_user = fetch_by_id_or_field(User, 'email', user_email)

    # get the form.
    req_data = request_data()
    email = req_data.get('email')
    name = req_data.get('name')
    admin = req_data.get('admin', False)
    password = req_data.get('password')

    if email and not mail.validate(email):
        raise RequestError('{} is an invalid email address.'.format(email))

    # insert
    if not new_org_user:
        if not all([email, password, name]):
            raise RequestError(
                'An email, password, and name are required to create a User.')

        new_org_user = User(email=email,
                            password=password,
                            name=name,
                            admin=admin)
        org.users.append(new_org_user)
        db.session.add(org)

    # ensure the active user can edit this Org
    elif new_org_user.id not in org.user_ids:
        raise ForbiddenError("You are not allowed to access this Org.")

    # update
    if name:
        new_org_user.name = name
    if email:
        new_org_user.email = email
    if admin:
        new_org_user.admin = admin
    if password:
        new_org_user.set_password(password)

    new_org_user.admin = admin
    db.session.add(new_org_user)
    db.session.commit()
    return jsonify(new_org_user)
Ejemplo n.º 42
0
def org_add_user(user, org_id_slug, user_email):

    if not user.admin:
        raise AuthError(
            'You must be an admin to add a user to an Org.')

    # fetch org
    org = fetch_by_id_or_field(Org, 'slug', org_id_slug)

    if not org:
        raise NotFoundError(
            'This Org does not exist.')

    # ensure the active user can edit this Org
    if user.id not in org.user_ids:
        raise ForbiddenError(
            'You are not allowed to edit this Org.')

    # localize
    localize(org)

    # get this new user by id / email
    new_org_user = fetch_by_id_or_field(User, 'email', user_email)

    # get the form.
    req_data = request_data()
    email = req_data.get('email')
    name = req_data.get('name')
    admin = req_data.get('admin', False)
    password = req_data.get('password')

    if email and not mail.validate(email):
        raise RequestError(
            '{} is an invalid email address.'
            .format(email))

    # insert
    if not new_org_user:
        if not all([email, password, name]):
            raise RequestError(
                'An email, password, and name are required to create a User.')
        
        new_org_user = User(
            email=email,
            password=password,
            name=name,
            admin=admin)
        org.users.append(new_org_user)
        db.session.add(org)

    # ensure the active user can edit this Org
    elif new_org_user.id not in org.user_ids:
        raise ForbiddenError(
            "You are not allowed to access this Org.")
    
    # update
    if name:
        new_org_user.name = name
    if email:
        new_org_user.email = email 
    if admin:
        new_org_user.admin = admin 
    if password:
        new_org_user.set_password(password)

    new_org_user.admin = admin
    db.session.add(new_org_user)
    db.session.commit()
    return jsonify(new_org_user)
Ejemplo n.º 43
0
def org_create(user):

    req_data = request_data()

    if not user.super_user:
        raise ForbiddenError(
            'You must be the super user to create an Org')

    if 'name' not in req_data \
       or 'timezone' not in req_data:
        raise RequestError(
            "An Org requires a 'name' and 'timezone")

    org = Org.query\
        .filter_by(name=req_data['name'])\
        .first()

    # if the org doesnt exist, create it.
    if org:
        raise RequestError(
            "Org '{}' already exists"
            .format(req_data['name']))

    # add the requesting user to the org
    org = Org(
        name=req_data['name'],
        timezone=req_data['timezone']
    )
    org.users.append(user)
    db.session.add(org)
    db.session.commit()

    # add default tags
    for tag in load_default_tags():
        tag['org_id'] = org.id
        t = Tag(**tag)
        db.session.add(t)

    # add default recipes
    for recipe in load_default_recipes():

        # fetch it's sous chef.
        sous_chef_slug = recipe.pop('sous_chef')
        if not sous_chef_slug:
            raise RecipeSchemaError(
                "Default recipe '{}' is missing a 'sous_chef' slug."
                .format(recipe.get('slug', '')))

        sc = SousChef.query\
            .filter_by(slug=sous_chef_slug)\
            .first()

        if not sc:
            raise RecipeSchemaError(
                '"{}" is not a valid SousChef slug or the '
                'SousChef does not yet exist.'
                .format(sous_chef_slug))

        # validate the recipe
        recipe = recipe_schema.validate(recipe, sc.to_dict())

        # fill in relations
        recipe['user_id'] = user.id
        recipe['org_id'] = org.id

        # add to database
        r = Recipe(sc, **recipe)
        db.session.add(r)
        db.session.commit()

        # if the recipe creates metrics create them here.
        if 'metrics' in sc.creates:
            for name, params in sc.metrics.items():
                m = Metric(
                    name=name,
                    recipe_id=r.id,
                    org_id=org.id,
                    **params)
                db.session.add(m)
    db.session.commit()
    return jsonify(org)
Ejemplo n.º 44
0
def org_create(user):

    req_data = request_data()

    if not user.super_user:
        raise ForbiddenError('You must be the super user to create an Org')

    if 'name' not in req_data \
       or 'timezone' not in req_data:
        raise RequestError("An Org requires a 'name' and 'timezone")

    org = Org.query\
        .filter_by(name=req_data['name'])\
        .first()

    # if the org doesnt exist, create it.
    if org:
        raise RequestError("Org '{}' already exists".format(req_data['name']))

    # add the requesting user to the org
    org = Org(name=req_data['name'], timezone=req_data['timezone'])
    org.users.append(user)
    db.session.add(org)
    db.session.commit()

    # add default tags
    for tag in load_default_tags():
        tag['org_id'] = org.id
        t = Tag(**tag)
        db.session.add(t)

    # add default recipes
    for recipe in load_default_recipes():

        # fetch it's sous chef.
        sous_chef_slug = recipe.pop('sous_chef')
        if not sous_chef_slug:
            raise RecipeSchemaError(
                "Default recipe '{}' is missing a 'sous_chef' slug.".format(
                    recipe.get('slug', '')))

        sc = SousChef.query\
            .filter_by(slug=sous_chef_slug)\
            .first()

        if not sc:
            raise RecipeSchemaError(
                '"{}" is not a valid SousChef slug or the '
                'SousChef does not yet exist.'.format(sous_chef_slug))

        # validate the recipe
        recipe = recipe_schema.validate(recipe, sc.to_dict())

        # fill in relations
        recipe['user_id'] = user.id
        recipe['org_id'] = org.id

        # add to database
        r = Recipe(sc, **recipe)
        db.session.add(r)
        db.session.commit()

        # if the recipe creates metrics create them here.
        if 'metrics' in sc.creates:
            for name, params in sc.metrics.items():
                m = Metric(name=name, recipe_id=r.id, org_id=org.id, **params)
                db.session.add(m)
    db.session.commit()
    return jsonify(org)