Пример #1
0
    def POST(self):
        if not session().logged:
            raise web.seeother('/register')

        i = web.input(authors="",
                      url=None,
                      title=None,
                      comments=[],
                      year=None,
                      enabled=True,
                      subtitle='',
                      time=datetime.utcnow(),
                      votes=1,
                      cite={
                          'mla': '',
                          'apa': '',
                          'chicago': ''
                      })
        db = Db('db/openjournal')

        def next_pid():
            papers = db.get('papers')
            return papers[-1]['pid'] + 1 if papers else 0

        i.submitter = session()['uname']
        if i.authors:
            i.authors = map(self.parse_author, i.authors.split(','))
        i.pid = next_pid()
        record_submission(i.submitter, i.pid)
        record_vote(i.submitter, i.submitter, i.pid)
        db.append('papers', dict(i))
        Search().index()
        raise web.seeother('/')
Пример #2
0
    def POST(self):
        """Organize/sort the comments according to votes, author,
        time, etc (heuristic)
        """
        i = web.input(pid=None, time=datetime.utcnow().ctime(),
                      comment="", username=session()['uname'], votes=0,
                      enabled=True)
        if i.pid:
            i.pid = int(i.pid)
            i.cid = 0 #sets default cid val if first comment

            if not session().logged:
                raise web.seeother('/login?redir=/item=?pid=%s' % i.pid)
            try:
                db = Db('db/openjournal')
                papers = db.get('papers')                 
                paper = papers[i.pid] #XXX get by key 'pid' instead
                if paper['comments']:
                    i.cid = paper['comments'][-1]['cid'] + 1
                papers[i.pid]['comments'].append(dict(i))
                db.put('papers', papers)
                record_comment(i.username, i.pid, i.cid)
                return render().item(i.pid, paper)
            except IndexError:
                return "No such item exists, id out of range"
        raise web.seeother('/')        
Пример #3
0
    def POST(self):
        i = web.input(username='', email='', password='', redir='/')
        i.email = i.email.lower()

        u = User.register(i.username, i.password, email=i.email)

        if User.authenticate(i.username, i.password, u.salt, u.uhash):
            # Logic to populate session() with user vars:
            session().logged = True
            session().username = i.username

            # migrate elsewhere, maybe utils redir
            if i.redir:
                if not i.redir[0] == "/":
                    i.redir = "/" + i.redir
                elif i.redir[0] == "/":
                    i.redir = "/"
                raise web.seeother(web.ctx.homedomain + i.redir)
            raise web.seeother(web.ctx.homedomain + "/account")
        return render().login(msg=ERROR_LOGIN_PASSWD['key'])


        session().logged = True
        session().username = i.username
        raise web.seeother('/account')
Пример #4
0
 def POST(self):
     i = web.input(email=None, passwd=None, imap="imap.gmail.com")
     session().email = i.email
     session().passwd = i.passwd
     session().imap = i.imap
     if getattr(session(), 'passwd', None):            
         raise web.seeother('/emails?page=0&limit=10')
     raise web.seeother('/login')
Пример #5
0
 def GET(self):
     """Invalidate session, etc"""
     i = web.input(redir='')
     session().update({'logged': False,
                       'uname': '',
                       'karma': 0,
                       })
     session().kill()
     if i.redir:
         raise web.seeother(i.redir)
     raise web.seeother('/')
Пример #6
0
 def GET(self, uid=None):
     i = web.input(page=0, limit=10)
     if getattr(session(), 'passwd', None) and uid:
         mail = Mailbox()
         if uid:
             return render().email(uid, email=mail.read(uid))
     raise web.seeother('/login')
Пример #7
0
 def GET(self, username=""): 
     if username:
         try:
             user = Academic.get(username, safe=True)
             return render().profiles.index(user)
         except:
             pass
     raise web.seeother('/')
Пример #8
0
 def GET(self):
     try:
         del session().email
         del session().passwd
     except:
         pass
     session().kill()
     raise web.seeother('/')
Пример #9
0
 def GET(self, username=""): 
     if username:
         try:
             user = User.get(username, safe=True)
             return render().profiles.index(user)
         except:
             pass
     raise web.seeother('/')
Пример #10
0
 def GET(self):
     i = web.input(redir='')
     session().logged = False
     session().username= ''
     session().kill()
     if i.redir:
         raise web.seeother(i.redir)
     #raise redir2login(redir='/login')
     return render().auth.login(resp=LOGGED_OUT)
Пример #11
0
 def inner(*args, **kwargs):
     logged = False
     if value in [None, True, False]:
         if session()[key] is value:
             logged = True
     if session()[key] != value:
         if session()[key] == value:
             logged = True
     if logged:
         raise web.seeother(redir)
Пример #12
0
    def GET(self):
        i = web.input(page=0, limit=10)

        if getattr(session(), 'passwd', None):
            mail = Mailbox()
            page, limit = int(i.page), int(i.limit)
            offset = page * limit
            emails = mail.newest(limit=limit, offset=offset)
            return render().ui(emails=emails, page=page, limit=limit)
        raise web.seeother('/login')
Пример #13
0
 def GET(self):
     """Invalidate session, etc"""
     i = web.input(redir='')
     session().logged = False
     session().uid = None
     session().uname = ''
     session().kill()
     if i.redir:
         raise web.seeother(i.redir)
     return "Logged out"
Пример #14
0
    def POST(self):
        i = web.input(username='', passwd='', redir='/')

        if session().logged:
            raise web.seeother(i.redir)

        if not Academic.validates(i.username, i.passwd):
            return render().auth.login(err=AUTH_ERR['malformed_creds'])

        # attempting login first
        if login(i.username, i.passwd):
            raise web.seeother(i.redir)

        try:
            u = Academic.register(i.username, i.passwd, **Academic.defaults())
            u.login()
            raise web.seeother(i.redir)
        except Academic.RegistrationException as e:
            err = AUTH_ERR[str(e.message)]
        return render().auth.register(err=err)
Пример #15
0
    def POST(self):
        """TODO: handle redir"""
        i = web.input(username='', passwd='', redir='/')

        if not Academic.validates(i.username, i.passwd):
            return render().auth.login(err=AUTH_ERR['malformed_creds'])

        if login(i.username, i.passwd):
            raise web.seeother(i.redir)

        return render().auth.login(err=AUTH_ERR['wrong_creds'])
Пример #16
0
    def POST(self):
        i = web.input(username='', passwd='', redir='/')

        if session().logged:
            raise web.seeother(i.redir)

        if not Academic.validates(i.username, i.passwd):
            return render().auth.login(err=AUTH_ERR['malformed_creds'])

        # attempting login first
        if login(i.username, i.passwd):
            raise web.seeother(i.redir)

        try:
            u = Academic.register(i.username, i.passwd, **Academic.defaults())
            u.login()
            raise web.seeother(i.redir)
        except Academic.RegistrationException as e:
            err = AUTH_ERR[str(e.message)]
        return render().auth.register(err=err)
Пример #17
0
    def POST(self):
        i = web.input(authors=None, url=None, title=None, comments=[],
                      year=None, enabled=False, submitter='',
                      subtitle='', time=datetime.utcnow(),
                      cite={'mla': '', 'apa': '', 'chicago': ''})
        i.authors = map(parse_author, i.authors.split(','))

        # abstract db out of routes
        db = Db('db/openjournal')
        db.append('papers', dict(i))
        raise web.seeother('/')
Пример #18
0
    def POST(self):
        """TODO: handle redir"""
        i = web.input(username='', passwd='', redir='/')

        if not Academic.validates(i.username, i.passwd):
            return render().auth.login(err=AUTH_ERR['malformed_creds'])

        if login(i.username, i.passwd):
            raise web.seeother(i.redir)

        return render().auth.login(err=AUTH_ERR['wrong_creds'])
Пример #19
0
 def POST(self):
     i = web.input(email="", password="", password_confirm="")
     if not waltz.utils.valid_email(i.email):
         return self.GET(msg="invalid email")
     try:
         u = User(i.email)
     except:
         u = User.register(i.email, i.password, passwd2=i.password_confirm)
         session().update({'logged': True,
                           'email': i.email})
         raise web.seeother('/')
     return Login().GET(msg="User already exists")
Пример #20
0
    def POST(self):
        i = web.input(to="", cc="", bcc="", subject="", tags="", message="")
        if not getattr(session(), 'passwd', None):
            raise web.seeother('/login')

        resp = "success"
        try:            
            if 'passwd' in session() and session().passwd:
                tags = [str('#%s' % tag.strip()) if tag[0] != '#' else str(tag.strip()) \
                            for tag in i.tags.split(',')]
                message = unescape_html("%s %s" % (i.message, tags) if tags else i.message)
                mailman = Mailman(session()['email'], session()['passwd'])
                mailman.sendmail(sender=session().email, subject=i.subject,
                                 recipients=[i.to], msg=message, fmt="html")
            else:
                raise Exception("Email not sent, account credentials " \
                                    "could not be verified.")
        except Exception as e:
            return e
            resp = "failure"
        raise web.seeother(web.ctx.homedomain + '?response=' + resp)
Пример #21
0
 def POST(self):        
     i = web.input(email="", password="")
     if not waltz.utils.valid_email(i.email):
         return self.GET(msg="invalid email")
     try:
         u = User(i.email)
     except AttributeError:
         return self.GET(msg="no such user")
     if u.authenticate(i.password):
         session().update({'logged': True,
                           'email': i.email})
         raise web.seeother('/')
     return self.GET(msg="invalid credentials")
Пример #22
0
 def GET(self):
     i = web.input(pid=None, comment=None)
     if i.pid:            
         try:
             papers = db.get('papers')
             paper = papers[int(i.pid)]
             if i.comment:
                 comment = paper['comments'][int(i.comment)]
                 return render().comment(i.pid, comment)
             return render().item(i.pid, paper)
         except IndexError:
             return "No such item exists, id out of range"
     raise web.seeother('/')
Пример #23
0
    def POST(self):
        if not session().logged:
            raise web.seeother('/register')

        i = web.input(authors="", url=None, title=None, comments=[],
                      year=None, enabled=False, subtitle='',
                      time=datetime.utcnow(), votes=1,
                      cite={'mla': '', 'apa': '', 'chicago': ''})
        db = Db('db/openjournal')

        def next_pid():
            papers = db.get('papers')
            return papers[-1]['pid'] + 1 if papers else 0

        i.submitter = session()['uname']
        if i.authors:
            i.authors = map(self.parse_author, i.authors.split(','))
        i.pid = next_pid()
        record_submission(i.submitter, i.pid)
        record_vote(i.submitter, i.submitter, i.pid)
        db.append('papers', dict(i))
        Search().index()
        raise web.seeother('/')
Пример #24
0
    def POST(self):
        def defusr():
            return {'karma': 0,
                    'comments': [],
                    'votes': [],
                    'posts': [],
                    'created': datetime.datetime.utcnow(),
                    'bio': '',
                    'email': ''}

        i = web.input(username='', passwd='', redir='')
        if i.username and i.passwd:            
            if re.match(username_regex, i.username):
                if re.match(passwd_regex, i.passwd):
                    try:
                        # treat as login if creds are right
                        u = User.get(i.username)
                        if User.easyauth(u, i.passwd):
                            loadsession(u)
                            raise web.seeother('/')
                    except:
                        pass

                    try:
                        u = User.register(i.username, i.passwd,
                                          **defusr())
                        loadsession(u)
                        raise web.seeother('/')
                    except:
                        err = "Username unavailable"
                else:
                    err = passwd_err
            else:
                err = username_err
        else:
            err = "Please enter all required fields"
        return render().auth.register(err=err)
Пример #25
0
    def GET(self):
        """Research http://news.ycombinator.com/item?id=1781013 how
        hacker news voting works and emulate

        XXX Restrict voting to session().logged users + element id
        must not already exist in user['votes'] set.

        XXX Requires accounting + record keeping

        XXX Preserve the web.ctx GET query params to preserve sorting
        / ordering

        Algo:
        1. Add karma to paper['submitter'] if vote
        2. Record vote in user['votes'] set by id
        - calc unique vote id via some linear combination of paper pid
          (and or comment id [cid], if it exists)
        """
        msg = None
        i = web.input(pid=None, sort="popular")
        
        if not session().logged:
            raise web.seeother('/register')
        db = Db('db/openjournal')
        ps = db.get('papers')
        u = User.get(session()['uname'])
        if i.pid:
            i.pid = int(i.pid)
            if canvote(u, i.pid):
                try:
                    ps[i.pid]['votes'] += 1
                    db.put('papers', ps)
                    submitter_uname = ps[i.pid]['submitter']
                    record_vote(u['username'], submitter_uname, i.pid)
                except IndexError:
                    return "No such items exists to vote on"
        raise web.seeother('/?sort=%s' % i.sort)
Пример #26
0
    def GET(self):
        """Research http://news.ycombinator.com/item?id=1781013 how
        hacker news voting works and emulate

        XXX Restrict voting to session().logged users + element id
        must not already exist in user['votes'] set.

        XXX Requires accounting + record keeping

        XXX Preserve the web.ctx GET query params to preserve sorting
        / ordering

        Algo:
        1. Add karma to paper['submitter'] if vote
        2. Record vote in user['votes'] set by id
        - calc unique vote id via some linear combination of paper pid
          (and or comment id [cid], if it exists)
        """
        i = web.input(pid=None, sort="popular")

        if not session().logged:
            raise web.seeother('/register')

        if i.pid:
            i.pid = int(i.pid)
            u = Academic(session()['uname'])
            p = Paper(i.pid)
            if canvote(u, i.pid):
                try:
                    # move set_vote to paper api
                    p.votes += 1
                    p.save()
                    record_vote(u['username'], p.submitter, i.pid)
                except IndexError:
                    return "No such items exists to vote on"
        raise web.seeother('/?sort=%s' % i.sort)
Пример #27
0
 def POST(self):
     """TODO: handle redir"""
     i = web.input(username='', passwd='', redir='')
     if i.username and i.passwd:
         try:
             u = User.get(i.username)
             if User.easyauth(u, i.passwd):
                 loadsession(u)
                 raise web.seeother('/')
         except:
             raise
         err = "Incorrect username or password"
     else:
         err = "Please provide all required fields"
     return render().auth.login(err=err)
Пример #28
0
    def GET(self):
        """Research http://news.ycombinator.com/item?id=1781013 how
        hacker news voting works and emulate

        XXX Restrict voting to session().logged users + element id
        must not already exist in user['votes'] set.

        XXX Requires accounting + record keeping

        XXX Preserve the web.ctx GET query params to preserve sorting
        / ordering

        Algo:
        1. Add karma to paper['submitter'] if vote
        2. Record vote in user['votes'] set by id
        - calc unique vote id via some linear combination of paper pid
          (and or comment id [cid], if it exists)
        """
        i = web.input(pid=None, sort="popular")
        
        if not session().logged:
            raise web.seeother('/register')

        if i.pid:
            i.pid = int(i.pid)
            u = Academic(session()['uname'])
            p = Paper(i.pid)
            if canvote(u, i.pid):
                try:
                    # move set_vote to paper api
                    p.votes += 1
                    p.save()                    
                    record_vote(u['username'], p.submitter, i.pid)
                except IndexError:
                    return "No such items exists to vote on"
        raise web.seeother('/?sort=%s' % i.sort)
Пример #29
0
 def POST(self):
     """Organize/sort the comments according to votes, author,
     time, etc (heuristic)
     """
     i = web.input(pid=None, time=datetime.utcnow().ctime(),
                   comment="", user="******", votes=0)
     if i.pid:
         try:
             papers = db.get('papers') 
             paper = papers[int(i.pid)]
             papers[int(i.pid)]['comments'].append(dict(i))
             db.put('papers', papers)
             return render().item(i.pid, paper)
         except IndexError:
             return "No such item exists, id out of range"
     raise web.seeother('/')        
Пример #30
0
    def POST(self):
        i = web.input(q="", p='0', rows=50, page=1)
        serp = "<p>No Results Found</p>"
        zeroclick=""
        if i.p == '0' and 'http://' in i.q:
            zeroclick = '<img style="height: 50px;" src="http://archive.org/images/wayback.gif"/><span style="position: relative; top: -14px; margin-left: 10px;"><a style="margin-left: 10px;" href="http://web.archive.org/web/*/%s">View older versions o1f %s</a><span>' % (i.q, i.q)
            raise web.seeother('http://web.archive.org/web/*/%s' % i.q)

        # Fallback to seach all mediatypes
        if i.q:
            r = requests.post('http://archive.org/advancedsearch.php',
                              data={'q': i.q.replace('http://', ''),
                                    'rows': i.rows,
                                    'page': i.page, 'output': 'json'})
            serp = r.json
        return render().serp(query=i.q, p=i.p, serp=serp,
                             page=i.page, rows=i.rows,
                             zeroclick=zeroclick)
Пример #31
0
    def POST(self):
        """Organize/sort the comments according to votes, author,
        time, etc (heuristic)

        POST route to add a comment to a paper
        side effects:
        - handles votes / karma
        """
        i = web.input(pid=None, cid=None, comment="", opt="", enabled=True)
        option = i.pop('opt')

        try:  # getting the requested paper
            i.pid = int(i.pid)
            paper = Paper(i.pid)
        except (TypeError, IndexError):
            # TODO: Log
            # IndexEror("No such paper") or
            # TypeError("int() arg must be str or number, not 'NoneType'")
            raise web.notfound()

        if not i.comment:
            return render().item(paper)

        if not session().logged:
            raise web.seeother('/login?redir=/item?pid=%s' % i.pid)
        else:
            i.username = session()['uname']

        if option == "edit":
            try:
                paper.edit_comment(i.cid, content=i.comment, enabled=i.enabled)

            except (TypeError, ValueError) as e:
                # XXX Log error e
                return render().item(paper)
        else:
            i.cid = paper.add_comment(i.cid,
                                      session()['uname'],
                                      content=i.comment,
                                      votes=paper.votes,
                                      enabled=i.enabled)
            record_comment(session()['uname'], i.pid, i.cid)
        return render().item(paper)
Пример #32
0
 def GET(self):
     i = web.input(pid=None, cid=None)
     if i.pid:
         i.pid = int(i.pid)
         try:
             db = Db('db/openjournal')
             papers = db.get('papers')
             paper = papers[i.pid]
             if i.cid:
                 i.cid = int(i.cid)
                 # XXX Revise data storage scheme s.t. comment can
                 # be retrieved by cid pkey, not i.cid'th index (below)
                 # reason: cnnt can be deleted and lead to consistency
                 # errors (id would then reference wrong entity)
                 comment = paper['comments'][i.cid]
                 return render().comment(i.pid, i.cid, comment)
             return render().item(i.pid, paper)
         except IndexError:
             return "No such item exists, id out of range"
     raise web.seeother('/')
Пример #33
0
    def POST(self):
        """Organize/sort the comments according to votes, author,
        time, etc (heuristic)

        POST route to add a comment to a paper
        side effects:
        - handles votes / karma
        """
        i = web.input(pid=None, cid=None, comment="", opt="", enabled=True)
        option = i.pop('opt')

        try: # getting the requested paper
            i.pid = int(i.pid)
            paper = Paper(i.pid)
        except (TypeError, IndexError):
            # TODO: Log
            # IndexEror("No such paper") or 
            # TypeError("int() arg must be str or number, not 'NoneType'")
            raise web.notfound()

        if not i.comment:
            return render().item(paper)

        if not session().logged:
            raise web.seeother('/login?redir=/item?pid=%s' % i.pid)
        else:
            i.username = session()['uname']

        if option == "edit":
            try:
                paper.edit_comment(i.cid, content=i.comment, enabled=i.enabled)
                
            except (TypeError, ValueError) as e:
                # XXX Log error e
                return render().item(paper)
        else:
            i.cid = paper.add_comment(i.cid, session()['uname'], content=i.comment,
                              votes=paper.votes, enabled=i.enabled)
            record_comment(session()['uname'], i.pid, i.cid)
        return render().item(paper)
Пример #34
0
 def GET(self, uid=None):
     if getattr(session(), 'passwd', None):
         return render().compose()
     raise web.seeother('/login')
Пример #35
0
 def GET(self):
     if not session().logged:
         raise web.seeother('/register')
     return render().submit()
Пример #36
0
 def GET(self):
     """Invalidate session, etc"""
     i = web.input(redir='/')
     Academic.logout()
     raise web.seeother(i.redir)
Пример #37
0
 def GET(self):
     if session().logged:
         raise web.seeother('/')
     return render().auth.register()
Пример #38
0
 def GET(self):
     if session().logged:
         raise web.seeother('/')
     return render().auth.register()
Пример #39
0
 def GET(self):
     """Invalidate session, etc"""
     i = web.input(redir='/')
     Academic.logout()
     raise web.seeother(i.redir)