Beispiel #1
0
 def view(request):
     if with_id:
         id_ = request.context.id
         url = request.route_path(route_name, id=id_)
     else:
         url = request.route_path(route_name)
     return HTTPTemporaryRedirect(url)
Beispiel #2
0
 def filter(self, environ, headers, data):
     status = environ.pop('flexfilter.status')
     if status == HTTPTemporaryRedirect().status:
         response = '''
                     <error>
                       <code>%s</code>
                       <location>%s</location>
                       <message>%s</message>
                     </error>
                     ''' % (status, header_value(headers, 'Location'),
                            header_value(headers, 'Warning'))
         replace_header(headers, 'Content-Length', len(response))
     else:
         root = etree.HTML(data)
         message = escape(etree.tostring(root.find('.//body'),
                                         method="text").strip())
         if not message:
             message = root.find('.//title').text
         details = ""
         code_node = root.find('.//code')
         if code_node  is not None and code_node.text  is not None:
             details = escape(code_node.text)
             # Shorten a bit.
             pos = details.find(',')
             if pos != -1:
                 details = details[:pos]
         response = '''
                     <error>
                       <code>%s</code>
                       <message>%s</message>
                       <details>%s</details>
                     </error>
                     ''' % (status, message, details)
         replace_header(headers, 'Content-Length', len(response))
     return response
Beispiel #3
0
def page_not_found(request):
    """Return a JSON 404 error response."""
    config_key = 'trailing_slash_redirect_enabled'
    redirect_enabled = request.registry.settings[config_key]
    trailing_slash_redirection_enabled = asbool(redirect_enabled)

    querystring = request.url[(request.url.rindex(request.path) +
                               len(request.path)):]

    errno = ERRORS.MISSING_RESOURCE
    error_msg = "The resource you are looking for could not be found."

    if not request.path.startswith('/' + request.registry.route_prefix):
        errno = ERRORS.VERSION_NOT_AVAILABLE
        error_msg = ("The requested protocol version is not available "
                     "on this server.")
    elif trailing_slash_redirection_enabled:
        redirect = None

        if request.path.endswith('/'):
            path = request.path.rstrip('/')
            redirect = '%s%s' % (path, querystring)
        elif request.path == '/' + request.registry.route_prefix:
            # Case for /v0 -> /v0/
            redirect = '/%s/%s' % (request.registry.route_prefix, querystring)

        if redirect:
            return HTTPTemporaryRedirect(redirect)

    response = http_error(httpexceptions.HTTPNotFound(),
                          errno=errno,
                          message=error_msg)
    return response
Beispiel #4
0
def page_not_found(response, request):
    """Return a JSON 404 error response."""
    config_key = "trailing_slash_redirect_enabled"
    redirect_enabled = request.registry.settings[config_key]
    trailing_slash_redirection_enabled = asbool(redirect_enabled)

    querystring = request.url[(request.url.rindex(request.path) +
                               len(request.path)):]

    errno = ERRORS.MISSING_RESOURCE
    error_msg = "The resource you are looking for could not be found."

    if not request.path.startswith(f"/{request.registry.route_prefix}"):
        errno = ERRORS.VERSION_NOT_AVAILABLE
        error_msg = "The requested API version is not available " "on this server."
    elif trailing_slash_redirection_enabled:
        redirect = None

        if request.path.endswith("/"):
            path = request.path.rstrip("/")
            redirect = f"{path}{querystring}"
        elif request.path == f"/{request.registry.route_prefix}":
            # Case for /v0 -> /v0/
            redirect = f"/{request.registry.route_prefix}/{querystring}"

        if redirect:
            return reapply_cors(request, HTTPTemporaryRedirect(redirect))

    if response.content_type != "application/json":
        response = http_error(httpexceptions.HTTPNotFound(),
                              errno=errno,
                              message=error_msg)
    return reapply_cors(request, response)
def select_day(request):
    try:
        if not ('year' in request.params and 'month' in request.params
                and 'day' in request.params and 'hour' in request.params):
            return HTTPTemporaryRedirect(location=request.route_path(
                'today',
                accesstype=request.params.getone('accessby'),
                access=request.params.getone('accessto')))
        selected = validdate(int(request.params.getone('year')),
                             int(request.params.getone('month')),
                             int(request.params.getone('day')),
                             int(request.params.getone('hour')))
        return HTTPTemporaryRedirect(
            location=monthurlfor(request, request.params.getone('accessby'),
                                 request.params.getone('accessto'), selected))
    except:
        return HTTPTemporaryRedirect(location=request.route_path('home'))
Beispiel #6
0
    def _redirect_to_version_view(request):
        if request.method.lower() == "options":
            # CORS responses should always have status 200.
            return utils.reapply_cors(request, Response())

        querystring = request.url[(request.url.rindex(request.path) + len(request.path)) :]
        redirect = "/{}{}{}".format(route_prefix, request.path, querystring)
        raise HTTPTemporaryRedirect(redirect)
def select_month(request):
    try:
        if not ('year' in request.params and 'month' in request.params):
            return HTTPTemporaryRedirect(location=request.route_path(
                'thumb',
                accesstype=request.params.getone('accessby'),
                access=request.params.getone('accessto'),
                thumbtype=request.params.getone('type')))
        selected = validdate(int(request.params.getone('year')),
                             int(request.params.getone('month')))
        if 'day' in request.params:
            selected += timedelta(days=int(request.params.getone('day')) - 1)
        return HTTPTemporaryRedirect(
            location=monthurlfor(request, request.params.getone('accessby'),
                                 request.params.getone('accessto'),
                                 request.params.getone('type'), selected))
    except:
        return HTTPTemporaryRedirect(location=request.route_path("home"))
Beispiel #8
0
def download(context, request):
    properties = context.upgrade_properties()
    mapping = context.schema['file_format_file_extension']
    file_extension = mapping[properties['file_format']]
    accession_or_external = properties.get(
        'accession') or properties['external_accession']
    filename = accession_or_external + file_extension
    if request.subpath:
        _filename, = request.subpath
        if filename != _filename:
            raise HTTPNotFound(_filename)

    proxy = asbool(request.params.get('proxy')) or 'Origin' in request.headers \
                                                or 'Range' in request.headers

    use_download_proxy = request.client_addr not in request.registry[
        'aws_ipset']

    external = context.propsheets.get('external', {})
    if external.get('service') == 's3':
        conn = boto3.client('s3')
        location = conn.generate_presigned_url(
            ClientMethod='get_object',
            Params={
                'Bucket': external['bucket'],
                'Key': external['key'],
                'ResponseContentDisposition':
                'attachment; filename=' + filename
            },
            ExpiresIn=36 * 60 * 60)
    else:
        raise HTTPNotFound(detail='External service {} not expected'.format(
            external.get('service')))

    if asbool(request.params.get('soft')):
        expires = int(parse_qs(urlparse(location).query)['Expires'][0])
        return {
            '@type': ['SoftRedirect'],
            'location':
            location,
            'expires':
            datetime.datetime.fromtimestamp(expires, pytz.utc).isoformat(),
        }

    if proxy:
        return Response(
            headers={'X-Accel-Redirect': '/_proxy/' + str(location)})

    # We don't use X-Accel-Redirect here so that client behaviour is similar for
    # both aws and non-aws users.
    if use_download_proxy:
        location = request.registry.settings.get('download_proxy',
                                                 '') + str(location)

    # 307 redirect specifies to keep original method
    raise HTTPTemporaryRedirect(location=location)
Beispiel #9
0
    def _redirect_to_version_view(request):
        if request.method.lower() == 'options':
            # CORS responses should always have status 200.
            return utils.reapply_cors(request, Response())

        path = request.matchdict['path']
        querystring = request.url[(request.url.rindex(request.path) +
                                   len(request.path)):]
        redirect = '/%s/%s%s' % (route_prefix, path, querystring)
        raise HTTPTemporaryRedirect(redirect)
Beispiel #10
0
 def prepare_params(self):
     cleaned_param_dict = super(RestAPIViewBase, self).prepare_params()
     default_delta = datetime.timedelta(days=int(
         self.request.registry.settings.get('default_time_min',
                                            self.DEFAULT_TIME_MIN)))
     redirect_url = self.get_redirect_url_if_no_time_min(
         cleaned_param_dict, default_delta)
     if redirect_url is not None:
         raise HTTPTemporaryRedirect(redirect_url)
     return cleaned_param_dict
Beispiel #11
0
def download(context, request):
    properties = context.upgrade_properties()
    mapping = context.schema['file_format_file_extension']
    file_extension = mapping[properties['file_format']]
    accession_or_external = properties.get(
        'accession') or properties['external_accession']
    filename = accession_or_external + file_extension
    if request.subpath:
        _filename, = request.subpath
        if filename != _filename:
            raise HTTPNotFound(_filename)

    proxy = asbool(request.params.get('proxy')) or 'Origin' in request.headers \
                                                or 'Range' in request.headers

    use_download_proxy = request.client_addr not in request.registry[
        'aws_ipset']

    external = context.propsheets.get('external', {})
    if external.get('service') == 's3':
        conn = boto.connect_s3()
        location = conn.generate_url(36 * 60 * 60,
                                     request.method,
                                     external['bucket'],
                                     external['key'],
                                     force_http=False,
                                     response_headers={
                                         'content-type':
                                         'binary/octet-stream',
                                         'response-content-disposition':
                                         "attachment; filename=" + filename,
                                     })
    else:
        raise ValueError(external.get('service'))

    if asbool(request.params.get('soft')):
        expires = int(parse_qs(urlparse(location).query)['Expires'][0])
        return {
            '@type': ['SoftRedirect'],
            'location':
            location,
            'expires':
            datetime.datetime.fromtimestamp(expires, pytz.utc).isoformat(),
        }

    # if proxy:
    #    return Response(headers={'X-Accel-Redirect': '/_proxy/' + str(location)})

    # We don't use X-Accel-Redirect here so that client behaviour is similar for
    # both aws and non-aws users.
    # if use_download_proxy:
    #    location = request.registry.settings.get('download_proxy', '') + str(location)

    # 307 redirect specifies to keep original method
    raise HTTPTemporaryRedirect(location=location)
Beispiel #12
0
 def account_route_put(self, context, request: TracimRequest,
                       hapic_data: HapicData):
     """
     Convenient route allowing to use PUT /api/users/{user_id}/* endpoint with authenticated user
     without giving directly user id.
     This route generate a HTTP 307 with the right url
     """
     return HTTPTemporaryRedirect(
         request.url.replace(
             "/users/me", "/users/{user_id}".format(
                 user_id=request.current_user.user_id), 1))
Beispiel #13
0
 def index(self):
     if self.username is None:
         account = self.request.session.get(LOGGED_ACCOUNT_KEY, None)
     else:
         password = self.request.params.get('password', None)
         account = AccountService.find_out_account(self.username, password)
     if account is None:
         return HTTPTemporaryRedirect(location="/in.log")
     else:
         self.request.session[LOGGED_ACCOUNT_KEY] = account
         return {}
Beispiel #14
0
def expenses_access_view(request):
    """
        get/initialize the expense corresponding to the 4-uple:
            (year, month, user_id, company_id)
        Redirect to the expected expense page
        Should be called with post args
    """
    year, month = get_period(request)
    cid = request.context.id
    uid = request.matchdict.get('uid')
    expense = get_expense_sheet(request, year, month, cid, uid)
    # Here we use a temporary redirect since the expense we redirect too may
    # have change if it was reset
    return HTTPTemporaryRedirect(
        request.route_path("expensesheet", id=expense.id))
def redirect_day(request):
    try:
        methodtype = request.matchdict['accesstype']
        methodkey = request.matchdict['access']
        nowtime = datetime.utcnow()
        try:
            mylib = HSRLImageArchiveLibrarian(**{methodtype: methodkey})
        except RuntimeError:
            return HTTPNotFound(methodtype + "-" + methodkey + " is invalid")

        if 'year' in request.matchdict:
            yearno = int(request.matchdict['year'])
        else:
            yearno = nowtime.year
        if 'month' in request.matchdict:
            monthno = int(request.matchdict['month'])
        else:
            monthno = nowtime.month
        if 'day' in request.matchdict:
            dayno = int(request.matchdict['day'])
        else:
            dayno = nowtime.day
        if 'ampm' in request.matchdict:
            ampm = request.matchdict['ampm']
            if ampm == 'am':
                hourno = 0
            else:
                hourno = 12
        else:
            hourno = nowtime.hour
        besttime = mylib.validClosestTime(
            datetime(yearno, monthno, dayno, hourno, 0, 0))
        return HTTPTemporaryRedirect(
            location=dayurlfor(request, methodtype, methodkey, besttime))
    except:
        return HTTPTemporaryRedirect(location=request.route_path('home'))
Beispiel #16
0
def process_sign_in_external(request, username, provider):
    provider_name = provider.lower()
    if provider_name == "openid":
        query_field = dict(id=username)
    elif provider_name == "github":
        query_field = None
        # query_field = dict(login_field=username)
    elif provider_name == "wso2":
        query_field = {}
    else:
        query_field = dict(username=username)

    came_from = request.POST.get("came_from", "/")
    request.response.set_cookie("homepage_route", came_from)
    external_login_route = request.route_url(s.ProviderSigninAPI.name, provider_name=provider_name, _query=query_field)
    return HTTPTemporaryRedirect(location=external_login_route, headers=request.response.headers)
def download(context, request):
    properties = context.upgrade_properties()
    mapping = context.schema['file_format_file_extension']
    file_extension = mapping[properties['file_format']]
    accession_or_external = properties.get(
        'accession') or properties['external_accession']
    filename = accession_or_external + file_extension
    if request.subpath:
        _filename, = request.subpath
        if filename != _filename:
            raise HTTPNotFound(_filename)
    external = context.propsheets.get('external', {})
    if external.get('service') == 's3':
        conn = boto3.client('s3')
        location = conn.generate_presigned_url(
            ClientMethod='get_object',
            Params={
                'Bucket': external['bucket'],
                'Key': external['key'],
                'ResponseContentDisposition':
                'attachment; filename=' + filename
            },
            ExpiresIn=36 * 60 * 60)
    else:
        raise HTTPNotFound(detail='External service {} not expected'.format(
            external.get('service')))
    if asbool(request.params.get('soft')):
        expires = int(parse_qs(urlparse(location).query)['Expires'][0])
        return {
            '@type': ['SoftRedirect'],
            'location':
            location,
            'expires':
            datetime.datetime.fromtimestamp(expires, pytz.utc).isoformat(),
        }
    proxy = asbool(request.params.get('proxy'))
    accel_redirect_header = request.registry.settings.get(
        'accel_redirect_header')
    if proxy and accel_redirect_header:
        return InternalRedirect(
            headers={accel_redirect_header: '/_proxy/' + str(location)})
    raise HTTPTemporaryRedirect(location=location)
Beispiel #18
0
def netcdfrequest(request):
    #print 'URLREQ: ',request.matched_route.name
    session = request.session
    sessionid = session.new_csrf_token()
    sessiondict = {}
    sessiondict['sessionid'] = sessionid
    if request.params.getone('filemode') == 'single':
        sessiondict['finalpage'] = request.route_path('netcdfresult',
                                                      session=sessionid)
        return picnicsession.newSessionProcess("newnetcdf", request,
                                               sessiondict)
    sessiondict['finalpage'] = request.route_path('multinetcdfresult',
                                                  session=sessionid)
    picnicsession.newSessionProcess("newmultinetcdf",
                                    request,
                                    sessiondict,
                                    force_time=datetime.utcnow() +
                                    timedelta(days=1))
    time.sleep(1)
    return HTTPTemporaryRedirect(location=sessiondict['finalpage'])
Beispiel #19
0
def logbook(request):
    methodtype = request.matchdict['accesstype']
    methodkey = request.matchdict['access']
    try:
        datasetid = lib(
            'dataset',
            lib(**{methodtype: methodkey})['Instruments'][0])['DatasetID']
    except RuntimeError:
        return HTTPNotFound(methodtype + "-" + methodkey + " is invalid")


#        return HTTPTemporaryRedirect(location=request.route_path("home"))
    parms = {'dataset': '%i' % datasetid}
    for f in [
            'byr', 'bmo', 'bdy', 'bhr', 'bmn', 'eyr', 'emo', 'edy', 'ehr',
            'emn', 'rss'
    ]:
        if f in request.params:
            parms[f] = request.params.getone(f)
    return HTTPTemporaryRedirect(
        location='http://lidar.ssec.wisc.edu/cgi-bin/logbook/showlogbook.cgi?'
        + '&'.join([(k + '=' + parms[k]) for k in parms.keys()]))
Beispiel #20
0
def archiveconf(request):
    tok = request.matchdict['json_type_token']
    #check if this was submitted
    response = request.response
    print request.params
    if 'remove' in request.params:
        remove_archived_file(tok, request.params.getone('remove'))
    if 'submitted' in request.params:
        usearray = []
        for h in get_complete_list(tok):
            if h in request.params and request.params.getone(h):
                usearray.append(h)
        if 'remove' not in request.params:
            if 'destination' in request.params:
                response = HTTPTemporaryRedirect(
                    location=request.params.getone('destination')
                )  #slowredirect(location=request.params.getone('destination'))
            replace_archive_list(request, tok, usearray, response=response)
            if 'destination' in request.params:
                return response
    else:
        usearray = [x for x in get_archive_list(request, tok)]
    return {
        'datetime':
        datetime,
        'timedelta':
        timedelta,
        'token':
        tok,
        'destination':
        request.params.getone('destination')
        if 'destination' in request.params else None,
        'entries':
        get_complete_list(tok),
        'selected_entries':
        usearray,
        'get_file_description':
        get_file_description
    }
Beispiel #21
0
def pdf_serve_single(request):

    patent = request.matchdict['patent']
    #parts = request.matchdict['parts']

    data = pdf_universal(patent)

    if 'pdf' in data and data['pdf']:
        # http://tools.ietf.org/html/rfc6266#section-4.2
        request.response.content_type = 'application/pdf'
        request.response.charset = None
        request.response.headers['Content-Disposition'] = 'inline; filename={0}.pdf'.format(patent)
        request.response.headers['X-Pdf-Source'] = data['datasource']
        return data['pdf']

    elif 'meta' in data:
        meta = data['meta']
        if 'location' in meta and meta['location']:
            url = meta['location']
            log.info('Redirecting PDF request to "{url}"'.format(url=url))
            raise HTTPTemporaryRedirect(location=url)

    raise HTTPNotFound('No PDF for document {patent}'.format(patent=patent))
Beispiel #22
0
def download(context, request):
    """ Navigates to the IGV snapshot hrf on the bam_snapshot field. """
    calculated = calculate_properties(context, request)
    s3_client = boto3.client('s3')
    params_to_get_obj = {
        'Bucket': request.registry.settings.get('file_wfout_bucket'),
        'Key': calculated['bam_snapshot']
    }
    location = s3_client.generate_presigned_url(
        ClientMethod='get_object',
        Params=params_to_get_obj,
        ExpiresIn=36*60*60
    )

    if asbool(request.params.get('soft')):
        expires = int(parse_qs(urlparse(location).query)['Expires'][0])
        return {
            '@type': ['SoftRedirect'],
            'location': location,
            'expires': datetime.datetime.fromtimestamp(expires, pytz.utc).isoformat(),
        }

    # 307 redirect specifies to keep original method
    raise HTTPTemporaryRedirect(location=location)  # 307
Beispiel #23
0
    def raise_if_blocked(self, url):
        """Raise a redirect to Checkmate if the URL is blocked.

        This will sensibly apply all ignore reasons and other configuration for
        Checkmate.

        :param url: The URL to check
        :raise HTTPTemporaryRedirect: If the URL is blocked
        """
        try:
            blocked = self.check_url(
                url,
                allow_all=self._request.registry.settings["checkmate_allow_all"],
                blocked_for=self._request.params.get("via.blocked_for"),
                ignore_reasons=self._request.registry.settings[
                    "checkmate_ignore_reasons"
                ],
            )

        except CheckmateException:
            blocked = None

        if blocked:
            raise HTTPTemporaryRedirect(location=blocked.presentation_url)
Beispiel #24
0
 def admin_redirect_view(request):
     raise HTTPTemporaryRedirect(request.path + '/')
Beispiel #25
0
def progress_getlastid(request):
    sessionid = request.session.get_csrf_token(
    )  #get_cookies['session']#POST['csrf_token']
    return HTTPTemporaryRedirect(
        location=request.route_path("progress_withid", session=sessionid))
Beispiel #26
0
def form_view(request):
    #print 'URLREQ: ',request.matched_route.name
    methodtype = request.matchdict['accesstype']
    methodkey = request.matchdict['access']
    try:
        mylib = HSRLImageArchiveLibrarian(**{methodtype: methodkey})
    except RuntimeError:
        return HTTPNotFound(methodtype + "-" + methodkey + " is invalid")
#        return HTTPTemporaryRedirect(location=request.route_path("home"))
    st = mylib()
    instruments = st['Instruments']
    instcount = len(instruments)
    name = st['Name']
    datasets = []
    for inst in instruments:
        datasets.extend(lib.instrument(inst)['datasets'])

    try:
        starttime = validdate(int(request.params.getone('byr')),
                              int(request.params.getone('bmo')),
                              int(request.params.getone('bdy')),
                              int(request.params.getone('bhr')),
                              int(request.params.getone('bmn')))
        endtime = validdate(int(request.params.getone('eyr')),
                            int(request.params.getone('emo')),
                            int(request.params.getone('edy')),
                            int(request.params.getone('ehr')),
                            int(request.params.getone('emn')))
        maxalt = float(request.params.getone('maxalt'))
        minalt = float(request.params.getone('minalt'))
    except:
        #print 'fallback'
        #print request.POST
        #print request.GET
        minalt = 0
        maxalt = 15
        lasttime = mylib.validClosestTime(datetime.utcnow())
        endtime = validdate(lasttime.year, lasttime.month, lasttime.day,
                            lasttime.hour,
                            lasttime.minute - (lasttime.minute % 5))
        starttime = validdate(endtime.year, endtime.month, endtime.day,
                              endtime.hour - 2, endtime.minute)

    oldformparmsdict = {
        methodtype: methodkey,
        'forcematlab': 'yes',
        'byr': '%i' % starttime.year,
        'bmo': '%i' % starttime.month,
        'bdy': '%i' % starttime.day,
        'bhr': '%i' % starttime.hour,
        'bmn': '%i' % starttime.minute,
        'eyr': '%i' % endtime.year,
        'emo': '%i' % endtime.month,
        'edy': '%i' % endtime.day,
        'ehr': '%i' % endtime.hour,
        'emn': '%i' % endtime.minute,
        'minalt': '%i' % minalt,
        'maxalt': '%i' % maxalt
    }
    oldformparams = '&'.join(
        (k + '=' + oldformparmsdict[k]) for k in oldformparmsdict.keys())
    #print oldformparams

    if request.matched_route.name == 'netcdfgen':
        oldurl = "http://lidar.ssec.wisc.edu/cgi-bin/processeddata/retrievedata.cgi?%s" % (
            oldformparams)
    if request.matched_route.name == 'imagegen':
        oldurl = "http://lidar.ssec.wisc.edu/cgi-bin/ahsrldisplay/requestfigs.cgi?%s" % (
            oldformparams)
    if False:  #instcount>3 :#more than just HSRL. python doesn't support it yet
        return HTTPTemporaryRedirect(location=oldurl)

    #print request
    # used in both forms, but simplifies template
    alts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 20, 25,
            30]  #in kilometers
    # these are only used in netcdf, and not form-configurable. this simplifies the template
    altres = 30
    timeres = 30
    altresvals = [
        7.5, 15, 30, 45, 60, 75, 90, 120, 150, 300, 450, 600, 900, 1200
    ]  # in meters
    timeresvals = [
        2.5, 5, 10, 15, 30, 60, 120, 180, 240, 300, 600, 900, 1200, 3600, 43200
    ]  # in seconds

    #print instruments

    hosttouse = None
    porttouse = None
    if "X-Forwarded-Host" in request.headers:
        hosttouse = request.headers['X-Forwarded-Host']
        porttouse = ''

    return {
        'project':
        'Picnic',
        'bdate':
        starttime,
        'edate':
        endtime,
        'calendar':
        calendar,
        'timedelta':
        timedelta,
        'datetime':
        datetime,
        'altrange': [minalt, maxalt],
        'alts':
        alts,
        'timeresvals':
        timeresvals,
        'altresvals':
        altresvals,
        'timeres':
        timeres,
        'altres':
        altres,
        'imagesets':
        jsgen.formsetsForInstruments(datasets, 'images'),
        'netcdfsets':
        jsgen.formsetsForInstruments(datasets, 'netcdf'),
        'datasets':
        datasets,
        'method':
        methodtype,
        methodtype:
        methodkey,
        'oldurl':
        oldurl,
        'netcdfdestinationurl':
        request.route_url('netcdfreq', _host=hosttouse, _port=porttouse),
        'imagedestinationurl':
        request.route_url('imagereq', _host=hosttouse, _port=porttouse),
        'cdltemplates': {
            "hsrl_nomenclature.cdl": "UW HSRL(NetCDF4)",
            "hsrl_cfradial.cdl": "NCAR CFRadial",
            "hsrl3_processed.cdl": "UW Processed (NetCDF3)",
            "hsrl3_raw.cdl": "UW Raw (NetCDF3)",
            "custom": "User Provided:"
        },
        'cdltemplateorder': [
            "hsrl_nomenclature.cdl", "hsrl_cfradial.cdl",
            "hsrl3_processed.cdl", "hsrl3_raw.cdl", "custom"
        ],
        'userTracking':
        picnicsession.haveUserTracking(),
        #'usercheckurl':request.route_path('userCheck'),#'http://lidar.ssec.wisc.edu/cgi-bin/util/userCheck.cgi',
        'dataAvailabilityURL':
        request.route_path('dataAvailability'),
        'sitename':
        name,
        'setCount':
        setCount,
        'setGen':
        setGen,
        'make_archived_widget':
        server_archive.make_archived_widget,
        'archived_widget_head':
        server_archive.archived_widget_head
    }
Beispiel #27
0
 def _redirect_to_version_view(request):
     path = request.matchdict['path']
     querystring = request.url[(request.url.rindex(request.path) +
                                len(request.path)):]
     redirect = '/%s/%s%s' % (route_prefix, path, querystring)
     raise HTTPTemporaryRedirect(redirect)
Beispiel #28
0
def newSessionProcess(dispatch, request, session, *args, **kwargs):
    storesession(session)
    sessionid = session['sessionid']
    logfilepath = sessionfile(sessionid, 'logfile', create=True)
    if sessionid in tasks and tasks[sessionid].is_alive():
        log.debug('cancelling stale task for  %s' % sessionid)
        tasks[sessionid].terminate()
        tasks[sessionid].join()
        del tasks[sessionid]
    else:
        tasks[sessionid] = PicnicTaskWrapper(sessionid=sessionid)
        log.debug("newSessionProcess - created task %s for %s" %
                  (repr(tasks[sessionid]), sessionid))
    session['rescode'] = ''
    folder = _sessionfolder(sessionid)
    for s in os.listdir(folder):
        if s.startswith('.') or s == 'logfile' or s.endswith(
                '.json') or s.endswith('.nc') or s.endswith('.cdl'):
            continue
        os.unlink(safejoin(folder, s))
    stdt = file(logfilepath, 'w')
    tasks[sessionid].new_task(sessionid=sessionid,
                              target=taskdispatch,
                              args=(dispatch, request, session, stdt))
    session['comment'] = 'inited'
    session['percentcomplete'] = 0.0
    session['task_started'] = datetime.strftime(datetime.utcnow(),
                                                json_dateformat)
    session['logfileurl'] = request.route_path('session_resource',
                                               session=sessionid,
                                               filename='logfile')
    dispatchers[dispatch](request, session, False)
    storesession(session)
    if haveUserTracking():
        import cgi_datauser
        if datacookiename in request.cookies:
            userid = request.cookies[datacookiename]
        #elif datacookiename in request.params:
        #    userid=request.params.getone(datacookiename)
        else:
            userid = "unknown"

        b = cgi_datauser.lidarwebdb()

        processDescription = {
            'taskid':
            sessionid,
            'uid':
            userid,
            'processtype':
            dispatch,
            'start_time':
            datetime.strptime(session['starttime'],
                              json_dateformat).strftime('%F %T'),
            'end_time':
            datetime.strptime(session['endtime'],
                              json_dateformat).strftime('%F %T'),
            'min_alt':
            session['altmin'],
            'max_alt':
            session['altmax'],
        }
        if 'timeres' in session:
            processDescription['timeres'] = session['timeres']
        if 'altres' in session:
            processDescription['altres'] = session['altres']
        if 'process_control' in session:
            processDescription['parameterstructure'] = json.dumps(
                session['process_control'], separators=(',', ':'))
        elif os.access(sessionfile(session, 'process_parameters.json'),
                       os.R_OK):
            processDescription['parameterstructure'] = json.dumps(
                loadjson(session, 'process_parameters.json'),
                separators=(',', ':'))
        dropfields = ['process_control', 'display_defaults', 'logfileurl']
        omitf = ['selected_fields', 'figstocapture']
        needcopy = False
        for f in dropfields + omitf:
            if f in session:
                needcopy = True
                break
        if needcopy:
            tsess = copy.deepcopy(session)
            for f in dropfields:
                if f in session:
                    del tsess[f]
            for f in omitf:
                if f in session:
                    tsess[f] = 'omitted'
        else:
            tsess = session
        processDescription['commandline'] = json.dumps(tsess,
                                                       separators=(',', ':')),

        b.addProcess(processDescription)

    log.debug('starting task for %s dispatch named %s (mypid = %d)' %
              (sessionid, dispatch, os.getpid()))
    tasks[sessionid].start(updateseconds=120, *args, **kwargs)
    stdt.close()
    return HTTPTemporaryRedirect(location=makeUserCheckURL(
        request, request.route_path('progress_withid', session=sessionid)))
Beispiel #29
0
def userCheck(request):
    #print 'URLREQ: ',request.matched_route.name
    req = request
    try:
        import cgi_datauser
    except:
        print "Couldn't load cgi_datauser from hsrl git codebase. user tracking disabled"
        jumpurl = ''
        parms = '?' + getFirst(req, 'PARAMS', '')
        if len(parms) <= 1:
            parms = '?' + request.query_string  #os.environ.get("QUERY_STRING","");
        jumpurl = getFirst(req, 'URL', '')
        if len(jumpurl) <= 0:
            jumpurl = '/'
            parms = ''
        dest = jumpurl + parms
        return HTTPTemporaryRedirect(location=dest)
    dbc = cgi_datauser.lidarwebdb()
    info = {}
    doForm = True
    fromSQL = False
    indebug = False  #True
    if len(
            getFirst(req, keyfield, '')
    ) > 0 or datacookiename in request.cookies or indebug:  #fixme maybe not read cookie here, just grab from form
        doForm = False
        if len(getFirst(req, keyfield, '')) > 0:
            keyv = getFirst(req, keyfield)
            if not isValidEmailAddress(keyv):
                doForm = True
            else:
                info[keyfield] = keyv
                hasreq = True
                for f in reqfields:
                    if len(getFirst(req, f, '')) > 0:
                        info[f] = getFirst(req, f)
                    else:
                        hasreq = False
                for f in optionalfields:
                    if len(getFirst(req, f, '')) > 0:
                        info[f] = getFirst(req, f)
                if not hasreq:  #work by lookup
                    ti = dbc.getUserByEMail(info[keyfield])
                    if ti:
                        info = ti
                        fromSQL = True
        elif datacookiename in request.cookies:
            ti = dbc.getUserByUID(request.cookies[datacookiename])
            if ti:
                info = ti
                fromSQL = True
        elif indebug:  #DEBUG ONLY
            ti = dbc.getUserByEMail("null")
            if ti == None:
                dbc.addClient({'email': 'null', 'name': 'bubba'})
                ti = dbc.getUserByEMail("null")
            info = ti
            fromSQL = True
        for f in reqfields:
            if not info.has_key(f):
                doForm = True
                break
    if not doForm:
        #print 'Not doing form'
        if not fromSQL:
            #print 'Not from SQL'
            uid = dbc.addClient(info)
        else:
            #print 'From SQL'
            uid = info['uid']
        if uid != None:
            #print 'have UID'
            parms = ''
            jumpurl = ''
            parms = '?' + getFirst(req, "PARAMS", '')
            if len(parms) <= 1:
                parms = '?' + request.query_string  #os.environ.get("QUERY_STRING","");
            jumpurl = getFirst(req, "URL", "")
            if len(jumpurl) <= 0:
                jumpurl = '/'
                parms = ''
            dest = jumpurl + parms
            if False and indebug:
                print "Content-Type: text/plain"
                print
                if len(cookies) > 0:
                    print cookies
                else:
                    print "No cookies"
                print "jump to %s" % dest
            else:
                bod = """
                <HTML><HEAD>
                <META HTTP-EQUIV="Refresh" CONTENT="0;url=%s">
                <TITLE>Registered</TITLE>
                </HEAD><BODY></BODY></HTML>
               """ % dest
            resp = Response(body=bod, content_type="text/html")
            resp.set_cookie(datacookiename, uid, max_age=timedelta(weeks=12))
            #print 'done. returning forward to',dest
            return resp
    #print 'Doing form'
    #form
    #info=dbc.getUserByEMail("null")
    #print "Content-Type: text/html"
    #if len(cookies)>0:
    #    print cookies
    #print
    info["URL"] = getFirst(req, "URL", "")
    info['PARAMS'] = getFirst(req, 'PARAMS', request.query_string)
    info["MYURL"] = request.path  #os.environ.get("SCRIPT_NAME","")
    #print 'form ops are',info

    fields = ("email", "name", "org")
    fielddesc = {
        "email": "E-Mail Address",
        "name": "Name",
        "org": "Organization"
    }

    return {
        'MYURL': info['MYURL'],
        'URL': info['URL'],
        'PARAMS': info['PARAMS'],
        'fields': fields,
        'info': info,
        'fielddesc': fielddesc,
        'reqfields': reqfields
    }
Beispiel #30
0
def authomatic_login(request):
    """
    Signs in a user session using an external provider.
    """

    provider_name = request.matchdict.get("provider_name", "").lower()
    response = Response()
    verify_provider(provider_name)
    try:
        authomatic_handler = authomatic_setup(request)

        # if we directly have the Authorization header, bypass authomatic login and retrieve 'userinfo' to signin
        if "Authorization" in request.headers and "authomatic" not in request.cookies:
            provider_config = authomatic_handler.config.get(provider_name, {})
            provider_class = resolve_provider_class(provider_config.get("class_"))
            provider = provider_class(authomatic_handler, adapter=None, provider_name=provider_name)
            # provide the token user data, let the external provider update it on login afterwards
            token_type, access_token = request.headers.get("Authorization").split()
            data = {"access_token": access_token, "token_type": token_type}
            cred = Credentials(authomatic_handler.config, token=access_token, token_type=token_type, provider=provider)
            provider.credentials = cred
            result = LoginResult(provider)
            # pylint: disable=W0212
            result.provider.user = result.provider._update_or_create_user(data, credentials=cred)  # noqa: W0212

        # otherwise, use the standard login procedure
        else:
            result = authomatic_handler.login(WebObAdapter(request, response), provider_name)
            if result is None:
                if response.location is not None:
                    return HTTPTemporaryRedirect(location=response.location, headers=response.headers)
                return response

        if result:
            if result.error:
                # Login procedure finished with an error.
                error = result.error.to_dict() if hasattr(result.error, "to_dict") else result.error
                LOGGER.debug("Login failure with error. [%r]", error)
                return login_failure(request, reason=result.error.message)
            if result.user:
                # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
                # update the user to get more info.
                if not (result.user.name and result.user.id):
                    try:
                        response = result.user.update()
                    # this error can happen if providing incorrectly formed authorization header
                    except OAuth2Error as exc:
                        LOGGER.debug("Login failure with Authorization header.")
                        ax.raise_http(http_error=HTTPBadRequest, content={"reason": str(exc.message)},
                                      detail=s.ProviderSignin_GET_BadRequestResponseSchema.description)
                    # verify that the update procedure succeeded with provided token
                    if 400 <= response.status < 500:
                        LOGGER.debug("Login failure with invalid token.")
                        ax.raise_http(http_error=HTTPUnauthorized,
                                      detail=s.ProviderSignin_GET_UnauthorizedResponseSchema.description)
                # create/retrieve the user using found details from login provider
                return login_success_external(request,
                                              external_id=result.user.username or result.user.id,
                                              email=result.user.email,
                                              provider_name=result.provider.name,
                                              external_user_name=result.user.name)
    except Exception as exc:
        exc_msg = "Unhandled error during external provider '{}' login. [{!s}]".format(provider_name, exc)
        LOGGER.exception(exc_msg, exc_info=True)
        ax.raise_http(http_error=HTTPInternalServerError, detail=exc_msg)

    LOGGER.debug("Reached end of login function. Response: %r", response)
    return response