예제 #1
0
파일: app.py 프로젝트: USGS-EROS/espa-web
def login():
    destination = request.args.get('next')
    if request.method == 'POST':
        resp_json = api_get("/user", uauth=(request.form['username'], request.form['password']))
        if 'username' in resp_json:
            session['logged_in'] = True
            resp_json['wurd'] = request.form['password']
            session['user'] = User(**resp_json)
            update_status_details()
            logger.info("User %s logged in\n" % session['user'].username)
            # send the user back to their
            # originally requested destination
            if destination and destination != 'None':
                return redirect(destination)
            else:
                return redirect(url_for('index'))
        else:
            logger.info("**** Failed user login %s \n" % request.form['username'])
            flash(format_errors(resp_json['msg']), 'error')
            _status = 401
    else:
        _status = 200
        if 'user' not in session:
            session['user'] = None

    in_ops = 'ESPA_ENV' in os.environ and os.environ['ESPA_ENV'] == 'ops'
    explorer = "http://earthexplorer.usgs.gov" if in_ops else "http://eedevmast.cr.usgs.gov"
    reg_host = "https://ers.cr.usgs.gov" if in_ops else "http://ersdevmast.cr.usgs.gov"

    return render_template('login.html', next=destination,
                           earthexplorer=explorer,
                           register_user=reg_host+"/register",
                           forgot_login=reg_host+"/password/request"), _status
예제 #2
0
파일: app.py 프로젝트: govtmirror/espa-web
def new_external_order():
    if request.method == 'POST':
        data = request.form.to_dict()
        try:
            scenelist = data['input_product_list']
            _u, _p = base64.b64decode(data['user']).split(':')
            resp_json = api_get('/user', uauth=(_u, _p))
            if 'username' in resp_json:
                session['logged_in'] = True
                resp_json['wurd'] = _p
                session['user'] = User(**resp_json)
            else:
                logger.info(
                    '*** Failed external order user login: {}'.format(_u))
                return jsonify({'msg': 'user auth failed'}), 401
        except KeyError:
            return jsonify({
                'error':
                "'input_product_list' and 'user' fields are required"
            }), 401
        except Exception as e:
            logger.info(
                "*** espa-web exception - problem parsing external order request. message: {}"
                .format(e.message))
            return jsonify({'error': 'problem parsing request'}), 400
    else:
        # GET redirect from ESPA after order validation
        scenelist = session['ipl']

    return render_template('new_order.html',
                           form_action=url_for('submit_order'),
                           scenelist=scenelist)
예제 #3
0
파일: app.py 프로젝트: USGS-EROS/espa-web
def new_external_order():
    if request.method == 'POST':
        data = request.form.to_dict()
        try:
            scenelist = data['input_product_list']
            _u, _p = base64.b64decode(data['user']).split(':')
            resp_json = api_get('/user', uauth=(_u, _p))
            if 'username' in resp_json:
                session['logged_in'] = True
                resp_json['wurd'] = _p
                session['user'] = User(**resp_json)
            else:
                logger.info('*** Failed external order user login: {}'.format(_u))
                return jsonify({'msg': 'user auth failed'}), 401
        except KeyError:
            return jsonify({'error': "'input_product_list' and 'user' fields are required"}), 401
        except Exception as e:
            logger.info("*** espa-web exception - problem parsing external order request. message: {}".format(e.message))
            return jsonify({'error': 'problem parsing request'}), 400
    else:
        # GET redirect from ESPA after order validation
        scenelist = session['ipl']

    return render_template('new_order.html',
                           form_action=url_for('submit_order'),
                           scenelist=scenelist)
예제 #4
0
파일: app.py 프로젝트: djzelenak/espa-web
def cancel_order(orderid):
    payload = {'orderid': orderid, 'status': 'cancelled'}
    response = api_up('/order', json=payload, verb='put')
    if response.get('orderid') == orderid:
        flash("Order cancelled successfully!")
        logger.info(
            "order cancellation for user {0} ({1})\n\n orderid: {2}".format(
                session['user'].username, request.remote_addr, response))
    return ''
예제 #5
0
파일: app.py 프로젝트: govtmirror/espa-web
def logout():
    logger.info("Logging out user %s \n" % session['user'].username)
    for item in [
            'logged_in', 'user', 'system_message_body', 'system_message_title',
            'stat_products_complete_24_hrs', 'stat_backlog_depth',
            'stat_onorder_depth'
    ]:
        session.pop(item, None)
    return redirect(url_for('login'))
예제 #6
0
파일: app.py 프로젝트: djzelenak/espa-web
def espa_session_clear():
    if 'user' not in session:
        return
    logger.info("Clearing out user session %s \n" % session['user'].username)
    cache_key = '{}_web_credentials'.format(session['user'].username.replace(
        ' ', '_'))
    cache.delete(cache_key)
    for item in [
            'logged_in', 'user', 'system_message_body', 'system_message_title',
            'stat_products_complete_24_hrs', 'stat_backlog_depth', 'sso_cookie'
    ]:
        session.pop(item, None)
예제 #7
0
파일: app.py 프로젝트: djzelenak/espa-web
def logout():
    if 'user' not in session:
        logger.info('No user session found.')
        return redirect(url_for('index'))

    resp = make_response(redirect(url_for('index')))
    resp.set_cookie(SSO_COOKIE_NAME, '', expires=0, domain='usgs.gov')
    resp.set_cookie(SSO_COOKIE_NAME.replace('_secure', ''),
                    '',
                    expires=0,
                    domain='usgs.gov')
    return resp
예제 #8
0
파일: app.py 프로젝트: djzelenak/espa-web
def list_orders_feed(email):
    # browser hit this url, need to handle # TODO: Is this still used?
    # user auth for both use cases
    if 'Authorization' in request.headers:  # FIXME: pretty sure this is gone
        # coming in from bulk downloader
        logger.info("Apparent bulk download attempt, headers: %s" %
                    request.headers)
        auth_header_dec = base64.b64decode(request.headers['Authorization'])
        uauth = tuple(auth_header_dec.split(":"))
    else:
        if 'logged_in' not in session or session['logged_in'] is not True:
            return redirect(url_for('index', next=request.url))
        else:
            uauth = (session['user'].username, session['user'].wurd)
    orders = api_up("/list-orders/{}".format(email),
                    uauth=uauth,
                    json={'status': 'complete'})

    order_items = dict()
    for orderid in orders:
        item_status = api_up('/item-status/{}'.format(orderid), uauth=uauth)
        item_status = item_status.get(orderid, {})
        item_status = map(lambda x: Scene(**x), item_status)
        order_info = api_up('/order/{}'.format(orderid), uauth=uauth)
        order_items[orderid] = dict(scenes=item_status,
                                    orderdate=order_info['order_date'])

    rss = PyRSS2Gen.RSS2(
        title='ESPA Status Feed',
        link='http://espa.cr.usgs.gov/ordering/status/{0}/rss/'.format(email),
        description='ESPA scene status for:{0}'.format(email),
        language='en-us',
        lastBuildDate=datetime.datetime.now(),
        items=[])

    for orderid, order in order_items.items():
        for scene in order['scenes']:
            if scene.status != 'complete':
                continue
            description = ('scene_status:{0},orderid:{1},orderdate:{2}'.format(
                scene.status, orderid, order['orderdate']))
            new_rss_item = PyRSS2Gen.RSSItem(title=scene.name,
                                             link=scene.product_dload_url,
                                             description=description,
                                             guid=PyRSS2Gen.Guid(
                                                 scene.product_dload_url))

            rss.items.append(new_rss_item)

    return rss.to_xml(encoding='utf-8')
예제 #9
0
파일: app.py 프로젝트: USGS-EROS/espa-web
def submit_order():
    # form values come in as an ImmutableMultiDict
    data = request.form.to_dict()
    logger.info("* new order submission for user %s\n\n order details: %s\n\n\n" % (session['user'].username, data))
    _external = False
    try:
        # grab sceneids from the file in input_product_list field
        _ipl_list = request.files.get('input_product_list').read().splitlines()
        _ipl = [i.strip().split("/r") for i in _ipl_list]
        _ipl = [item for sublist in _ipl for item in sublist if item]
    except AttributeError, e:
        # must be coming from new_external_order
        _ipl_list = data.pop('input_product_list')
        _ipl = _ipl_list.split(",")
        session['ipl'] = _ipl_list
        _external = True
예제 #10
0
파일: app.py 프로젝트: govtmirror/espa-web
def list_orders_feed(email):
    # bulk downloader and the browser hit this url, need to handle
    # user auth for both use cases
    url = "/list-orders-feed/{}".format(email)
    if 'Authorization' in request.headers:
        # coming in from bulk downloader
        logger.info("Apparent bulk download attempt, headers: %s" %
                    request.headers)
        auth_header_dec = base64.b64decode(request.headers['Authorization'])
        response = api_get(url, uauth=tuple(auth_header_dec.split(":")))
    else:
        if 'logged_in' not in session or session['logged_in'] is not True:
            return redirect(url_for('login', next=request.url))
        else:
            response = api_get(url)

    if "msg" in response:
        logger.info("Problem retrieving rss for email: %s \n message: %s\n" %
                    (email, response['msg']))
        status_code = 404
        if "Invalid username/password" in response['msg']:
            status_code = 403
        return jsonify(response), status_code
    else:
        rss = PyRSS2Gen.RSS2(
            title='ESPA Status Feed',
            link='http://espa.cr.usgs.gov/ordering/status/{0}/rss/'.format(
                email),
            description='ESPA scene status for:{0}'.format(email),
            language='en-us',
            lastBuildDate=datetime.datetime.now(),
            items=[])

        for item in response:
            for scene in response[item]['scenes']:
                description = 'scene_status:{0},orderid:{1},orderdate:{2}'.format(
                    scene['status'], item, response[item]['orderdate'])
                new_rss_item = PyRSS2Gen.RSSItem(title=scene['name'],
                                                 link=scene['url'],
                                                 description=description,
                                                 guid=PyRSS2Gen.Guid(
                                                     scene['url']))

                rss.items.append(new_rss_item)

        return rss.to_xml(encoding='utf-8')
예제 #11
0
파일: app.py 프로젝트: govtmirror/espa-web
def submit_order():
    # form values come in as an ImmutableMultiDict
    data = request.form.to_dict()
    logger.info(
        "* new order submission for user %s\n\n order details: %s\n\n\n" %
        (session['user'].username, data))
    _external = False
    try:
        # grab sceneids from the file in input_product_list field
        _ipl_list = request.files.get('input_product_list').read().splitlines()
        _ipl = [i.strip().split("/r") for i in _ipl_list]
        _ipl = [item for sublist in _ipl for item in sublist if item]
    except AttributeError, e:
        # must be coming from new_external_order
        _ipl_list = data.pop('input_product_list')
        _ipl = _ipl_list.split(",")
        session['ipl'] = _ipl_list
        _external = True
예제 #12
0
파일: app.py 프로젝트: USGS-EROS/espa-web
def list_orders_feed(email):
    # bulk downloader and the browser hit this url, need to handle
    # user auth for both use cases
    url = "/list-orders-feed/{}".format(email)
    if 'Authorization' in request.headers:
        # coming in from bulk downloader
        logger.info("Apparent bulk download attempt, headers: %s" % request.headers)
        auth_header_dec = base64.b64decode(request.headers['Authorization'])
        response = api_get(url, uauth=tuple(auth_header_dec.split(":")))
    else:
        if 'logged_in' not in session or session['logged_in'] is not True:
            return redirect(url_for('login', next=request.url))
        else:
            response = api_get(url)

    if "msg" in response:
        logger.info("Problem retrieving rss for email: %s \n message: %s\n" % (email, response['msg']))
        status_code = 404
        if "Invalid username/password" in response['msg']:
            status_code = 403
        return jsonify(response), status_code
    else:
        rss = PyRSS2Gen.RSS2(
            title='ESPA Status Feed',
            link='http://espa.cr.usgs.gov/ordering/status/{0}/rss/'.format(email),
            description='ESPA scene status for:{0}'.format(email),
            language='en-us',
            lastBuildDate=datetime.datetime.now(),
            items=[]
        )

        for item in response:
            for scene in response[item]['scenes']:
                description = 'scene_status:{0},orderid:{1},orderdate:{2}'.format(scene['status'], item, response[item]['orderdate'])
                new_rss_item = PyRSS2Gen.RSSItem(
                    title=scene['name'],
                    link=scene['url'],
                    description=description,
                    guid=PyRSS2Gen.Guid(scene['url'])
                )

                rss.items.append(new_rss_item)

        return rss.to_xml(encoding='utf-8')
예제 #13
0
파일: app.py 프로젝트: djzelenak/espa-web
def espa_session_login(username, password):
    cache_key = '{}_web_credentials'.format(username.replace(' ', '_'))
    resp_json = cache.get(cache_key)
    if (resp_json is None) or (isinstance(resp_json, dict)
                               and resp_json.get('wurd') != password):
        resp_json = api_up("/user", uauth=(username, password))

    if 'username' in resp_json:
        session['logged_in'] = True
        resp_json['wurd'] = password
        session['user'] = User(**resp_json)

        two_hours = 7200  # seconds
        cache.set(cache_key, resp_json, two_hours)

        update_status_details()
        logger.info("User %s logged in" % session['user'].username)
        return True
    else:
        logger.info("**** Failed user login %s" % username)
        return False
예제 #14
0
파일: app.py 프로젝트: govtmirror/espa-web
def login():
    destination = request.args.get('next')
    if request.method == 'POST':
        resp_json = api_get("/user",
                            uauth=(request.form['username'],
                                   request.form['password']))
        if 'username' in resp_json:
            session['logged_in'] = True
            resp_json['wurd'] = request.form['password']
            session['user'] = User(**resp_json)
            update_status_details()
            logger.info("User %s logged in\n" % session['user'].username)
            # send the user back to their
            # originally requested destination
            if destination and destination != 'None':
                return redirect(destination)
            else:
                return redirect(url_for('index'))
        else:
            logger.info("**** Failed user login %s \n" %
                        request.form['username'])
            flash(format_errors(resp_json['msg']), 'error')
            _status = 401
    else:
        _status = 200
        if 'user' not in session:
            session['user'] = None

    in_ops = 'ESPA_ENV' in os.environ and os.environ['ESPA_ENV'] == 'ops'
    explorer = "http://earthexplorer.usgs.gov" if in_ops else "http://eedevmast.cr.usgs.gov"
    reg_host = "https://ers.cr.usgs.gov" if in_ops else "http://ersdevmast.cr.usgs.gov"

    return render_template('login.html',
                           next=destination,
                           earthexplorer=explorer,
                           register_user=reg_host + "/register",
                           forgot_login=reg_host +
                           "/password/request"), _status
예제 #15
0
파일: app.py 프로젝트: USGS-EROS/espa-web
        _ipl_list = request.files.get('input_product_list').read().splitlines()
        _ipl = [i.strip().split("/r") for i in _ipl_list]
        _ipl = [item for sublist in _ipl for item in sublist if item]
    except AttributeError, e:
        # must be coming from new_external_order
        _ipl_list = data.pop('input_product_list')
        _ipl = _ipl_list.split(",")
        session['ipl'] = _ipl_list
        _external = True

    try:
        # convert our list of sceneids into format required for new orders
        scene_dict_all_prods = api_up("/available-products", {'inputs': _ipl}).json()
    except UnicodeDecodeError as e:
        flash('Decoding Error with input file. Please check input file encoding', 'error')
        logger.info("problem with order submission for user %s\n\n message: %s\n\n" % (session['user'].username,
                                                                                       e.message))

        return redirect(url_for('new_order'))

    # create a list of requested products
    landsat_list = [key for key in data if key in conversions['products']]
    # now that we have the product list, lets remove
    # this key from the form inputs
    for p in landsat_list:
        data.pop(p)

    # scrub the 'spectral_indices' value from data
    # used simply for toggling display of spectral indice products
    if 'spectral_indices' in data:
        data.pop('spectral_indices')
예제 #16
0
파일: app.py 프로젝트: USGS-EROS/espa-web
def logout():
    logger.info("Logging out user %s \n" % session['user'].username)
    for item in ['logged_in', 'user', 'system_message_body', 'system_message_title',
                 'stat_products_complete_24_hrs', 'stat_backlog_depth', 'stat_onorder_depth']:
        session.pop(item, None)
    return redirect(url_for('login'))
예제 #17
0
파일: app.py 프로젝트: djzelenak/espa-web
        # grab sceneids from the file in input_product_list field
        _ipl_list = request.files.get('input_product_list').read().splitlines()
        _ipl = [i.strip().split("/r") for i in _ipl_list]
        _ipl = [item for sublist in _ipl for item in sublist if item]
    except AttributeError, e:
        # must be coming from new_external_order
        _ipl_list = data.pop('input_product_list')
        _ipl = _ipl_list.split(",")
        session['ipl'] = _ipl_list
        _external = True

    try:
        # convert our list of sceneids into format required for new orders
        scene_dict_all_prods = api_up("/available-products",
                                      json={'inputs': _ipl})
        logger.info("* available products - {}".format(scene_dict_all_prods))
    except UnicodeDecodeError as e:
        flash(
            'Decoding Error with input file. Please check input file encoding',
            'error')
        logger.info(
            "problem with order submission for user %s\n\n message: %s\n\n" %
            (session['user'].username, e.message))

        return redirect(url_for('new_order'))
    finally:
        # These are errors, and the API will not recognize them on validation
        remove = dict()

        not_implemented = scene_dict_all_prods.get('not_implemented')
        if not_implemented:
예제 #18
0
파일: app.py 프로젝트: govtmirror/espa-web
        _ipl_list = data.pop('input_product_list')
        _ipl = _ipl_list.split(",")
        session['ipl'] = _ipl_list
        _external = True

    try:
        # convert our list of sceneids into format required for new orders
        scene_dict_all_prods = api_up("/available-products", {
            'inputs': _ipl
        }).json()
    except UnicodeDecodeError as e:
        flash(
            'Decoding Error with input file. Please check input file encoding',
            'error')
        logger.info(
            "problem with order submission for user %s\n\n message: %s\n\n" %
            (session['user'].username, e.message))

        return redirect(url_for('new_order'))

    # create a list of requested products
    landsat_list = [key for key in data if key in conversions['products']]
    # now that we have the product list, lets remove
    # this key from the form inputs
    for p in landsat_list:
        data.pop(p)

    # scrub the 'spectral_indices' value from data
    # used simply for toggling display of spectral indice products
    if 'spectral_indices' in data:
        data.pop('spectral_indices')