Exemplo n.º 1
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
    }
Exemplo n.º 2
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}
Exemplo n.º 3
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)))
Exemplo n.º 4
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)))