Пример #1
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')
Пример #2
0
 def POST(self):
     i = web.input(username='', email='', passwd1='', passwd2='',
                   redir='')
     u = User.register(i.username, i.passwd1, i.passwd2, i.email)
     session().logged = True
     session().username = u['name']
     return u
Пример #3
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('/')        
Пример #4
0
    def GET(self):
        i = web.input(pid=None, cid=None, opt="")
        option = i.pop('opt')

        try: # getting the requested paper
            i.pid = int(i.pid)
            paper = Paper(i.pid)
            if not paper.enabled: raise
        except (TypeError, IndexError):
            raise web.notfound()

        try: # getting the specified comment
            i.cid = int(i.cid)
            comment = paper.comments[i.cid]
            if not comment['enabled']:
                raise IndexError
        except (TypeError, IndexError):
            return render().item(paper)

        if option and comment['username'] == session()['uname'] \
                and session()['logged']: # TODO: or session()['admin']
            if option == "delete":
                paper.activate_comment(i.cid, state=False)
                return render().item(paper)
            if option == "edit": return render().edit(i.pid, i.cid, comment)
        return render().comment(i.pid, i.cid, comment)
Пример #5
0
    def GET(self):
        i = web.input(pid=None, cid=None, opt="")
        option = i.pop('opt')

        try:  # getting the requested paper
            i.pid = int(i.pid)
            paper = Paper(i.pid)
            if not paper.enabled: raise
        except (TypeError, IndexError):
            raise web.notfound()

        try:  # getting the specified comment
            i.cid = int(i.cid)
            comment = paper.comments[i.cid]
            if not comment['enabled']:
                raise IndexError
        except (TypeError, IndexError):
            return render().item(paper)

        if option and comment['username'] == session()['uname'] \
                and session()['logged']: # TODO: or session()['admin']
            if option == "delete":
                paper.activate_comment(i.cid, state=False)
                return render().item(paper)
            if option == "edit": return render().edit(i.pid, i.cid, comment)
        return render().comment(i.pid, i.cid, comment)
Пример #6
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('/')
Пример #7
0
 def GET(self):
     try:
         del session().email
         del session().passwd
     except:
         pass
     session().kill()
     raise web.seeother('/')
Пример #8
0
def loadsession(u):
    """Constructs a dict of session variables for user u"""
    session().update({'logged': True,
                      'uname': u['username'],
                      'email': u['email'],
                      'created': u['created'],
                      'bio': u['bio']
                      })
Пример #9
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')
Пример #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 login(self):
     """Constructs a dict of session variables for user u"""
     session().update({'logged': True,
                       'uname': self.username,
                       'email': self.email,
                       'created': self.created,
                       'bio': self.bio
                       })
     return self.is_loggedin
Пример #12
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"
Пример #13
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)
Пример #14
0
 def login(self):
     """Constructs a dict of session variables for user u"""
     session().update({
         'logged': True,
         'uname': self.username,
         'email': self.email,
         'created': self.created,
         'bio': self.bio
     })
     return self.is_loggedin
Пример #15
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('/')
Пример #16
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")
Пример #17
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")
Пример #18
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')
Пример #19
0
 def GET(self):
     ## TODO: Enforce https
     #redirect2https(web.ctx, '/login')
     i = web.input(msg="", redir="", err="")
     if session().logged:
         return render().auth.login(resp=ALREADY_LOGGED)
     return render().auth.login()
Пример #20
0
    def GET(self):
        """Handles HTTP GET requests to the / route.

        The waltz.render() object is pre-configured to address any file within
        the project's templates/ directory as if it were an instance method.

        Calling waltz.render().filename() will automatically render
        the corresponding templates/filename.html file and inject it
        within the templates/base.html template.

        If using the templates/base.html template is undesirable, an
        alternative render called slender is provided to
        compile/render html files standalone as independent entities.

        For example:
        waltz.slender().index() will render and return
        templates/index.html without first injecting it into
        templates/base.html

        If you would like to create your own custom render object, you
        can do so by accessing the web module via waltz.web and by
        following the web.py documentation.

        See: http://webpy.org/docs/0.3/templetor
        """
        if waltz.session()['logged']:
            return waltz.render().index()
        raise waltz.web.seeother('/login')
Пример #21
0
 def GET(self):
     if session().logged:
         return render().account.index()
     else:
         return render().generic("Permission Denied", 
                                 "Can't let you do that, " \
                                     "Starfox. Please " \
                                     "<a href='/login'>Login</a> " \
                                     "first.")
Пример #22
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')
Пример #23
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)
Пример #24
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)
Пример #25
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('/')
Пример #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)
        """
        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)
Пример #27
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)
Пример #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 GET(self):
     """Research http://news.ycombinator.com/item?id=1781013 how
     hacker news voting works and emulate
     """
     msg = None
     i = web.input(pid=None)
     db = Db('db/openjournal')
     if i.pid:
         ps = db.get('papers')
         if not session().logged:
             msg = JS("Must be logged in to vote")
         else:
             try:
                 ps[int(i.pid)]['votes'] += 1
                 db.put('papers', ps)
             except IndexError:
                 return "No such items exists to vote on"
         return render().index(ps, msg=msg)
Пример #30
0
 def GET(self):
     i = web.input(op=None, ref=None, qty=1)
     if i.ref:
         pid = long(i.ref)
     if i.op == "coupon":
         session().cart.coupon = Coupon(1, "1010", percent_off=10,
                                      value_off="200.00")
     if i.op == "add" and pid:
         # XXX Replace Product with some product retrieved from listing
         # XXX Must sanitize + normalize pid, assert not None in treasury
         p = Product(pid, "Example Product", price="1.00")
         session().cart.add(p)
     if i.op == "remove" and pid:
         session().cart.remove(pid)
     if i.op == "reset":
         session().cart.empty()
     return render().cart.index()
Пример #31
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)
Пример #32
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)
Пример #33
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)
Пример #34
0
def get_karma(username):
    u = User(session()['uname'])
    if u:
        return u['karma']
    return 0
Пример #35
0
from configs.config import server

urls = ('/submit/?', 'routes.submit.Submit', '/item/?', 'routes.item.Item',
        '/upvote/?', 'routes.item.Vote', '/search/?', 'routes.search.Search',
        '/rss/?', 'routes.rss.Rss', '/admin', 'waltz.modules.Analytics',
        '/login/?', 'routes.auth.Login', '/register/?', 'routes.auth.Register',
        '/logout/?', 'routes.auth.Logout', '/users/(.*)/?',
        'routes.profiles.Profile', '/x/?', 'routes.auth.Register', '/404/?',
        'routes.responses.NotFound', '/admin/?', 'routes.admin.Analytics',
        '/?', 'routes.index.Index', '(.*)', 'routes.responses.NotFound')

env = {
    'random': random,
    'time':
    lambda x: web.datestr(str2datetime(x), now=datetime.datetime.utcnow()),
    'karma': lambda: get_karma(waltz.session()['uname']),
    'voted': lambda pid: has_voted(waltz.session()['uname'], pid),
    'join': lambda x, y: y.join(x)
}
sessions = SESSION_DEFAULTS
ssl = server['ssl'] if all(server['ssl']) else None
app = waltz.setup.dancefloor(urls,
                             globals(),
                             env=env,
                             sessions=sessions,
                             db='%s/db/waltz' % os.getcwd(),
                             ssl=ssl,
                             fcgi=server['type'],
                             debug=server['debug'],
                             autoreload=False)
Пример #36
0
 def GET(self, uid=None):
     if getattr(session(), 'passwd', None):
         return render().compose()
     raise web.seeother('/login')
Пример #37
0
def has_voted(uname, pid):
    u = User(session()['uname'])
    if not u:
        return True
    return True if int(pid) in u.votes else False
Пример #38
0
 def GET(self):
     if not session().logged:
         raise web.seeother('/register')
     return render().submit()
Пример #39
0
 def is_loggedin(self):
     return session().get('logged', False)
Пример #40
0
 def logout():
     """Invalidates and Academic's session and nullifies/defaults
     their client session data
     """
     session().update(SESSION_DEFAULTS)
     session().kill()
Пример #41
0
 def __init__(self):
     super(Mailbox, self).__init__(session().email, session().passwd, session().imap)
Пример #42
0
 def GET(self):
     if session().logged:
         raise web.seeother('/')
     return render().auth.register()
Пример #43
0
 def GET(self):
     if session().logged:
         raise web.seeother('/')
     return render().auth.register()