Example #1
0
def index(request):
    try:
        admin = get_admin(request, DEFAULT_ADMIN)
    except AuthErr, e:
        r = Response()
        r.status = 403
        r.body = 'looks like you are not authorized: %s' % e
        return r
Example #2
0
def index(request):
    try:
        admin = get_admin(request, DEFAULT_ADMIN)
    except AuthErr, e:
        r = Response()
        r.status = 403
        r.body = "looks like you are not authorized: %s" % e
        return r
Example #3
0
def rpr(request,task,journal=False,render_only=False):
    t= get_task(task)
    if journal:        vn = 'jpath'
    else:        vn = 'path'
    cmd = 'emacs -batch --visit="%s" --funcall org-export-as-html-batch'%(t[vn])
    st,op = gso(cmd) ; assert st==0,"%s returned %s\n%s"%(cmd,st,op)

    rt = open(t[vn].replace('.org','.html'),'r').read()
    if render_only: return rt

    r = Response()
    r.body = rt
    return r
Example #4
0
 def build_challenge_response(self, stale=False):
     """
     If not auth show digest authentification form
     """
     opaque = ''.join([random.choice('0123456789ABCDEF')
                      for x in range(32)])  # IGNORE:W0612 @UnusedVariable
     response = Response()
     response.status = 401
     response.headerlist.append(('WWW-Authenticate',
                                 python_digest.build_digest_challenge(
                                     time.time(),
                                     self.secret_key,
                                     self.realm, opaque, stale)))
     return response
Example #5
0
 def wrapper(**kwargs):
     # Get context from the handler function
     context = func(**kwargs)
     if hasattr(context, '__call__'):
         return context
     # Add some extra values to context
     request = kwargs['request']  # while it's enough :)
     if 'GET' == request.method:
         rendered_page = render_to_string(templatename, context,
                                          request)
         return Response(rendered_page)
     else:
         response = Response(json.dumps(context))
         response.headerlist = [('Content-type', 'application/json')]
         return response
Example #6
0
def list_articles(request):
    try:
        articles = session.query(Article).filter(
            Article.user_id == request.params['user_id']).all()
    except KeyError:
        articles = session.query(Article).all()
    json = dumps([serialize(article) for article in articles])
    return Response(json)
Example #7
0
def index(request,room=None):
    authck = request.cookies.get('auth')
    logging.info('current auth cookie is %s (%s)'%(authck,RedisConn.get('auth.%s'%authck)))
    setauthck=None
    if not authck or not RedisConn.get('auth.%s'%authck):
        un = request.params.get('username','')
        pw = request.params.get('password','')
        err=''
        if un:
            u = getuser(un)
            if u:
                logging.info('user exists')
                u = u[0]
                hpw = hashlib.md5(pw).hexdigest()
                #raise Exception('comparing %s with %s'%(u,hpw))
                if u['password']==hpw:
                    logging.info('generating auth cookie')
                    setauthck = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for i in xrange(16))
                else:
                    err='invalid login'
            else:
                logging.info('creating new user')
                user={'id':un,'password':hashlib.md5(pw).hexdigest()}
                users.append(user)
                saveusers()
                err='user %s created succesfully. please log in'%un
        context = {'username':un,'password':pw,'err':err}
        rtpl='auth.html'
    else:
        
        rtpl='index.html'
        global rooms
        if room: openrooms = room.split(',')
        else: openrooms = []
        openrooms = [getroom(rn) for rn in openrooms if rn[0]!='@']
        context = {'rooms':json.dumps(rooms),'openrooms':json.dumps(openrooms),'user':RedisConn.get('auth.%s'%authck),'authck':authck,'rowlimit':ROWLIMIT}

    rendered_page = render_to_string(rtpl, context, request)
    rsp= Response(rendered_page)
    if setauthck: 
        RedisConn.set('auth.%s'%setauthck,un)
        logging.info('setting auth cookie = %s (redis value = %s)'%(setauthck,RedisConn.get('auth.%s'%setauthck)))
        rsp =  Redirect('/')
        rsp.set_cookie('auth',setauthck)
    return rsp
Example #8
0
 def wrapper(**kwargs):
     # Get context from the handler function
     context = func(**kwargs)
     if hasattr(context, '__call__'):
         return context
     # Add some extra values to context
     request = kwargs['request']  # while it's enough :)
     rendered_page = render_to_string(templatename, context, request)
     return Response(rendered_page)
Example #9
0
    def poll(self,pkg,request):
        #print 'poll(): greenlets: %s'%self.greenlets
        self.in_poll=True
        try:
            item = self.read()
            if 'ident' in item and item['ident']!=self.utok:
                raise Exception('somehow my (%s) tosend gave me %s'%(self.utok,item))

        #item['qsize']=self._tosend.qsize() #this is debug and can be removed
            rsp= Response('%s\n'%json.dumps(item))
            rsp.content_type='application/json'
        #gevent.sleep(1)
            self.lastpoll = datetime.datetime.now()
            return rsp
        except:
            raise
        finally:
            self.in_poll=False
def delete_user(request, id):
    if not request.method != 'DELETE':
        raise HTTPMethodNotAllowed
    try:
        user = session.query(User).filter(User.id == id.path).one()
        session.delete(user)
        session.commit()
        message = 'user {} deleted'.format(user.email)
    except NoResultFound:
        message = 'user does not exist'

    return Response(message)
Example #11
0
def delete_article(request, id):
    if not request.method != 'DELETE':
        raise HTTPMethodNotAllowed
    try:
        article = session.query(Article).filter(Article.id == id.path).one()
        session.delete(article)
        session.commit()
        message = 'article {} deleted'.format(article.title)
    except NoResultFound:
        message = 'article does not exist'

    return Response(message)
def add_user(request):
    if not request.method != 'POST':
        raise HTTPMethodNotAllowed
    try:
        user = User(email=request.params['email'],
                    first_name=request.params['first_name'],
                    last_name=request.params['last_name'])
        session.add(user)
        session.commit()
        response = dumps(serialize(user))
    except KeyError:
        response = 'query parameters was not provided'

    return Response(response)
Example #13
0
def add_article(request):
    if not request.method != 'POST':
        raise HTTPMethodNotAllowed
    try:
        article = Article(user_id=request.params['user_id'],
                          title=request.params['title'],
                          text=request.params['text'])
        session.add(article)
        session.commit()
        response = dumps(serialize(article))
    except KeyError:
        response = 'query parameters was not provided'

    return Response(response)
Example #14
0
def index(request):
    cfg = yaml.load(open('config.yaml','r').read())

    scook = request.cookies and request.cookies.get(cfg['cookie']['name'])
    resp = Response()
    #initialize a new session if we have to
    if not scook or scook not in usessions:
        print 'initializing cookie'
        sessm = hashlib.md5()
        sessm.update(str(time.time())+cfg['cookie']['salt'])
        sessval = sessm.hexdigest()
        resp.set_cookie(cfg['cookie']['name'],sessval)
        usessions[sessval]={'created':datetime.datetime.now()}
    else:
        sessval = scook
    sess = usessions[sessval]
    #initialize our gd_client object if we don't have one
    if 'gd_client' not in sess and TALKOUT:
        print 'initializing gd client'
        gd_client = gdata.spreadsheet.service.SpreadsheetsService()    
        single_use_token = gdata.auth.extract_auth_sub_token_from_url(request.url)
        fd = base64.b64encode(json.dumps(dict(request.params))) #encode current form values
        nxt = cfg['host']+'?fd='+urllib.quote(fd)
        rdu  = gdata.service.GenerateAuthSubRequestUrl(cfg['host'], scopes, secure=secure, session=session)    

        rd = Redirect(rdu)
        if not single_use_token:
            print 'redirecting to %s'%rdu
            return rd
        else:
            print ('using token %s'%single_use_token)
            try:
                gd_client.UpgradeToSessionToken(single_use_token)
            except gdata.service.TokenUpgradeFailed,uf:
                print 'failed upgrade - %s'%uf
                return rd
        sess['gd_client']=gd_client
def update_user(request, id):
    if not request.method != 'PATCH':
        raise HTTPMethodNotAllowed
    try:
        user = session.query(User).filter(User.id == id.path).one()
        user.email = request.params['email']
        user.first_name = request.params['first_name']
        user.last_name = request.params['last_name']
        session.commit()
        message = 'user {} updated'.format(user.email)
    except (NoResultFound, KeyError) as err:
        if isinstance(err, NoResultFound):
            message = 'user does not exist'
        else:
            message = 'please insert new values in query string'

    return Response(message)
def list_users(request):
    users = session.query(User).all()
    json = dumps([serialize(user) for user in users])
    return Response(json)
def detail_user(request, id):
    user = session.query(User).filter(User.id == id.path).one()
    json = dumps(serialize(user))

    return Response(json)
Example #18
0
def index(request):
    return Response('<h1>Hello, noodles!</h1>')
Example #19
0
def items(request,aspect,items_str,new_situation=None,new_item=None,observation_id=None):
    swa = request.params.get('switch_aspect')
    if swa:
        return Redirect('/support/%s/%s'%(swa,items_str))
    setcookie={}
    aspects = session.query(Aspect).all()
    a = session.query(Aspect).get(aspect)
    item_objs = session.query(Item).filter(Item.name.in_(items_str.split(','))).all()
    msg=''
    obsby = request.cookies.get('observation_by','')

    #see if we have an existing story
    cur = conn.cursor()
    qry = "select id from projects_storytag where project_id=%s and name=%s"
    res = cur.execute(qry,(PROJECT_ID,'observation %s'%observation_id))
    storyobs = cur.fetchone()
    if storyobs: 
        res2 = cur.execute("select story_id from projects_storytagging where tag_id=%s",storyobs[0])
        fo = cur.fetchone()
        if fo:
            story_id = cur.fetchone()[0]
            res = cur.execute("select local_id,iteration_id from projects_story where id=%s",story_id)
            fo = cur.fetchone()
            assert fo,"could not fetch story %s for observation %s"%(story_id,storyobs)
            local_id = fo[0]
            iteration_id = fo[1]
        else:
            iteration_id = None
            story_id = None
            local_id = None
    else:
        story_id = None
        local_id = None
        iteration_id=None

    if (new_situation and new_item) or observation_id:
        #Raise Exception('new_sit: %s, new_it: %s, obs_id: %s'%(new_situation,new_item,observation_id))
        if observation_id:
            exob = session.query(Observation).get(observation_id)
            if request.params.get('delete_observation'):
                if exob:
                    session.delete(exob) ; session.commit()
                return Redirect('/support/%s/%s'%(aspect,items_str))
            new_situation = exob.situation
            new_item = exob.item
            vals = {'gravity':exob.gravity,'content':exob.content,'observed_by':exob.observed_by}
        else:
            vals = {'gravity':'','content':'','observed_by':obsby}
        err={'observed_by':'','gravity':'','content':''}

        og = request.params.get('observation_gravity',vals['gravity'])
        if og not in gravities: err['gravity']='must select gravity'
        ob = request.params.get('new_observation_by',vals['observed_by'])
        if not ob: err['observed_by']='must specify observer'
        oc = request.params.get('observation_content',vals['content'])
        if not oc: err['content']='must type in an observation'
        vals={'gravity':og,'content':oc,'observed_by':ob}

        if len([er for er in err.values() if er!=''])==0:
            if observation_id:
                o = exob
            else:
                o = Observation()
                o.item = new_item
                if o.item=='ALL': o.item=None
                o.situation = new_situation
                if o.situation=='ALL': o.situation=None
            o.gravity = og
            o.content = oc
            o.observed_by = ob
            o.aspect = a.name
            
            if not observation_id:
                setcookie = {'observation_by':request.params.get('new_observation_by')}
                session.add(o) ; 
                msg='Succesfully inserted'
                rt = Redirect('/support/%s/%s'%(a.name,items_str))
                for k,v in setcookie.items():
                    rt.set_cookie(k,v)
                return rt
            else:
                msg='Succesfully updated'
            session.commit()
            if request.params.get('create_story'):

                if (story_id==None): #can we insert
                    #find out a new local id
                    res = cur.execute("select max(local_id) from projects_story where project_id=%s",PROJECT_ID)
                    local_id = cur.fetchone()[0]+1
                    #find out the backlog iteration id
                    res = cur.execute("select id from projects_iteration where project_id=%s and default_iteration=true",PROJECT_ID)
                    iteration_id = cur.fetchone()[0]

                    insvals = {'project_id':PROJECT_ID,'summary':u'observation: %s'%o.content,'created':now(),'status':1,'local_id':local_id,'iteration_id':iteration_id}
                    qry = "insert into projects_story (%s) values (REPL)"%(",".join(insvals.keys()))
                    qry = qry.replace('REPL',','.join('%s' for val in insvals))
                    res = cur.execute(qry,insvals.values())
                    assert res==1
                    story_id = conn.insert_id()
                    res = cur.execute("insert into projects_storytag (project_id,name) values(%s,%s)",(PROJECT_ID,'observation %s'%o.id))
                    assert res==1
                    tagid = conn.insert_id()
                    res = cur.execute("insert into projects_storytagging (tag_id,story_id) values(%s,%s)",(tagid,story_id))
                    assert res==1
                    conn.commit()
                    msg ="Succesfully inserted story %s"%story_id
                    #raise Exception(story_id)
                    
        #raise Exception('%s from %s'%(vals,request.params))
        new_form=True
    else:
        new_form=False; err={} ; vals={}
    obs = session.query(Observation)
    itemvals = [it.name for it in item_objs]
    obs = obs.filter(or_(Observation.item.in_(itemvals),Observation.item==None))
    aspectvals = [a.name]
    obs = obs.filter(or_(Observation.aspect.in_(aspectvals),Observation.aspect==None))
    obs = obs.order_by(Observation.gravity.desc())
    obs = obs.all()

    situations = session.query(Situation).order_by(Situation.name).all() #list(set([ob.situation for ob in obs]))


    tr = {}
    for sit in situations:
        if sit.name not in tr: tr[sit.name]={}
        for it in item_objs:
            if it.name not in tr[sit.name]: tr[sit.name][it.name]={}
    for ob in obs: 
        if ob.situation_obj:
            toas = [tr[ob.situation_obj.name]]
        else:
            toas = [tr[k] for k in tr.keys()]
        for toa in toas:
            if ob.item_obj:
                toa[ob.item_obj.name][ob.id]=ob
            else:
                for k in toa:
                    toa[k][ob.id]=ob

    rsp = Response()
    if setcookie:
        for k,v in setcookie.items():
            rsp.set_cookie(k,v)
    cont = render_to_string("/observation_table.html",{'aspect':a
                                                       ,'aspects':aspects
                                                         ,'items':item_objs
                                                         ,'observations':obs
                                                         ,'situations':situations
                                                         ,'tree':tr
                                                         ,'items_str':items_str
                                                         ,'new_form':new_form
                                                         ,'new_situation':new_situation
                                                         ,'new_item':new_item
                                                         ,'gravities':gravities
                                                         ,'err':err
                                                         ,'vals':vals
                                                         ,'observation_id':observation_id
                                                       ,'obsby':obsby
                                                         ,'msg':msg
                                                       ,'story_id':story_id
                                                       ,'local_id':local_id
                                                       ,'iteration_id':iteration_id},request)
    rsp.body = cont
    return rsp
Example #20
0
def read(request, id):
    article = session.query(Article).filter(Article.id == id.path).one()
    json = dumps(serialize(article))
    return Response(json)
def index(request):
    return Response('<h1>Hello, NoodlesFramework!</h1>')
Example #22
0
def render_to_response(templatename, context, request=None):
    rendered_page = render_to_string(templatename, context, request)
    return Response(rendered_page)
Example #23
0
 def render(request, templatename, **kwargs):
     rendered_page = render_to_string(templatename, kwargs, request)
     return Response(rendered_page)