Пример #1
0
 def get(self, slug):
     try:
         post = db.GqlQuery('''
             SELECT * FROM Post
             WHERE slug = '%s'
             AND type = 'page'
             AND active = TRUE
             LIMIT 1
             ''' % slug)[0]
     except IndexError:
         self.error(404)
         data = {
             'pages': Post.get_pages(),
             'session': sessions.Session(),
         }
         return self.response.out.write(
             unicode(template.render('404.html', data)))
     data = {
         'page_title': post.title,
         'content': convert_emails(post.content),
         'pages': Post.get_pages(),
         'session': sessions.Session(),
     }
     return self.response.out.write(
         unicode(template.render('post/page.html', data)))
Пример #2
0
 def get(self,key):
     user = get_current_user_name()
     if not user:
         return self.redirect(create_login_url(self.request.uri))
     if not is_current_user_admin():
         sessions.Session()['flash'] = ['You must be an admin to delete pages.']
         return self.redirect('/')
        
     # delete the post
     Post.get(db.Key(key)).delete()
     
     sessions.Session()['flash'] = ['News item deleted succesfully.']
     return self.redirect('/news')
Пример #3
0
def is_current_user_admin():
    try:
        user_name = sessions.Session()['user']
    except KeyError:
        return False
    # check google account first
    if users.is_current_user_admin():
        return True
    # then check shuttlebugs account
    user = db.Query(SBUser).filter('user_name =', user_name).get()
    if not user:
        return False
    sessions.Session()['admin'] = user.is_admin
    return user.is_admin
Пример #4
0
    def get(self):
        self.sess = sessions.Session()
        if not self.sess.has_key("model_test"):
            self.sess["model_test"] = SessionTestModel(testval="test")
            self.sess["model_test"].put()
            # give the datastore time to submit the commit
            time.sleep(1)
        self.cookie_sess = sessions.Session(writer="cookie")
        if self.request.get('deleteSession') == "true":
            self.sess.delete()
            print "Location: /session\n\n"
        elif self.request.get('setflash') == "true":
            self.sess[
                'flash'] = 'You set a flash message! <a href="/session">Refresh this page</a> and this message is gone!'
            print "Location: /session\n\n"
        elif self.request.get('setTestKey') == "true":
            self.sess['DeletableKey'] = 'delete me'
            print "Location: /session\n\n"
        elif self.request.get('clearTestKey') == "true":
            self.sess.delete_item('DeletableKey')
            print "Location: /session\n\n"
        else:
            keyname = 'testKey'
            self.sess[keyname] = "test"
            self.sess[keyname + '2'] = "test2"
            self.sess[3] = "test3"
            self.cookie_sess['cookie_test'] = "testing cookie values"
            self.sess[u"unicode_key"] = u"unicode_value"

            if not 'viewCount' in self.sess:
                self.sess['viewCount'] = 1
            else:
                self.sess['viewCount'] = int(self.sess['viewCount']) + 1
            self.sess["model_test"].testval = unicode(self.sess['viewCount'])
            testkey = self.sess["model_test"].put()
            session_length = len(self.sess)
            self.memcacheStats = memcache.get_stats()
            template_values = {
                'sess': self.sess,
                'sess_str': str(self.sess),
                'cookie_sess': self.cookie_sess,
                'session_length': session_length,
                'memcacheStats': self.memcacheStats,
                'model_test': self.sess["model_test"].testval,
                'testkey': testkey,
            }
            path = os.path.join(os.path.dirname(__file__),
                                'templates/session-new.html')
            self.response.out.write(template.render(path, template_values))
Пример #5
0
 def get(self):
     db_posts = db.GqlQuery('''
         SELECT * FROM Post
         WHERE type IN ('announcement', 'news')
         AND active = TRUE
         ORDER BY date
         DESC LIMIT 5
         ''')
     posts = []
     au_tz = pytz.timezone('Australia/Sydney')
     utc_tz = pytz.utc
     for db_post in db_posts:
         post = SimplePost(
             db_post.key,
             db_post.title,
             db_post.author,
             utc_tz.localize(db_post.date).astimezone(au_tz),
             db_post.content)
         posts.append(post)
     data = {
         'upcoming'      : next_session_widget(8),
         'picofday'      : pic_of_day_widget(),
         'posts'         : posts,
         'session'       : sessions.Session(),
         'pages'         : Post.get_pages(),
     }
     return self.response.out.write(template.render('index.html',data))
Пример #6
0
 def post(self):
     session = sessions.Session()
     ### Database entry ###
     user = User()
     user.email = self.request.get('email')
     user.city = str(self.request.get('city'))
     user.area = list(self.request.get_all('area'))
     user.put()
     ### Email to YDD ###
     session["Email"] = user.email
     message = mail.EmailMessage(
         sender="YourDinnerDeals <*****@*****.**>",
         subject="A User has Subscribed")
     message.to = "Vincent Jong <*****@*****.**>",
     message.body = session["Email"]
     message.send()
     ### Email to User ###
     template_values = {
         'email': session["Email"],
     }
     message = mail.EmailMessage(
         sender="YourDinnerDeals <*****@*****.**>",
         subject="Welcome to Your Dinner Deals")
     message.to = session["Email"],
     message.body = template.render('templates/confirm-email.html',
                                    template_values)
     message.html = template.render('templates/confirm-email.html',
                                    template_values)
     message.send()
     ### Redirect ###
     self.redirect('/thanks')
Пример #7
0
    def get(self):
        db_sessions = db.Query(Session).filter(
            'active =', True).order('ordering').fetch(100)
        sessions = []
        for s in db_sessions:
            cur = {
                'name': s.name,
                'day_of_week': s.day_of_week,
                'start_time': s.start_time,
                'end_time': s.end_time,
                'location': s.location,
                'quoted_loc': quote(s.location),
                'description': s.description,
                'member_price': s.member_price,
                'casual_price': s.casual_price,
                'courts': s.courts,
                'leader': s.leader,
                'coords': s.coordinates,
            }
            if s.leader:
                leader_name = s.leader.strip().split(' ')
                cur['email'] = get_email(*leader_name[0:2])
            else:
                cur['email'] = 'holy moly'
            sessions.append(cur)

        data = {
            'pages': Post.get_pages(),
            'session': util_sess.Session(),
            'sessions': sessions,
        }
        return self.response.out.write(
            template.render('session/sessions.html', data))
Пример #8
0
    def post(self):
        url = POOTER_API_ENDPOINT + "auth/login?"
        form_fields = {
            "email": self.request.get("email"),
            "password": hashlib.md5(self.request.get("password")).hexdigest(),
        }
        form_data = urllib.urlencode(form_fields)
        result = urlfetch.fetch(
            url=url,
            payload=form_data,
            method=urlfetch.POST,
            headers={'Content-Type': 'application/x-www-form-urlencoded'})
        received_content = json.loads(result.content)

        logging.info(received_content)
        if received_content["success"] == True:
            self.sess = sessions.Session()
            self.sess["user_key"] = received_content["user_key"]
            if self.request.get("redirect_url"):
                self.redirect(self.request.get("redirect_url"))
            else:
                self.redirect('/')
        else:
            redirect_url_string = None
            if self.request.get("redirect_url"):
                redirect_url_string = "&redirect_url=" + self.request.get(
                    "redirect_url")
            self.redirect('/login?message=' + received_content["error"] +
                          redirect_url_string)
Пример #9
0
 def get(self):
     self.sess = sessions.Session()
     if not 'viewCount' in self.sess:
         self.sess['viewCount'] = 1
     else:
         self.sess['viewCount'] = int(self.sess['viewCount']) + 1
     self.response.out.write('viewcount is ' + str(self.sess['viewCount']))
Пример #10
0
 def get(self):
     self.sess = sessions.Session(writer="cookie")
     if self.request.get('deleteSession') == "true":
         self.sess.delete()
         print "Location: /cookiesession\n\n"
     elif self.request.get('setflash') == "true":
         self.sess[
             'flash'] = 'You set a flash message! <a href="/cookiesession">Refresh this page</a> and this message is gone!'
         print "Location: /cookiesession\n\n"
     else:
         keyname = 'testKey'
         self.sess[keyname] = "test"
         self.sess[keyname + '2'] = "test2"
         self.sess[3] = "test3"
         if not 'viewCount' in self.sess:
             self.sess['viewCount'] = 1
         else:
             self.sess['viewCount'] = int(self.sess['viewCount']) + 1
         self.sess[u"unicode_key"] = u"unicode_value"
         session_length = len(self.sess)
         self.memcacheStats = memcache.get_stats()
         template_values = {
             'sess': self.sess,
             'sess_str': str(self.sess),
             'session_length': session_length,
             'memcacheStats': self.memcacheStats
         }
         path = os.path.join(os.path.dirname(__file__),
                             'templates/cookie_session-new.html')
         self.response.out.write(template.render(path, template_values))
Пример #11
0
    def post(self, key):
        user = get_current_user_name()

        title = self.request.get('title')
        content = self.request.get('content')

        # get the existing post
        post = Post.get(key)

        errors = []
        if not is_current_user_admin():
            errors.append('Only admins can edit')
        if not user:
            errors.append('You need to be logged in to edit')
        if not title or not content:
            errors.append('Please fill out all fields')
        if errors:
            session = sessions.Session()
            session['flash'] = errors
            data = {
                'title': title,
                'content': content,
                'session': session,
                'type': post.type,
                'key': key,
                'pages': Post.get_pages(),
            }
            return self.response.out.write(
                unicode(template.render('post/edit.html', data)))

        post.title = title
        post.content = content
        post.put()

        return self.redirect('/news')
Пример #12
0
def get_current_user_name():
    sess = sessions.Session()
    if sess.has_key('user'):
        return sess['user']
    #elif users.is_current_user_admin():
    #    return users.get_current_user().nickname()
    return ''
Пример #13
0
 def _compose(self, flash=[]):
     sess = sessions.Session()
     sess['flash'] = flash
     galleries = [{
         'id': gallery.key().id(),
         'slug': gallery.slug,
         'date': gallery.date,
         'title': gallery.title,
         'description': gallery.description
     }
                  for gallery in db.Query(Gallery).filter(
                      'disabled =', False).order('date').fetch(100)]
     disabled = [{
         'id': gallery.key().id(),
         'slug': gallery.slug,
         'date': gallery.date,
         'title': gallery.title,
         'description': gallery.description
     }
                 for gallery in db.Query(Gallery).filter(
                     'disabled =', True).order('date').fetch(100)]
     data = {
         'pages': Post.get_pages(),
         'session': sess,
         'galleries': galleries,
         'disabled': disabled
     }
     return self.response.out.write(
         template.render('photos/index.html', data))
Пример #14
0
 def new_funct(self, *args, **kw):
     user = get_current_user_name()
     if not user:
         sessions.Session()['flash'] = [
             'You must login to use this feature.'
         ]
         return self.redirect(create_login_url(self.request.uri))
     return funct(self, *args, **kw)
Пример #15
0
 def get(self):
     sess = sessions.Session()
     if not sess.has_key('user') or not sess['user']:
         return self.redirect(create_login_url(self.request.uri))            
     data = {
         'session' : sess,
         'pages'   : Post.get_pages(),
     }
     return self.response.out.write(template.render('post/post.html',data))
Пример #16
0
 def get(self):
     user = users.get_current_user()
     session = sessions.Session()
     if not 'user' in session:
         session['flash'] = ['Not logged in, cant log out.']
         return self.redirect('/user/login')
     data = {'pages': post.Post.get_pages(), 'session': session}
     return self.response.out.write(
         unicode(template.render('sbuser/logout.html', data)))
Пример #17
0
 def _compose(self, flash=[]):
     sess = sessions.Session()
     sess['flash'] = flash
     galleries = db.Query(Gallery).order('date').fetch(100)
     data = {
         'pages': Post.get_pages(),
         'session': sess,
         'galleries': galleries,
     }
     return self.response.out.write(
         template.render('photos/index.html', data))
Пример #18
0
 def get(self,slug):
     user = get_current_user_name()
     if not user:
         return self.redirect(create_login_url(self.request.uri))
     if not is_current_user_admin():
         sessions.Session()['flash'] = ['You must be an admin to delete pages.']
         return self.redirect('/')
        
     # get the existing post
     post = db.GqlQuery('''
         SELECT * FROM Post
         WHERE slug = '%s'
         AND type = 'page'
         LIMIT 1
         ''' % slug)[0]
         
     post.active = False
     post.put()
     sessions.Session()['flash'] = ['Page deleted succesfully.']
     return self.redirect('/')
Пример #19
0
 def get(self):
     user = users.get_current_user()
     target = self.request.get('target')
     session = sessions.Session()
     data = {
         'pages': post.Post.get_pages(),
         'session': session,
         'target': target
     }
     return self.response.out.write(
         unicode(template.render('sbuser/login.html', data)))
Пример #20
0
 def _compose(self,gallery_slug,flash=[]):
     gallery = db.Query(Gallery).filter('slug =',gallery_slug).get()
     sess = sessions.Session()
     sess['flash'] = flash        
     data = {
         'session'   : sess,
         'pages'     : Post.get_pages(),
         'title'     : gallery.title,
         'photos'    : [ {'id':photo.key().id(), 'caption':photo.title, 'ext':photo.extension, 'fp':photo.frontpage} for photo in gallery.photos ],
     }
     return self.response.out.write(unicode(template.render('photos/upload.html',data)))        
Пример #21
0
    def post(self):
        email_address = self.request.get('email_address')
        user_name = self.request.get('user_name')
        password = self.request.get('password')
        password_again = self.request.get('password_again')
        sess = sessions.Session()
        existing = db.Query(SBUser).filter('email_address =',
                                           email_address).get()
        error = False
        flash = []
        if not existing:
            flash.append('This email address is not on the member list')
            error = True
        else:
            if existing.is_registered:
                flash.append('This user has already registered')
                error = True
        if password != password_again:
            flash.append('Your passwords were entered differently')
            error = True
        if error:
            sess['flash'] = flash
            return self.redirect(self.request.uri)
        sess['user'] = user_name
        sess['flash'] = [
            'Registration Successful.',
            'You will receive an email with a link you can use to confirm registration.',
            'Logged in.'
        ]
        existing.password = md5(password).hexdigest()
        existing.user_name = user_name
        #existing.is_registered = True
        existing.rego_code = gen_rego_code()
        existing.put()
        mail.send_mail(
            sender='Shuttlebugs Website<*****@*****.**>',
            to='%s %s <%s>' %
            (existing.first_name, existing.last_name, email_address),
            subject='Confirm Shuttlebugs Website Registration',
            body='''
Hi %s,

Your email account has been activated on the Shuttlebugs Website.

To confirm that everything is working correctly and complete the registration, please visit the following link.

http://sbugsbc.appspot.com/user/confirm?code=%s&email=%s

Regards,
Shuttlebugs
            ''' % (existing.first_name, existing.rego_code, email_address))
        return self.redirect('/')
Пример #22
0
 def get(self,gallery):
     gallery = db.Query(Gallery).filter("slug =",gallery).get()
     data = {
         'pages'     : Post.get_pages(),
         'session'   : sessions.Session(),
     }
     if not gallery:
         self.error(404)
         return self.response.out.write(unicode(template.render('404.html',data)))
     data['gallery'] = gallery
     data['photos'] = [ {'id':photo.key().id(), 'caption':photo.title} for photo in gallery.photos ]
     self.response.headers['Content-Type'] = "application/x-shockwave-flash"
     return self.response.out.write(unicode(open('static/main.css','r').read()))
Пример #23
0
 def _compose(self,gallery_slug,flash=[]):
     sess = sessions.Session()
     sess['flash'] = flash
     gallery = db.Query(Gallery).filter('slug =',gallery_slug).get()
     data = {
         'pages'     : Post.get_pages(),
         'session'   : sess,
         'gallery'   : gallery,
     }
     if not gallery:
         self.error(404)
         return self.response.out.write(unicode(template.render('404.html',data)))
     return self.response.out.write(unicode(template.render('photos/gallery.html',data)))
Пример #24
0
 def get(self,gallery):
     gallery = db.Query(Gallery).filter("slug =",gallery).get()
     data = {
         'pages'     : Post.get_pages(),
         'session'   : sessions.Session(),
     }
     if not gallery:
         self.error(404)
         return self.response.out.write(unicode(template.render('404.html',data)))
     data['gallery'] = gallery
     data['photos'] = [ {'id':photo.key().id(), 'caption':photo.title, 'ext':photo.extension} for photo in gallery.photos ]
     self.response.headers['Content-Type'] = "text/xml"
     return self.response.out.write(unicode(template.render('photos/images.xml',data)))
Пример #25
0
 def get(self):
     data = {
         'pages':
         post.Post.get_pages(),
         'session':
         sessions.Session(),
         'users':
         list(
             db.Query(SBUser).order('first_name').order('last_name').fetch(
                 1000))
     }
     return self.response.out.write(
         unicode(template.render('sbuser/manage.html', data)))
Пример #26
0
def create_login_details():
    sess = sessions.Session()
    user = None
    google_user = users.get_current_user()
    if sess.has_key('user'):
        user = db.Query(SBUser).filter('user_name =', sess['user']).get()
    elif google_user:
        user = db.Query(SBUser).filter('google_user ='******'name': user.user_name, 'admin': user.is_admin}
        return login_details

    return None
Пример #27
0
    def post(self):        
        title = self.request.get('title')
        type = self.request.get('type')
        content = self.request.get('content')
        
        
        # if it's a page, check that the title/slug has not already been used
        existing = False
        if type == 'page':
            existing = Post.all().filter('type =', 'page').filter('slug =', slugify(title)).fetch(1)

        errors = []
        if not is_current_user_admin():
            errors.append('Only admins can post')
        if not get_current_user_name():
            errors.append('You need to be logged in to post')
        if not title or not type or not content:
            errors.append('Please fill out all fields')
        if existing:
            errors.append('A page with this title already exists')
        if type not in ['news','announcement','page','pdf']:
            errors.append('Invalid page type')            
        if errors:
            session = sessions.Session()
            session['flash'] = errors
            data = {
                'title'     : title,
                'type'      : type,
                'content'   : content,
                'session'   : session,
                'pages'     : Post.get_pages(),
                }
            return self.response.out.write(template.render('post/post.html',data))

        fixed_type = type
        if fixed_type == 'pdf':
            fixed_type = 'page'

        new_post = Post(
            title = title,
            type = fixed_type,
            content = content
        )
        if fixed_type == 'page':
            new_post.hidden = True
        new_post.put()
        
        if fixed_type == 'page':
            return self.redirect('/%s.html' % new_post.slug)
        else:
            return self.redirect('/')
Пример #28
0
    def current_user(self):
        if not hasattr(self, '_current_user'):
            sess = sessions.Session()
            if 'id' in sess:
                id = sess['id']

                # Try to find user info in memcache
                cache = mc.get(id, namespace='users')
                if cache:
                    logging.info('Found user %s in cache' % (id))
                    u = User(id=id, email=cache['email'])
                else:
                    logging.info('Looking for user %s in store' % (id))
                    u = User.get_by_key_name(id)

                    if u:
                        # Memcache already existing user
                        logging.info('Setting user %s in cache' % (id))
                        mc.set(id,
                               dict(id=u.id, email=u.email),
                               namespace='users')
                    else:
                        # We have a new user
                        logging.info('Creating new user %s' % (id))

                        # Make sure it's the correct class year
                        d = DNDRemoteLookup()
                        dndnames = d.lookup([id], CLASS_YEAR)
                        if id not in dndnames or len(dndnames[id]) == 0:
                            logging.info('Reject new user %s' % (id))
                            self.response.out.write(
                                "Sorry, only the senior class can enter last chances.  If you think there's been a mistake, please contact people running this."
                            )
                            self._current_user = None
                            sess.delete()
                            return None

                        # Add new user
                        email = id.replace(' ', '.').replace(
                            '..', '.') + '@dartmouth.edu'
                        u = User(key_name=id, id=id, email=email)
                        u.save()

                        # memcache the user
                        mc.set(id, dict(id=id, email=email), namespace='users')

                self._current_user = u
            else:
                self._current_user = None
        return self._current_user
Пример #29
0
    def get(self):
        # Login if necessary
        c = CASClient(CAS_URL, SERVICE_URL)
        id = c.Authenticate(self.request.get('ticket', None))

        if id:
            sess = sessions.Session()
            try:
                sess['id'] = id[:id.find('@')]
                self.redirect('/entry')
                return
            except:
                pass
        self.response.out.write('Login failed')
Пример #30
0
 def _compose(self, flash=[]):
     sess = sessions.Session()
     sess['flash'] = flash
     data = {
         'session':
         sess,
         'pages':
         Post.get_pages(),
         'files':
         File.all().order('path').order('filename').order(
             'extension').fetch(1000)
     }
     return self.response.out.write(
         template.render('files/upload.html', data))