Python flask.g 模块,auth() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用flask.g.auth()

项目:SwarmOps    作者:staugur    | 项目源码 | 文件源码
def before_request():
    g.startTime = time.time()
    g.requestId = gen_requestId()
    g.sessionId = request.cookies.get("sessionId", "")
    g.username  = request.cookies.get("username", "")
    g.expires   = request.cookies.get("time", "")
    g.auth      = isLogged_in('.'.join([ g.username, g.expires, g.sessionId ]))
    g.swarm     = swarm
    g.service   = ServiceManager(ActiveSwarm=g.swarm.getActive)
    g.node      = NodeManager(ActiveSwarm=g.swarm.getActive)
    g.network   = NetworkManager(ActiveSwarm=g.swarm.getActive)
    g.registry  = RegistryManager(Registry=REGISTRY)
    g.sysInfo   = {"Version": __version__, "Author": __author__, "Email": __email__, "Doc": __doc__}
    logger.info("Start Once Access, and this requestId is %s, auth(%s)" %(g.requestId, g.auth))
    app.logger.info(app.url_map)

#?????????????????????requestId????????????API, ??????.
项目:SwarmOps    作者:staugur    | 项目源码 | 文件源码
def sso():
    ticket = request.args.get("ticket")
    if not ticket:
        logger.info("sso ticket get failed")
        return """<html><head><title>?????……</title><meta http-equiv="Content-Language" content="zh-CN"><meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf8"><meta http-equiv="refresh" content="1.0;url={}"></head><body></b>?????, ????, ?????!<b></body></html>""".format(url_for("auth.logout"))
    logger.info("ticket: %s" %ticket)
    username, expires, sessionId = ticket.split('.')
    if username and username not in SSO["SSO.AllowedUserList"]:
        logger.info("SwarmOps is not allowed to login with {}.".format(username))
        return redirect(url_for("auth.sso"))
    if expires == 'None':
        UnixExpires = None
    else:
        UnixExpires = datetime.datetime.strptime(expires,"%Y-%m-%d")
    resp = make_response(redirect(url_for("index")))
    resp.set_cookie(key='logged_in', value="yes", expires=UnixExpires)
    resp.set_cookie(key='username',  value=username, expires=UnixExpires)
    resp.set_cookie(key='sessionId', value=sessionId, expires=UnixExpires)
    resp.set_cookie(key='time', value=expires, expires=UnixExpires)
    resp.set_cookie(key='Azone', value="sso", expires=UnixExpires)
    return resp
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_token_from_request():
    """
    Pulls the auth token from the request headers.

    :return:  Auth token if it exists, else None.
    """
    token = None
    try:
        header = request.headers.get('Authorization')
        token = header.split()[1] if header is not None else request.cookies.get('auth_token')
    except (AttributeError, IndexError):
        pass

    if token is None:
        raise TokenException('Unable to get token from request.')

    return token
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_retailer(retailer_id):
    """
    Retrieve a single retailer object.

    :param retailer_id:   The retailer's id

    :return: {
        "id": "123",
        "address": {Address}
    }

    """
    check_null_input((retailer_id, 'retailer to retrieve'))

    retailer = retailer_service.get_retailer(token=g.auth['loopback_token'],
                                             retailer_id=retailer_id)
    return Response(retailer,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_products():
    """
    Get all product objects.

    :return: [{
        "id": "I9",
        "name": "Milk",
        "supplier": "Abbott"
    }, {...}]

    """

    products = product_service.get_products(token=g.auth['loopback_token'])
    return Response(products,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_distribution_centers():
    """
    Get all distribution center objects.

    :return: [{
        "id": "D2",
        "address": {Address},
        "contact": {Contact}
    }, {...}]

    """

    distribution_centers = distribution_center_service.get_distribution_centers(token=g.auth['loopback_token'])
    return Response(distribution_centers,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_distribution_center(dc_id):
    """
    Retrieve a single distribution center object.

    :param dc_id:   The distribution center's id

    :return: {
        "id": "D2",
        "address": {Address},
        "contact": {Contact}
    }

    """
    check_null_input((dc_id, 'distribution center to retrieve'))

    distribution_center = distribution_center_service.get_distribution_center(token=g.auth['loopback_token'],
                                                                              dc_id=dc_id)
    return Response(distribution_center,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_distribution_center_inventory(dc_id):
    """
    Retrieve all inventory at the specified distribution center.

    :param dc_id:   The distribution center's id

    :return: [{
        "id": "123",
        "quantity": 10,
        "productId": "123",
        "locationId": "123",
        "locationType": "DistributionCenter"
    }, {...}]
    """
    check_null_input((dc_id, 'distribution center whose inventory you want to retrieve'))

    inventory = distribution_center_service.get_distribution_center_inventory(token=g.auth['loopback_token'],
                                                                              dc_id=dc_id)
    return Response(inventory,
                    status=200,
                    mimetype='application/json')
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def _get_instance(auth, owner, package_name, package_hash):
    instance = (
        Instance.query
        .filter_by(hash=package_hash)
        .options(undefer('contents'))  # Contents is deferred by default.
        .join(Instance.package)
        .filter_by(owner=owner, name=package_name)
        .join(Package.access)
        .filter(Access.user.in_([auth.user, PUBLIC]))
        .one_or_none()
    )
    if instance is None:
        raise ApiException(
            requests.codes.not_found,
            "Package hash does not exist"
        )
    return instance
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def user_packages(owner):
    packages = (
        db.session.query(Package, sa.func.max(Access.user == PUBLIC))
        .filter_by(owner=owner)
        .join(Package.access)
        .filter(Access.user.in_([g.auth.user, PUBLIC]))
        .group_by(Package.id)
        .order_by(Package.name)
        .all()
    )

    return dict(
        packages=[
            dict(
                name=package.name,
                is_public=is_public
            )
            for package, is_public in packages
        ]
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def version_list(owner, package_name):
    package = _get_package(g.auth, owner, package_name)

    versions = (
        db.session.query(Version, Instance)
        .filter_by(package=package)
        .join(Version.instance)
        .all()
    )

    sorted_versions = sorted(versions, key=lambda row: row.Version.sort_key())

    return dict(
        versions=[
            dict(
                version=version.user_version,
                hash=instance.hash
            ) for version, instance in sorted_versions
        ]
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def tag_list(owner, package_name):
    package = _get_package(g.auth, owner, package_name)

    tags = (
        db.session.query(Tag, Instance)
        .filter_by(package=package)
        .order_by(Tag.tag)
        .join(Tag.instance)
        .all()
    )

    return dict(
        tags=[
            dict(
                tag=tag.tag,
                hash=instance.hash
            ) for tag, instance in tags
        ]
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def access_get(owner, package_name, user):
    if g.auth.user != owner:
        raise ApiException(
            requests.codes.forbidden,
            "Only the package owner can view access"
        )

    access = (
        db.session.query(Access)
        .filter_by(user=user)
        .join(Access.package)
        .filter_by(owner=owner, name=package_name)
        .one_or_none()
    )
    if access is None:
        raise PackageNotFoundException(owner, package_name)

    return dict()
项目:fallball-connector    作者:ingrammicro    | 项目源码 | 文件源码
def get_reseller_info():
    reseller_id = request.headers.get('Aps-Instance-Id')
    is_new = g.endpoint == ApplicationList.__name__.lower()
    reseller_name = set_name_for_reseller(reseller_id)
    oauth = get_oauth()
    return ResellerInfo(id=reseller_id, name=reseller_name, is_new=is_new, auth=oauth)
项目:fallball-connector    作者:ingrammicro    | 项目源码 | 文件源码
def before_request():
    g.log = dict()
    g.log['out'] = list()
    g.log['request'] = log_request(request)

    g.endpoint = request.endpoint
    if request.blueprint:
        g.endpoint = g.endpoint[len(request.blueprint):].lstrip('.')

    reseller_info = get_reseller_info()
    g.reseller_name = reseller_info.name
    g.company_name = 'N/A'

    if not reseller_info.name:
        allow_public_endpoints_only()
        return

    if not check_oauth_signature(request):
        abort(401)

    g.auth = reseller_info.auth

    g.reseller = Reseller(reseller_info.name, reseller_info.id, None)
    g.reseller.refresh()

    if not g.reseller.token and not reseller_info.is_new:
        abort(403)
项目:SwarmOps    作者:staugur    | 项目源码 | 文件源码
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not g.auth:
            return redirect(url_for('auth.login'))
        return f(*args, **kwargs)
    return decorated_function
项目:SwarmOps    作者:staugur    | 项目源码 | 文件源码
def login():
    if g.auth:
        return redirect(url_for("index"))
    else:
        query = {"sso": True,
           "sso_r": SpliceURL.Modify(request.url_root, "/sso/").geturl,
           "sso_p": SSO["SSO.PROJECT"],
           "sso_t": md5("%s:%s" %(SSO["SSO.PROJECT"], SpliceURL.Modify(request.url_root, "/sso/").geturl))
        }
        SSOLoginURL = SpliceURL.Modify(url=SSO["SSO.URL"], path="/login/", query=query).geturl
        logger.info("User request login to SSO: %s" %SSOLoginURL)
        return redirect(SSOLoginURL)
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def logged_in(func, *args, **kwargs):
    if g.auth is None:
        raise AuthorizationException('No existing session.')
    else:
        return func(*args, **kwargs)
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_retailers():
    """
    Get all retailer objects.

    :return: [{
        "id": "123",
        "address": {Address}
    }, {...}]

    """

    retailers = retailer_service.get_retailers(token=g.auth['loopback_token'])
    return Response(retailers,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_retailer_shipments(retailer_id):
    """
    Retrieve all shipments heading to the specified retailer.

    :param retailer_id:   The retailer's id

    :return: [{
        "id": "123",
        "status": "SHIPPED",
        "createdAt": "2015-11-05T22:00:51.692765",
        "updatedAt": "2015-11-08T22:00:51.692765",
        "deliveredAt": "2015-11-08T22:00:51.692765",
        "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",
        "currentLocation": {Address},
        "fromId": "D2",
        "toId:": "123"
    }, {...}]

    """
    check_null_input((retailer_id, 'retailer whose shipments you want to retrieve'))
    status = request.args.get('status')

    shipments = shipment_service.get_shipments(token=g.auth['loopback_token'],
                                               retailer_id=retailer_id,
                                               status=status)
    return Response(shipments,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_recommendations():
    """
    Return recommendations.

    :return: the list of recommendations

    """
    recommendations = weather_service.get_recommendations(g.auth['guid'])
    return Response(recommendations,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def acknowledge_recommendation():
    """
    Acknowledge a recommendation.
    """
    body = get_json_data(request)

    response = weather_service.acknowledge_recommendation(g.auth['guid'], body.get('id'))
    return Response(response,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def trigger_simulation():
    """
    Trigger a simulation for the given demo.
    """
    response = weather_service.trigger_simulation(g.auth['guid'])
    return Response(response,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_shipments():
    """
    Get all shipment objects.

    :return: [{
        "id": "123",
        "status": "SHIPPED",
        "createdAt": "2015-11-05T22:00:51.692765",
        "updatedAt": "2015-11-08T22:00:51.692765",
        "deliveredAt": "2015-11-08T22:00:51.692765",
        "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",
        "currentLocation": {Address},
        "fromId": "D2",
        "toId:": "123"
    }, {...}]

    """

    status = request.args.get('status')
    retailer_id = request.args.get('rid')
    dc_id = request.args.get('did')
    shipments = shipment_service.get_shipments(token=g.auth['loopback_token'],
                                               status=status,
                                               retailer_id=retailer_id,
                                               dc_id=dc_id)
    return Response(shipments,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def get_shipment(shipment_id):
    """
    Retrieve a single shipment object.

    :param shipment_id:   The shipment's id

    :return: {
        "id": "123",
        "status": "SHIPPED",
        "createdAt": "2015-11-05T22:00:51.692765",
        "updatedAt": "2015-11-08T22:00:51.692765",
        "deliveredAt": "2015-11-08T22:00:51.692765",
        "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",
        "currentLocation": {Address},
        "fromId": "123",
        "toId:": "123",
        "items": [{LineItem}]
    }

    """
    include_items = request.args.get('include_items')
    check_null_input((shipment_id, 'shipment to retrieve'))

    shipment = shipment_service.get_shipment(token=g.auth['loopback_token'],
                                             shipment_id=shipment_id,
                                             include_items=include_items)

    return Response(shipment,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def delete_shipment(shipment_id):
    """
    Retrieve a single shipment object.

    :param shipment_id:   The shipment's id
    :return:

    """
    check_null_input((shipment_id, 'shipment to delete'))

    shipment_service.delete_shipment(token=g.auth['loopback_token'], shipment_id=shipment_id)
    return '', 204
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def update_shipment(shipment_id):
    """
    Update a single shipment object.

    :param shipment_id:   The shipment's id
    :param  {
        "id": "123",
        "status": "SHIPPED",
        "createdAt": "2015-11-05T22:00:51.692765",
        "updatedAt": "2015-11-08T22:00:51.692765",
        "deliveredAt": "2015-11-08T22:00:51.692765",
        "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",
        "currentLocation": {Address},
        "fromId": "D2",
        "toId:": "123"
    }

    :return: {
        "id": "123",
        "status": "SHIPPED",
        "createdAt": "2015-11-05T22:00:51.692765",
        "updatedAt": "2015-11-08T22:00:51.692765",
        "deliveredAt": "2015-11-08T22:00:51.692765",
        "estimatedTimeOfArrival": "2015-11-07T22:00:51.692765",
        "currentLocation": {Address},
        "fromId": "D2",
        "toId:": "123"
    }

    """
    check_null_input((shipment_id, 'shipment to update'))

    updated_shipment = get_json_data(request)
    shipment = shipment_service.update_shipment(token=g.auth['loopback_token'],
                                                shipment_id=shipment_id, shipment=updated_shipment)
    return Response(shipment,
                    status=200,
                    mimetype='application/json')
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def setup_auth_from_request():
    """
    Get the Auth data from the request headers and store on the g
    object for later use.
    """
    try:
        token = web_utils.get_token_from_request()
        if token is not None:
            g.auth = web_utils.detokenize(token)
    except (TokenException, ResourceDoesNotExistException):
        g.auth = None
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def deauthenticate(token):
    """
    Logout the current user
    :param token  Current web token
    :return:
    """
    request_token = web_utils.get_token_from_request()
    # Only allow deletion of a web token if the token belongs to the current user
    if request_token == token:
        user_service.logout(token=g.auth['loopback_token'])
    return '', 204
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
def load_admin_data():
    """
    Load all data relative to the currently logged in user

    :return: {
        "shipments": [{Shipments}],
        "retailers": [{Retailer}],
        "distribution_centers": [{Distribution Center}]
    }
    """

    # Specify functions and corresponding arguments to call to retrieve ERP data
    loopback_token = g.auth['loopback_token']
    erp_calls = [(shipment_service.get_shipments, loopback_token),
                 (distribution_center_service.get_distribution_centers, loopback_token),
                 (retailer_service.get_retailers, loopback_token)]
    pool = Pool(processes=len(erp_calls))

    # Asynchronously make calls and then wait on all processes to finish
    try:
        results = pool.map(async_helper, erp_calls)
    except Exception as e:
        raise APIException('Error retrieving admin data view', internal_details=str(e))
    pool.close()
    pool.join()

    # Send back serialized results to client
    return Response(json.dumps({
                        "shipments": json.loads(results[0]),
                        "distribution-centers": json.loads(results[1]),
                        "retailers": json.loads(results[2])
                    }),
                    status=200,
                    mimetype='application/json')
项目:Breezes    作者:staugur    | 项目源码 | 文件源码
def before_request():
    g.auth      = True
    g.requestId = gen_requestId()
    g.registries= registries
    g.registry  = ApiRegistryManager(ActiveRegistry=g.registries.getActive)
    g.sysInfo   = {"Version": __version__, "Author": __author__, "Email": __email__, "Doc": __doc__}
    logger.info("Start Once Access, and this requestId is {}".format(g.requestId))

#?????????????????????requestId????????????API, ??????.
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def _get_package(auth, owner, package_name):
    """
    Helper for looking up a package and checking permissions.
    Only useful for *_list functions; all others should use more efficient queries.
    """
    package = (
        Package.query
        .filter_by(owner=owner, name=package_name)
        .join(Package.access)
        .filter(Access.user.in_([auth.user, PUBLIC]))
        .one_or_none()
    )
    if package is None:
        raise PackageNotFoundException(owner, package_name, auth.user is not PUBLIC)
    return package
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def _mp_track(**kwargs):
    if g.user_agent['browser']['name'] == 'QuiltCli':
        source = 'cli'
    else:
        source = 'web'

    # Use the user ID if the user is logged in; otherwise, let MP use the IP address.
    distinct_id = g.auth.user if g.auth.user != PUBLIC else None

    # Try to get the ELB's forwarded IP, and fall back to the actual IP (in dev).
    ip_addr = request.headers.get('x-forwarded-for', request.remote_addr)

    # Set common attributes sent with each event. kwargs cannot override these.
    all_args = dict(
        kwargs,
        time=time.time(),
        ip=ip_addr,
        user=g.auth.user,
        source=source,
        browser_name=g.user_agent['browser']['name'],
        browser_version=g.user_agent['browser']['version'],
        platform_name=g.user_agent['platform']['name'],
        platform_version=g.user_agent['platform']['version'],
        deployment_id=DEPLOYMENT_ID,
    )

    mp.track(distinct_id, MIXPANEL_EVENT, all_args)
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def _get_or_create_customer():
    assert HAVE_PAYMENTS, "Payments are not enabled"
    assert g.auth.user != PUBLIC

    db_customer = Customer.query.filter_by(id=g.auth.user).one_or_none()

    if db_customer is None:
        try:
            # Insert a placeholder with no Stripe ID just to lock the row.
            db_customer = Customer(id=g.auth.user)
            db.session.add(db_customer)
            db.session.flush()
        except IntegrityError:
            # Someone else just created it, so look it up.
            db.session.rollback()
            db_customer = Customer.query.filter_by(id=g.auth.user).one()
        else:
            # Create a new customer.
            plan = PaymentPlan.FREE.value
            customer = stripe.Customer.create(
                email=g.auth.email,
                description=g.auth.user,
            )
            stripe.Subscription.create(
                customer=customer.id,
                plan=plan,
            )

            db_customer.stripe_customer_id = customer.id
            db.session.commit()

    customer = stripe.Customer.retrieve(db_customer.stripe_customer_id)
    assert customer.subscriptions.total_count == 1
    return customer
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def package_get(owner, package_name, package_hash):
    subpath = request.args.get('subpath')

    instance = _get_instance(g.auth, owner, package_name, package_hash)
    contents = json.loads(instance.contents, object_hook=decode_node)

    subnode = contents
    for component in subpath.split('/') if subpath else []:
        try:
            subnode = subnode.children[component]
        except (AttributeError, KeyError):
            raise ApiException(requests.codes.not_found, "Invalid subpath: %r" % component)

    all_hashes = set(find_object_hashes(subnode))

    urls = {
        blob_hash: _generate_presigned_url(S3_GET_OBJECT, owner, blob_hash)
        for blob_hash in all_hashes
    }

    _mp_track(
        type="install",
        package_owner=owner,
        package_name=package_name,
        subpath=subpath,
    )

    return dict(
        contents=contents,
        urls=urls,
        created_by=instance.created_by,
        created_at=_utc_datetime_to_ts(instance.created_at),
        updated_by=instance.updated_by,
        updated_at=_utc_datetime_to_ts(instance.updated_at),
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def package_preview(owner, package_name, package_hash):
    instance = _get_instance(g.auth, owner, package_name, package_hash)
    contents = json.loads(instance.contents, object_hook=decode_node)

    readme = contents.children.get('README')
    if isinstance(readme, FileNode):
        assert len(readme.hashes) == 1
        readme_url = _generate_presigned_url(S3_GET_OBJECT, owner, readme.hashes[0])
    else:
        readme_url = None

    contents_preview = _generate_preview(contents)

    _mp_track(
        type="preview",
        package_owner=owner,
        package_name=package_name,
    )

    return dict(
        preview=contents_preview,
        readme_url=readme_url,
        created_by=instance.created_by,
        created_at=_utc_datetime_to_ts(instance.created_at),
        updated_by=instance.updated_by,
        updated_at=_utc_datetime_to_ts(instance.updated_at),
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def package_list(owner, package_name):
    package = _get_package(g.auth, owner, package_name)
    instances = (
        Instance.query
        .filter_by(package=package)
    )

    return dict(
        hashes=[instance.hash for instance in instances]
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def package_delete(owner, package_name):
    if g.auth.user != owner:
        raise ApiException(requests.codes.forbidden,
                           "Only the package owner can delete packages.")

    package = _get_package(g.auth, owner, package_name)

    db.session.delete(package)
    db.session.commit()

    return dict()
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def version_put(owner, package_name, package_version):
    # TODO: Write access for collaborators.
    if g.auth.user != owner:
        raise ApiException(
            requests.codes.forbidden,
            "Only the package owner can create versions"
        )

    user_version = package_version
    package_version = normalize_version(package_version)

    data = request.get_json()
    package_hash = data['hash']

    instance = (
        Instance.query
        .filter_by(hash=package_hash)
        .join(Instance.package)
        .filter_by(owner=owner, name=package_name)
        .one_or_none()
    )

    if instance is None:
        raise ApiException(requests.codes.not_found, "Package hash does not exist")

    version = Version(
        package_id=instance.package_id,
        version=package_version,
        user_version=user_version,
        instance=instance
    )

    try:
        db.session.add(version)
        db.session.commit()
    except IntegrityError:
        raise ApiException(requests.codes.conflict, "Version already exists")

    return dict()
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def version_get(owner, package_name, package_version):
    package_version = normalize_version(package_version)
    package = _get_package(g.auth, owner, package_name)

    instance = (
        Instance.query
        .join(Instance.versions)
        .filter_by(package=package, version=package_version)
        .one_or_none()
    )

    if instance is None:
        raise ApiException(
            requests.codes.not_found,
            "Version %s does not exist" % package_version
        )

    _mp_track(
        type="get_hash",
        package_owner=owner,
        package_name=package_name,
        package_version=package_version,
    )

    return dict(
        hash=instance.hash,
        created_by=instance.created_by,
        created_at=_utc_datetime_to_ts(instance.created_at),
        updated_by=instance.updated_by,
        updated_at=_utc_datetime_to_ts(instance.updated_at),
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def tag_get(owner, package_name, package_tag):
    package = _get_package(g.auth, owner, package_name)

    instance = (
        Instance.query
        .join(Instance.tags)
        .filter_by(package=package, tag=package_tag)
        .one_or_none()
    )

    if instance is None:
        raise ApiException(
            requests.codes.not_found,
            "Tag %r does not exist" % package_tag
        )

    _mp_track(
        type="get_hash",
        package_owner=owner,
        package_name=package_name,
        package_tag=package_tag,
    )

    return dict(
        hash=instance.hash,
        created_by=instance.created_by,
        created_at=_utc_datetime_to_ts(instance.created_at),
        updated_by=instance.updated_by,
        updated_at=_utc_datetime_to_ts(instance.updated_at),
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def access_delete(owner, package_name, user):
    if g.auth.user != owner:
        raise ApiException(
            requests.codes.forbidden,
            "Only the package owner can revoke access"
        )

    if user == owner:
        raise ApiException(
            requests.codes.forbidden,
            "Cannot revoke the owner's access"
        )

    if HAVE_PAYMENTS and user == PUBLIC:
        customer = _get_or_create_customer()
        plan = _get_customer_plan(customer)
        if plan == PaymentPlan.FREE:
            raise ApiException(
                requests.codes.payment_required,
                "Insufficient permissions. " +
                "Upgrade your plan to create private packages: https://quiltdata.com/profile."
            )

    access = (
        Access.query
        .with_for_update()
        .filter_by(user=user)
        .join(Access.package)
        .filter_by(owner=owner, name=package_name)
        .one_or_none()
    )
    if access is None:
        raise PackageNotFoundException(owner, package_name)

    db.session.delete(access)
    db.session.commit()
    return dict()
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def access_list(owner, package_name):
    accesses = (
        Access.query
        .join(Access.package)
        .filter_by(owner=owner, name=package_name)
    )

    can_access = [access.user for access in accesses]
    is_collaborator = g.auth.user in can_access
    is_public = PUBLIC in can_access

    if is_public or is_collaborator:
        return dict(users=can_access)
    else:
        raise PackageNotFoundException(owner, package_name)
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def search():
    query = request.args.get('q', '')
    keywords = query.split()

    if len(keywords) > 5:
        # Let's not overload the DB with crazy queries.
        raise ApiException(requests.codes.bad_request, "Too many search terms (max is 5)")

    filter_list = [
        sa.func.instr(
            sa.sql.collate(sa.func.concat(Package.owner, '/', Package.name), UTF8_GENERAL_CI),
            keyword
        ) > 0
        for keyword in keywords
    ]

    results = (
        db.session.query(Package, sa.func.max(Access.user == PUBLIC))
        .filter(sa.and_(*filter_list))
        .join(Package.access)
        .filter(Access.user.in_([g.auth.user, PUBLIC]))
        .group_by(Package.id)
        .order_by(
            sa.sql.collate(Package.owner, UTF8_GENERAL_CI),
            sa.sql.collate(Package.name, UTF8_GENERAL_CI)
        )
        .all()
    )

    return dict(
        packages=[
            dict(
                owner=package.owner,
                name=package.name,
                is_public=is_public,
            ) for package, is_public in results
        ]
    )
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def invitation_user_list():
    invitations = (
        db.session.query(Invitation, Package)
        .filter_by(email=g.auth.email)
        .join(Invitation.package)
        .all()
    )
    return dict(invitations=[dict(invitation_id=invite.id,
                                  owner=package.owner,
                                  package=package.name,
                                  email=invite.email,
                                  invited_at=invite.invited_at)
                             for invite, package in invitations])
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def invitation_package_list(owner, package_name):
    package = _get_package(g.auth, owner, package_name)
    invitations = (
        Invitation.query
        .filter_by(package_id=package.id)
    )

    return dict(invitations=[dict(invitation_id=invite.id,
                                  owner=package.owner,
                                  package=package.name,
                                  email=invite.email,
                                  invited_at=invite.invited_at)
                             for invite in invitations])
项目:fallball-connector    作者:ingrammicro    | 项目源码 | 文件源码
def send_request(method, path, body=None, transaction=True, impersonate_as=None, retry_num=10):
        oa_uri = request.headers.get('aps-controller-uri')
        url = urljoin(oa_uri, path)

        headers = {'Content-Type': 'application/json'}
        if impersonate_as:
            headers['aps-resource-id'] = impersonate_as
        if transaction and request.headers.get('aps-transaction-id'):
            headers['aps-transaction-id'] = request.headers.get('aps-transaction-id')

        data = None if body is None else json.dumps(body)

        retry_num = retry_num if retry_num > 0 else 1

        with Session() as s:
            prepared = Request(
                method=method,
                url=url,
                data=data,
                headers=headers,
                auth=g.auth
            ).prepare()

            while retry_num > 0:
                retry_num -= 1
                try:
                    g.log['out'].append(dict(request=None, response=None))
                    g.log['out'][-1]['request'] = log_outgoing_request(prepared)
                    resp = s.send(prepared, timeout=OA.request_timeout, verify=False)
                    g.log['out'][-1]['response'] = log_outgoing_response(resp)
                except requests.exceptions.Timeout:
                    err = ErrorResponse(None, 'Request to OA timed out. '
                                              'Timeout: {}'.format(OA.request_timeout))
                    raise OACommunicationException(err)
                except Exception as e:
                    err = ErrorResponse(None, str(e))
                    raise OACommunicationException(err)

                if resp.status_code == 200:
                    return resp.json()
                elif resp.status_code != 400:
                    raise OACommunicationException(resp)

            raise OACommunicationException(resp)
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def api(require_login=True, schema=None):
    """
    Decorator for API requests.
    Handles auth and adds the username as the first argument.
    """
    if schema is not None:
        Draft4Validator.check_schema(schema)
        validator = Draft4Validator(schema)
    else:
        validator = None

    def innerdec(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            g.auth = Auth(PUBLIC, None)

            user_agent_str = request.headers.get('user-agent', '')
            g.user_agent = httpagentparser.detect(user_agent_str, fill_none=True)

            if validator is not None:
                try:
                    validator.validate(request.get_json(cache=True))
                except ValidationError as ex:
                    raise ApiException(requests.codes.bad_request, ex.message)

            auth = request.headers.get(AUTHORIZATION_HEADER)
            g.auth_header = auth
            if auth is None:
                if require_login:
                    raise ApiException(requests.codes.unauthorized, "Not logged in")
            else:
                headers = {
                    AUTHORIZATION_HEADER: auth
                }
                try:
                    resp = requests.get(OAUTH_USER_API, headers=headers)
                    resp.raise_for_status()

                    data = resp.json()
                    # TODO(dima): Generalize this.
                    user = data.get('current_user', data.get('login'))
                    assert user
                    email = data['email']

                    g.auth = Auth(user, email)
                except requests.HTTPError as ex:
                    if resp.status_code == requests.codes.unauthorized:
                        raise ApiException(
                            requests.codes.unauthorized,
                            "Invalid credentials"
                        )
                    else:
                        raise ApiException(requests.codes.server_error, "Server error")
                except (ConnectionError, requests.RequestException) as ex:
                    raise ApiException(requests.codes.server_error, "Server error")
            return f(*args, **kwargs)
        return wrapper
    return innerdec
项目:quilt    作者:quiltdata    | 项目源码 | 文件源码
def tag_put(owner, package_name, package_tag):
    # TODO: Write access for collaborators.
    if g.auth.user != owner:
        raise ApiException(
            requests.codes.forbidden,
            "Only the package owner can modify tags"
        )

    data = request.get_json()
    package_hash = data['hash']

    instance = (
        Instance.query
        .filter_by(hash=package_hash)
        .join(Instance.package)
        .filter_by(owner=owner, name=package_name)
        .one_or_none()
    )

    if instance is None:
        raise ApiException(requests.codes.not_found, "Package hash does not exist")

    # Update an existing tag or create a new one.
    tag = (
        Tag.query
        .with_for_update()
        .filter_by(package_id=instance.package_id, tag=package_tag)
        .one_or_none()
    )
    if tag is None:
        tag = Tag(
            package_id=instance.package_id,
            tag=package_tag,
            instance=instance
        )
        db.session.add(tag)
    else:
        tag.instance = instance

    db.session.commit()

    return dict()