Exemple #1
0
def vote(request, poll_pk):
    if request.is_ajax():
        try:
            poll = Poll.objects.get(pk=poll_pk)
        except:
            return HttpResponse('Wrong parameters', status=400)

        item_pk = request.GET.get("item", False)
        if not item_pk:
            return HttpResponse('Wrong parameters', status=400)            
        
        try:
            item = Item.objects.get(pk=item_pk)        
        except:
            return HttpResponse('Wrong parameters', status=400)
                    
        if request.user.is_authenticated():
            user = request.user
        else:
            user = None
        
        vote = Vote.objects.create(
            poll=poll,
            ip=request.META['REMOTE_ADDR'],
            user=user,
            item=item,
        )
        
        response = HttpResponse(status=200)
        set_cookie(response, poll.get_cookie_name(), poll_pk)
        
        return response
    return HttpResponse(status=400)
def vote(request, poll_pk):
    if request.is_ajax():
        try:
            poll = Poll.objects.get(pk=poll_pk)
        except:
            return HttpResponse('Wrong parameters', status=400)

        item_pk = request.GET.get("item", False)
        if not item_pk:
            return HttpResponse('Wrong parameters', status=400)

        try:
            item = Item.objects.get(pk=item_pk)
        except:
            return HttpResponse('Wrong parameters', status=400)

        if request.user.is_authenticated():
            user = request.user
        else:
            user = None

        vote = Vote.objects.create(
            poll=poll,
            ip=request.META['REMOTE_ADDR'],
            user=user,
            item=item,
        )

        response = HttpResponse(status=200)
        set_cookie(response, poll.get_cookie_name(), poll_pk)

        return response
    return HttpResponse(status=400)
Exemple #3
0
def bury(itemcode):
    try:

        uid = get_cookie(UID)
        if uid is None:
            return 'noLogin'
        else:
            item = db.query_one('select t.id,t.itemcode,t.burytimes \
                  from gkgp_item t  where t.itemcode=%s',itemcode)
            if item is not None:
                digOrBuryHistory = get_cookie('DigOrBury_'+itemcode)
                if digOrBuryHistory is not None and len(digOrBuryHistory)>0:
                    if item[2] is not None:
                        return beautifulDisPlay(str(item[2]))
                    else:
                        return '0'
                else:
                    if item[2] is not None:
                        temp = item[2]+1
                        db.update('update gkgp_item set burytimes=%s where id=%s',(temp,item[0]))
                        set_cookie('DigOrBury_'+itemcode,itemcode)
                        return beautifulDisPlay(str(temp))
                    else:
                        return '0'
            else:
                return '0'
    except Exception:
        traceback.print_exc()
        return 'bury error'
Exemple #4
0
def poll_ajax_vote(request, poll_pk):
    if request.is_ajax():
        try:
            poll = Poll.objects.get(pk=poll_pk)
            if poll.queue:
                if not authpass(request.user, poll.queue):
                    return HttpResponse('Non-authenticated users can\'t vote',
                                        status=400)

            chosen_items = simplejson.loads(request.GET['chosen_items'])
        except:
            return HttpResponse('Wrong parameters', status=400)

        if request.user.is_authenticated():
            user = request.user
        else:
            user = None
        vote = Vote.objects.create(poll=poll,
                                   ip=request.META['REMOTE_ADDR'],
                                   user=user)
        try:
            for item_pk, value in chosen_items.items():
                item = Item.objects.get(pk=item_pk)

                if item.userbox:
                    Choice.objects.create(vote=vote, item=item,
                                          uservalue=value)
                else:
                    Choice.objects.create(vote=vote, item=item)
        except:
            return HttpResponse('Data recognition failed', status=400)
        response = HttpResponse(status=200)
        set_cookie(response, poll.get_cookie_name(), poll_pk)
        return response
    return HttpResponse(status=400)
Exemple #5
0
 def post(self):
     user = users.get_current_user()
     try:
         start_time = datetime.strptime('%s %s:%s %s' % (
             self.request.get('date'),
             self.request.get('start_time_hour'),
             self.request.get('start_time_minute'),
             self.request.get('start_time_ampm')), '%m/%d/%Y %I:%M %p')
         end_time = datetime.strptime('%s %s:%s %s' % (
             self.request.get('date'),
             self.request.get('end_time_hour'),
             self.request.get('end_time_minute'),
             self.request.get('end_time_ampm')), '%m/%d/%Y %I:%M %p')
         conflicts = Event.check_conflict(start_time,end_time,self.request.get_all('rooms'))
         if conflicts:
           raise ValueError('Room conflict detected')
         if not self.request.get('estimated_size').isdigit():
           raise ValueError('Estimated number of people must be a number')
         if not int(self.request.get('estimated_size')) > 0:
           raise ValueError('Estimated number of people must be greater then zero')
         if (end_time-start_time).days < 0:
             raise ValueError('End time must be after start time')
         if (  self.request.get( 'contact_phone' ) and not is_phone_valid( self.request.get( 'contact_phone' ) ) ):
             raise ValueError( 'Phone number does not appear to be valid' )
         else:
             event = Event(
                 name = cgi.escape(self.request.get('name')),
                 start_time = start_time,
                 end_time = end_time,
                 type = cgi.escape(self.request.get('type')),
                 estimated_size = cgi.escape(self.request.get('estimated_size')),
                 contact_name = cgi.escape(self.request.get('contact_name')),
                 contact_phone = cgi.escape(self.request.get('contact_phone')),
                 details = cgi.escape(self.request.get('details')),
                 url = cgi.escape(self.request.get('url')),
                 fee = cgi.escape(self.request.get('fee')),
                 notes = cgi.escape(self.request.get('notes')),
                 rooms = self.request.get_all('rooms'),
                 expired = local_today() + timedelta(days=PENDING_LIFETIME), # Set expected expiration date
                 )
             event.put()
             log = HDLog(event=event,description="Created new event")
             log.put()
             notify_owner_confirmation(event)
             notify_new_event(event)
             set_cookie(self.response.headers, 'formvalues', None)
             self.redirect('/event/%s-%s' % (event.key().id(), slugify(event.name)))
     except Exception, e:
         message = str(e)
         if 'match format' in message:
             message = 'Date is required.'
         if message.startswith('Property'):
             message = message[9:].replace('_', ' ').capitalize()
         # This is NOT a reliable way to handle erorrs
         #set_cookie(self.response.headers, 'formerror', message)
         #set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
         #self.redirect('/new')
         error = message
         self.response.out.write(template.render('templates/error.html', locals()))
Exemple #6
0
    async def get(self, request: Request):
        token = await TwitchOauthClient.fetch_token(request=request)
        user = await TwitchOauthClient.user_info(token=token)

        b_token = json.dumps(token)
        b_user = json.dumps(user.json()['data'][0])

        response = RedirectResponse(request.url_for('home'))
        utils.set_cookie(response, "token", b_token)
        utils.set_cookie(response, "user", b_user)
        return response
Exemple #7
0
def delplaylist():
    try:
        itemcode = request.query.get('itemcode')
        playlist = get_cookie('playlist')
        l=json.loads(playlist)
        del l[l.index(itemcode)]
        set_cookie('playlist',json.dumps(l))
        return 'ok'
    except Exception:
        traceback.print_exc()
        return 'error'
Exemple #8
0
def login_logout(request):
    token = utils.get_request_value(request, 'token')
    if token:
        securityservice.SecurityService.logoff_user_token(token)

    c = template.RequestContext(request, locals())
    t = loader.get_template('login/logout.html')

    response = http.HttpResponse(t.render(c))
    utils.set_cookie(response, 'token', '')
    return response
def login_logout(request):
  token       = utils.get_request_value(request, 'token')
  if token:
      securityservice.SecurityService.logoff_user_token(token)
      
  c = template.RequestContext(request, locals())
  t = loader.get_template('login/logout.html')

  response = http.HttpResponse(t.render(c))
  utils.set_cookie(response, 'token', '')
  return response
Exemple #10
0
    async def dispatch(self, request: Request,
                       call_next: RequestResponseEndpoint) -> Response:
        response = await call_next(request)

        if 'X-Update-Cookie' in request.session:
            update_cookies = request.session.pop('X-Update-Cookie')
            if update_cookies:
                utils.set_cookie(response, "token",
                                 json.dumps(update_cookies['token']))
                utils.set_cookie(response, "user",
                                 json.dumps(update_cookies['user']))
        return response
Exemple #11
0
 def post(self, id):
     user = users.get_current_user()
     event = Event.get_by_id(int(id))
     try:
         if self.request.get('rating'):
             feedback = Feedback(
                 event = event,
                 rating = int(self.request.get('rating')),
                 comment = cgi.escape(self.request.get('comment')))
             feedback.put()
             self.redirect('/event/%s-%s' % (event.key().id(), slugify(event.name)))
         else:
             raise ValueError('Please select a rating')
     except Exception:
         set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
         self.redirect('/feedback/new/' + id)
Exemple #12
0
 def post(self, id):
     user = users.get_current_user()
     event = Event.get_by_id(int(id))
     try:
         if self.request.get("rating"):
             feedback = Feedback(
                 event=event, rating=int(self.request.get("rating")), comment=cgi.escape(self.request.get("comment"))
             )
             feedback.put()
             log = HDLog(event=event, description="Posted feedback")
             log.put()
             self.redirect("/event/%s-%s" % (event.key().id(), slugify(event.name)))
         else:
             raise ValueError("Please select a rating")
     except Exception:
         set_cookie(self.response.headers, "formvalues", dict(self.request.POST))
         self.redirect("/feedback/new/" + id)
Exemple #13
0
 def post(self, id):
     user = users.get_current_user()
     event = Event.get_by_id(int(id))
     try:
         if self.request.get('rating'):
             feedback = Feedback(
                 event = event,
                 rating = int(self.request.get('rating')),
                 comment = cgi.escape(self.request.get('comment')))
             feedback.put()
             log = HDLog(event=event,description="Posted feedback")
             log.put()
             self.redirect('/event/%s-%s' % (event.key().id(), slugify(event.name)))
         else:
             raise ValueError('Please select a rating')
     except Exception:
         set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
         self.redirect('/feedback/new/' + id)
Exemple #14
0
def play(itemcode):
    item = db.query_one('select t1.id,t1.itemcode,t.username,t.id,t1.title,t1.addtime,t1.description,t1.playtimes,t1.digtimes,t1.burytimes \
      ,t1.pics from gkgp_user t,gkgp_item t1 ,gkgp_user_item t2 where t1.id = t2.videoid and t2.userid = t.id and \
       itemcode=%s',(itemcode))
    # put play history into cookie
    # key : playlist
    # value : {'itemcode1','itemcode3','itemcode4'}
    playlist = get_cookie('playlist')
    if playlist:
        l=json.loads(playlist)
        if itemcode not in l:
            if(len(l)>=10):
                del l[0]
                l.append(itemcode)
            else:
                l.append(itemcode)
            set_cookie('playlist',json.dumps(l))
    else:
        l=[]
        l.append(itemcode)
        set_cookie('playlist',json.dumps(l))
    # end

    if item is not None:
        playtime = 0
        if item[7] is not None and item[7]>=0:
            playtime = item[7]+1
        else:
             playtime =1
        db.update('update gkgp_item set playtimes=%s where id=%s',(playtime,item[0]))
    #首发
    firstvideo = main.changeVideo(main.findItem(8,5))
    # get user  other videos
    othervideos = db.query_list('select t.title,t.pics,t.itemcode from gkgp_item t, \
        gkgp_user_item t1 where t.id=t1.videoid and t1.userid=%s order by t.addtime desc limit 0,4 ',(item[3]))

    item = list(item)
    item[7] = beautifulDisPlay(str(item[7]))
    item[8] = beautifulDisPlay(str(item[8]))
    item[9] = beautifulDisPlay(str(item[9]))

    return dict(domain=SITE_DOMAIN,picdomain=PIC_DOMAIN,itemcode=itemcode,item=item,firstvideo=firstvideo,othervideos=othervideos)
Exemple #15
0
    def render_articles(self,
                        page_info,
                        request,
                        recent,
                        template_name='articles.html',
                        additional_template_variables = None,
                        single_article = False):
        if not isinstance(page_info, PageInfoBase):
            raise Exception("Use 'page_info' instead of 'articles'; actual = %s" % type(page_info.articles))

        articles = page_info.articles

        url_prefix = 'http://' + request.environ['SERVER_NAME']
        port = request.environ['SERVER_PORT']
        if port:
            url_prefix += ':%s' % port

        self.augment_articles(articles, url_prefix, single_article=single_article)

        user_info = UserInfo(request)

        template_variables = {
            'defs'         : defs,
            'current_path' : cgi.escape(request.path),
            'articles'     : articles,
            'user_info'    : user_info,
            'comment_author'  : utils.get_unicode_cookie(self.request, 'comment_author', ''),
            'prev_page_url'   : page_info.prev_page_url,
            'next_page_url'   : page_info.next_page_url,
            'current_page_1'  : page_info.current_page,
            'pages_total'     : page_info.pages_total,
            'tag_cloud'       : caching.TagCloud.get(),
        }

        # used for JavaScript i18n
        utils.set_cookie(self.response, 'user_lang', self.extract_preferred_content_language())

        if additional_template_variables:
            template_variables.update(additional_template_variables)

        return self.render_template(template_name, template_variables)
Exemple #16
0
def poll_ajax_vote(request, poll_pk):
    if request.is_ajax():
        try:
            poll = Poll.objects.get(pk=poll_pk)
            if poll.queue:
                if not authpass(request.user, poll.queue):
                    return HttpResponse('Non-authenticated users can\'t vote',
                                        status=400)

            chosen_items = simplejson.loads(request.POST['chosen_items'])
        except:
            return HttpResponse('Wrong parameters', status=400)

        if request.user.is_authenticated():
            user = request.user
        else:
            user = None

        vote = Vote.objects.create(poll=poll,
                                   ip=request.META['REMOTE_ADDR'],
                                   user=user)
        try:
            for item_pk, value in chosen_items.items():
                item = Item.objects.get(pk=item_pk)

                if item.userbox:
                    Choice.objects.create(vote=vote,
                                          item=item,
                                          uservalue=value)
                else:
                    Choice.objects.create(vote=vote, item=item)
        except:
            return HttpResponse('Data recognition failed', status=400)

        response = HttpResponse(status=200)
        set_cookie(response, poll.get_cookie_name(), poll_pk)

        return response

    return HttpResponse(status=400)
Exemple #17
0
 def post(self):
     user = users.get_current_user()
     try:
         start_time = datetime.strptime("%s %s:%s %s" % (
             self.request.get('date'),
             self.request.get('start_time_hour'),
             self.request.get('start_time_minute'),
             self.request.get('start_time_ampm')), "%m/%d/%Y %I:%M %p")
         end_time = datetime.strptime("%s %s:%s %s" % (
             self.request.get('date'),
             self.request.get('end_time_hour'),
             self.request.get('end_time_minute'),
             self.request.get('end_time_ampm')), "%m/%d/%Y %I:%M %p")
         if (end_time-start_time).days < 0:
             raise ValueError("End time must be after start time")
         else:
             event = Event(
                 name = self.request.get('name'),
                 start_time = start_time,
                 end_time = end_time,
                 type = self.request.get('type'),
                 estimated_size = self.request.get('estimated_size'),
                 contact_name = self.request.get('contact_name'),
                 contact_phone = self.request.get('contact_phone'),
                 details = self.request.get('details'),
                 url = self.request.get('url'),
                 fee = self.request.get('fee'),
                 notes = self.request.get('notes'),
                 rooms = self.request.get_all('rooms'),
                 expired = datetime.today() + timedelta(days=PENDING_LIFETIME), # Set expected expiration date
                 )
             event.put()
             notify_owner_confirmation(event)
             if not event.is_staffed():
                 notify_staff_needed(event)
             notify_new_event(event)
             set_cookie(self.response.headers, 'formvalues', None)
             self.redirect('/event/%s-%s' % (event.key().id(), slugify(event.name)))
     except Exception, e:
         message = str(e)
         if 'match format' in message:
             message = "Date is required."
         if message.startswith('Property'):
             message = message[9:].replace('_', ' ').capitalize()
         set_cookie(self.response.headers, 'formerror', message)
         set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
         self.redirect('/new')
Exemple #18
0
    def post(self):
        user = users.get_current_user()
        try:
            start_time = datetime.strptime('%s %s:%s %s' % (
                self.request.get('start_date'),
                self.request.get('start_time_hour'),
                self.request.get('start_time_minute'),
                self.request.get('start_time_ampm')), '%m/%d/%Y %I:%M %p')
            end_time = datetime.strptime('%s %s:%s %s' % (
                self.request.get('end_date'),
                self.request.get('end_time_hour'),
                self.request.get('end_time_minute'),
                self.request.get('end_time_ampm')), '%m/%d/%Y %I:%M %p')
            conflicts = Event.check_conflict(start_time,end_time,self.request.get_all('rooms'))
            if conflicts:
                if "Deck" in self.request.get_all('rooms') or "Savanna" in self.request.get_all('rooms'):
                    raise ValueError('Room conflict detected <small>(Note: Deck &amp; Savanna share the same area, two events cannot take place at the same time in these rooms.)</small>')
                else:
                    raise ValueError('Room conflict detected')
            if not self.request.get('estimated_size').isdigit():
              raise ValueError('Estimated number of people must be a number')
            if not int(self.request.get('estimated_size')) > 0:
              raise ValueError('Estimated number of people must be greater then zero')
            if (end_time-start_time).days < 0:
                raise ValueError('End time must be after start time')
            if (  self.request.get( 'contact_phone' ) and not is_phone_valid( self.request.get( 'contact_phone' ) ) ):
                raise ValueError( 'Phone number does not appear to be valid' )
            else:
                event = Event(
                    name = cgi.escape(self.request.get('name')),
                    start_time = start_time,
                    end_time = end_time,
                    type = cgi.escape(self.request.get('type')),
                    estimated_size = cgi.escape(self.request.get('estimated_size')),
                    contact_name = cgi.escape(self.request.get('contact_name')),
                    contact_phone = cgi.escape(self.request.get('contact_phone')),
                    details = cgi.escape(self.request.get('details')),
                    url = cgi.escape(self.request.get('url')),
                    fee = cgi.escape(self.request.get('fee')),
                    notes = cgi.escape(self.request.get('notes')),
                    rooms = self.request.get_all('rooms'),
                    expired = local_today() + timedelta(days=PENDING_LIFETIME), # Set expected expiration date
                    )
                event.put()
                log = HDLog(event=event,description="Created new event")
                log.put()
                notify_owner_confirmation(event)
                notify_new_event(event)
                set_cookie(self.response.headers, 'formvalues', None)
                #self.redirect('/event/%s-%s' % (event.key().id(), slugify(event.name)))
                self.redirect('/confirm/%s-%s' % (event.key().id(), slugify(event.name)))

        except Exception, e:
            message = str(e)
            if 'match format' in message:
                message = 'Date is required.'
            if message.startswith('Property'):
                message = message[9:].replace('_', ' ').capitalize()
            # This is NOT a reliable way to handle erorrs
            #set_cookie(self.response.headers, 'formerror', message)
            #set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
            #self.redirect('/new')
            error = message
            self.response.out.write(template.render('templates/error.html', locals()))
Exemple #19
0
    def post(self):
        user = users.get_current_user()
        try:
            start_time = datetime.strptime(
                '%s %s:%s %s' % (self.request.get('start_date'),
                                 self.request.get('start_time_hour'),
                                 self.request.get('start_time_minute'),
                                 self.request.get('start_time_ampm')),
                '%m/%d/%Y %I:%M %p')
            end_time = datetime.strptime(
                '%s %s:%s %s' % (self.request.get('end_date'),
                                 self.request.get('end_time_hour'),
                                 self.request.get('end_time_minute'),
                                 self.request.get('end_time_ampm')),
                '%m/%d/%Y %I:%M %p')
            conflicts = Event.check_conflict(start_time, end_time,
                                             self.request.get_all('rooms'))
            if conflicts:
                if "Deck" in self.request.get_all(
                        'rooms') or "Savanna" in self.request.get_all('rooms'):
                    raise ValueError(
                        'Room conflict detected <small>(Note: Deck &amp; Savanna share the same area, two events cannot take place at the same time in these rooms.)</small>'
                    )
                else:
                    raise ValueError('Room conflict detected')
            if not self.request.get('details'):
                raise ValueError('You must provide a description of the event')
            if not self.request.get('estimated_size').isdigit():
                raise ValueError('Estimated number of people must be a number')
            if not int(self.request.get('estimated_size')) > 0:
                raise ValueError(
                    'Estimated number of people must be greater then zero')
            if (end_time - start_time).days < 0:
                raise ValueError('End time must be after start time')
            if (self.request.get('contact_phone')
                    and not is_phone_valid(self.request.get('contact_phone'))):
                raise ValueError('Phone number does not appear to be valid')
            else:
                event = Event(
                    name=cgi.escape(self.request.get('name')),
                    start_time=start_time,
                    end_time=end_time,
                    type=cgi.escape(self.request.get('type')),
                    estimated_size=cgi.escape(
                        self.request.get('estimated_size')),
                    contact_name=cgi.escape(self.request.get('contact_name')),
                    contact_phone=cgi.escape(
                        self.request.get('contact_phone')),
                    details=cgi.escape(self.request.get('details')),
                    url=cgi.escape(self.request.get('url')),
                    fee=cgi.escape(self.request.get('fee')),
                    notes=cgi.escape(self.request.get('notes')),
                    rooms=self.request.get_all('rooms'),
                    expired=local_today() + timedelta(
                        days=PENDING_LIFETIME),  # Set expected expiration date
                )
                event.put()
                log = HDLog(event=event, description="Created new event")
                log.put()
                notify_owner_confirmation(event)
                notify_new_event(event)
                set_cookie(self.response.headers, 'formvalues', None)

                rules = memcache.get("rules")
                if (rules is None):
                    try:
                        rules = urlfetch.fetch(
                            "http://wiki.hackerdojo.com/api_v2/op/GetPage/page/Event+Policies/_type/html",
                            "GET").content
                        memcache.add("rules", rules, 86400)
                    except Exception, e:
                        rules = "Error fetching rules.  Please report this error to [email protected]."
                self.response.out.write(
                    template.render('templates/confirmation.html', locals()))

        except Exception, e:
            message = str(e)
            if 'match format' in message:
                message = 'Date is required.'
            if message.startswith('Property'):
                message = message[9:].replace('_', ' ').capitalize()
            # This is NOT a reliable way to handle erorrs
            #set_cookie(self.response.headers, 'formerror', message)
            #set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
            #self.redirect('/new')
            error = message
            # this is not the permanent answer but just for now
            cdn = 'http://cdn.hackerdojo.com'
            self.response.out.write(
                template.render('templates/error.html', locals()))
Exemple #20
0
    def post(self):
        user = users.get_current_user()
        try:
            start_time = datetime.strptime('%s %s:%s %s' % (
                self.request.get('start_date'),
                self.request.get('start_time_hour'),
                self.request.get('start_time_minute'),
                self.request.get('start_time_ampm')), '%m/%d/%Y %I:%M %p')
            end_time = datetime.strptime('%s %s:%s %s' % (
                self.request.get('end_date'),
                self.request.get('end_time_hour'),
                self.request.get('end_time_minute'),
                self.request.get('end_time_ampm')), '%m/%d/%Y %I:%M %p')
            conflicts = Event.check_conflict(start_time,end_time,self.request.get_all('rooms'))
            if conflicts:
                if "Deck" in self.request.get_all('rooms') or "Savanna" in self.request.get_all('rooms'):
                    raise ValueError('Room conflict detected <small>(Note: Deck &amp; Savanna share the same area, two events cannot take place at the same time in these rooms.)</small>')
                else:
                    raise ValueError('Room conflict detected')
            if not self.request.get('estimated_size').isdigit():
              raise ValueError('Estimated number of people must be a number')
            if not int(self.request.get('estimated_size')) > 0:
              raise ValueError('Estimated number of people must be greater then zero')
            if int(self.request.get('estimated_size')) > 47:
                raise ValueError('Hacker Dojo temporarily is under order of the City of Mountain View to not allow assemblies larger than 49 persons.  Sorry, your event exceeds this size.  <p>NOTE: Lying about the event size to get around this restriction will result in membership ban plus possible legal action.  We will be fined $1500 for each violation, which will be passed on to the event host.')              
            if (end_time-start_time).days < 0:
                raise ValueError('End time must be after start time')
            if (  self.request.get( 'contact_phone' ) and not is_phone_valid( self.request.get( 'contact_phone' ) ) ):
                raise ValueError( 'Phone number does not appear to be valid' )
            else:
                event = Event(
                    name = cgi.escape(self.request.get('name')),
                    start_time = start_time,
                    end_time = end_time,
                    type = cgi.escape(self.request.get('type')),
                    estimated_size = cgi.escape(self.request.get('estimated_size')),
                    contact_name = cgi.escape(self.request.get('contact_name')),
                    contact_phone = cgi.escape(self.request.get('contact_phone')),
                    details = cgi.escape(self.request.get('details')),
                    url = cgi.escape(self.request.get('url')),
                    fee = cgi.escape(self.request.get('fee')),
                    notes = cgi.escape(self.request.get('notes')),
                    rooms = self.request.get_all('rooms'),
                    expired = local_today() + timedelta(days=PENDING_LIFETIME), # Set expected expiration date
                    )
                event.put()
                log = HDLog(event=event,description="Created new event")
                log.put()
                notify_owner_confirmation(event)
                notify_new_event(event)
                set_cookie(self.response.headers, 'formvalues', None)
                #self.redirect('/event/%s-%s' % (event.key().id(), slugify(event.name)))
                self.redirect('/confirm/%s-%s' % (event.key().id(), slugify(event.name)))

        except Exception, e:
            message = str(e)
            if 'match format' in message:
                message = 'Date is required.'
            if message.startswith('Property'):
                message = message[9:].replace('_', ' ').capitalize()
            # This is NOT a reliable way to handle erorrs
            #set_cookie(self.response.headers, 'formerror', message)
            #set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
            #self.redirect('/new')
            error = message
            self.response.out.write(template.render('templates/error.html', locals()))
      if not token:
          request.errors = 'Invalid username or password'
      else:
          request.errors = 'Login successful'
    except Exception, e:
      logging.error(str(e))
      request.errors = 'Failed to login'

  #if request.user:
  #  return http.HttpResponseRedirect('/login/logout')
  
  c = template.RequestContext(request, locals())    
  t = loader.get_template('login/login.html')
  response = http.HttpResponse(t.render(c))
  if token:
      utils.set_cookie(response, 'token', token)    
  return response

def login_logout(request):
  token       = utils.get_request_value(request, 'token')
  if token:
      securityservice.SecurityService.logoff_user_token(token)
      
  c = template.RequestContext(request, locals())
  t = loader.get_template('login/logout.html')

  response = http.HttpResponse(t.render(c))
  utils.set_cookie(response, 'token', '')
  return response

def login_forgot(request):
Exemple #22
0
    def post(self):
        user = users.get_current_user()
        try:
            start_time = datetime.strptime('%s %s:%s %s' % (
                self.request.get('start_date'),
                self.request.get('start_time_hour'),
                self.request.get('start_time_minute'),
                self.request.get('start_time_ampm')), '%m/%d/%Y %I:%M %p')
            end_time = datetime.strptime('%s %s:%s %s' % (
                self.request.get('end_date'),
                self.request.get('end_time_hour'),
                self.request.get('end_time_minute'),
                self.request.get('end_time_ampm')), '%m/%d/%Y %I:%M %p')
            conflicts = Event.check_conflict(
                start_time,end_time,
                self.request.get('setup'),
                self.request.get('teardown'),
                self.request.get_all('rooms')
            )
            if conflicts:
                if "Deck" in self.request.get_all('rooms') or "Savanna" in self.request.get_all('rooms'):
                    raise ValueError('Room conflict detected <small>(Note: Deck &amp; Savanna share the same area, two events cannot take place at the same time in these rooms.)</small>')
                else:
                    raise ValueError('Room conflict detected')
            if not self.request.get('details'):
              raise ValueError('You must provide a description of the event')
            if not self.request.get('estimated_size').isdigit():
              raise ValueError('Estimated number of people must be a number')
            if not int(self.request.get('estimated_size')) > 0:
              raise ValueError('Estimated number of people must be greater then zero')
            if (end_time-start_time).days < 0:
                raise ValueError('End time must be after start time')
            if (  self.request.get( 'contact_phone' ) and not is_phone_valid( self.request.get( 'contact_phone' ) ) ):
                raise ValueError( 'Phone number does not appear to be valid' )
            else:
                event = Event(
                    name = cgi.escape(self.request.get('name')),
                    start_time = start_time,
                    end_time = end_time,
                    type = cgi.escape(self.request.get('type')),
                    estimated_size = cgi.escape(self.request.get('estimated_size')),
                    contact_name = cgi.escape(self.request.get('contact_name')),
                    contact_phone = cgi.escape(self.request.get('contact_phone')),
                    details = cgi.escape(self.request.get('details')),
                    url = cgi.escape(self.request.get('url')),
                    fee = cgi.escape(self.request.get('fee')),
                    notes = cgi.escape(self.request.get('notes')),
                    rooms = self.request.get_all('rooms'),
                    expired = local_today() + timedelta(days=PENDING_LIFETIME), # Set expected expiration date
                    setup = int(self.request.get('setup') or 0),
                    teardown = int(self.request.get('teardown') or 0)
                )
                event.put()
                log = HDLog(event=event,description="Created new event")
                log.put()
                notify_owner_confirmation(event)
                notify_event_change(event)
                set_cookie(self.response.headers, 'formvalues', None)

                rules = memcache.get("rules")
                if(rules is None):
                    try:
                        rules = urlfetch.fetch("http://wiki.hackerdojo.com/api_v2/op/GetPage/page/Event+Policies/_type/html", "GET").content
                        memcache.add("rules", rules, 86400)
                    except Exception, e:
                        rules = "Error fetching rules.  Please report this error to [email protected]."
                self.response.out.write(template.render('templates/confirmation.html', locals()))


        except ValueError, e:
            message = str(e)
            if 'match format' in message:
                message = 'Date is required.'
            if message.startswith('Property'):
                message = message[9:].replace('_', ' ').capitalize()
            # This is NOT a reliable way to handle erorrs
            #set_cookie(self.response.headers, 'formerror', message)
            #set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
            #self.redirect('/new')
            error = message
            self.response.out.write(template.render('templates/error.html', locals()))
Exemple #23
0
 def __init__(self):
     self.menu_dict = {}  # this variable is shared by multiple methods...
     cookies = set_cookie()
     setattr(type(self), 'COOKIES', cookies)  # COOKIES is static variable
Exemple #24
0
            if not token:
                request.errors = 'Invalid username or password'
            else:
                request.errors = 'Login successful'
        except Exception, e:
            logging.error(str(e))
            request.errors = 'Failed to login'

    #if request.user:
    #  return http.HttpResponseRedirect('/login/logout')

    c = template.RequestContext(request, locals())
    t = loader.get_template('login/login.html')
    response = http.HttpResponse(t.render(c))
    if token:
        utils.set_cookie(response, 'token', token)
    return response


def login_logout(request):
    token = utils.get_request_value(request, 'token')
    if token:
        securityservice.SecurityService.logoff_user_token(token)

    c = template.RequestContext(request, locals())
    t = loader.get_template('login/logout.html')

    response = http.HttpResponse(t.render(c))
    utils.set_cookie(response, 'token', '')
    return response
Exemple #25
0
    def post(self):
        user = users.get_current_user()
        try:
            start_time = datetime.strptime(
                "%s %s:%s %s"
                % (
                    self.request.get("start_date"),
                    self.request.get("start_time_hour"),
                    self.request.get("start_time_minute"),
                    self.request.get("start_time_ampm"),
                ),
                "%m/%d/%Y %I:%M %p",
            )
            end_time = datetime.strptime(
                "%s %s:%s %s"
                % (
                    self.request.get("end_date"),
                    self.request.get("end_time_hour"),
                    self.request.get("end_time_minute"),
                    self.request.get("end_time_ampm"),
                ),
                "%m/%d/%Y %I:%M %p",
            )
            conflicts = Event.check_conflict(start_time, end_time, self.request.get_all("rooms"))
            if conflicts:
                if "Deck" in self.request.get_all("rooms") or "Savanna" in self.request.get_all("rooms"):
                    raise ValueError(
                        "Room conflict detected <small>(Note: Deck &amp; Savanna share the same area, two events cannot take place at the same time in these rooms.)</small>"
                    )
                else:
                    raise ValueError("Room conflict detected")
            if not self.request.get("details"):
                raise ValueError("You must provide a description of the event")
            if not self.request.get("estimated_size").isdigit():
                raise ValueError("Estimated number of people must be a number")
            if not int(self.request.get("estimated_size")) > 0:
                raise ValueError("Estimated number of people must be greater then zero")
            if (end_time - start_time).days < 0:
                raise ValueError("End time must be after start time")
            if self.request.get("contact_phone") and not is_phone_valid(self.request.get("contact_phone")):
                raise ValueError("Phone number does not appear to be valid")
            else:
                event = Event(
                    name=cgi.escape(self.request.get("name")),
                    start_time=start_time,
                    end_time=end_time,
                    type=cgi.escape(self.request.get("type")),
                    estimated_size=cgi.escape(self.request.get("estimated_size")),
                    contact_name=cgi.escape(self.request.get("contact_name")),
                    contact_phone=cgi.escape(self.request.get("contact_phone")),
                    details=cgi.escape(self.request.get("details")),
                    url=cgi.escape(self.request.get("url")),
                    fee=cgi.escape(self.request.get("fee")),
                    notes=cgi.escape(self.request.get("notes")),
                    rooms=self.request.get_all("rooms"),
                    expired=local_today() + timedelta(days=PENDING_LIFETIME),  # Set expected expiration date
                )
                event.put()
                log = HDLog(event=event, description="Created new event")
                log.put()
                notify_owner_confirmation(event)
                notify_new_event(event)
                set_cookie(self.response.headers, "formvalues", None)

                rules = memcache.get("rules")
                if rules is None:
                    try:
                        rules = urlfetch.fetch(
                            "http://wiki.hackerdojo.com/api_v2/op/GetPage/page/Event+Policies/_type/html", "GET"
                        ).content
                        memcache.add("rules", rules, 86400)
                    except Exception, e:
                        rules = "Error fetching rules.  Please report this error to [email protected]."
                self.response.out.write(template.render("templates/confirmation.html", locals()))

        except Exception, e:
            message = str(e)
            if "match format" in message:
                message = "Date is required."
            if message.startswith("Property"):
                message = message[9:].replace("_", " ").capitalize()
            # This is NOT a reliable way to handle erorrs
            # set_cookie(self.response.headers, 'formerror', message)
            # set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
            # self.redirect('/new')
            error = message
            # this is not the permanent answer but just for now
            cdn = "http://cdn.hackerdojo.com"
            self.response.out.write(template.render("templates/error.html", locals()))
Exemple #26
0
    def post(self):
        user = users.get_current_user()
        try:
            start_time = datetime.strptime(
                "%s %s:%s %s"
                % (
                    self.request.get("start_date"),
                    self.request.get("start_time_hour"),
                    self.request.get("start_time_minute"),
                    self.request.get("start_time_ampm"),
                ),
                "%m/%d/%Y %I:%M %p",
            )
            end_time = datetime.strptime(
                "%s %s:%s %s"
                % (
                    self.request.get("end_date"),
                    self.request.get("end_time_hour"),
                    self.request.get("end_time_minute"),
                    self.request.get("end_time_ampm"),
                ),
                "%m/%d/%Y %I:%M %p",
            )
            conflicts = Event.check_conflict(start_time, end_time, self.request.get_all("rooms"))
            if conflicts:
                if "Deck" in self.request.get_all("rooms") or "Savanna" in self.request.get_all("rooms"):
                    raise ValueError(
                        "Room conflict detected <small>(Note: Deck &amp; Savanna share the same area, two events cannot take place at the same time in these rooms.)</small>"
                    )
                else:
                    raise ValueError("Room conflict detected")
            if not self.request.get("estimated_size").isdigit():
                raise ValueError("Estimated number of people must be a number")
            if not int(self.request.get("estimated_size")) > 0:
                raise ValueError("Estimated number of people must be greater then zero")
            if (end_time - start_time).days < 0:
                raise ValueError("End time must be after start time")
            if self.request.get("contact_phone") and not is_phone_valid(self.request.get("contact_phone")):
                raise ValueError("Phone number does not appear to be valid")
            else:
                event = Event(
                    name=cgi.escape(self.request.get("name")),
                    start_time=start_time,
                    end_time=end_time,
                    type=cgi.escape(self.request.get("type")),
                    estimated_size=cgi.escape(self.request.get("estimated_size")),
                    contact_name=cgi.escape(self.request.get("contact_name")),
                    contact_phone=cgi.escape(self.request.get("contact_phone")),
                    details=cgi.escape(self.request.get("details")),
                    url=cgi.escape(self.request.get("url")),
                    fee=cgi.escape(self.request.get("fee")),
                    notes=cgi.escape(self.request.get("notes")),
                    rooms=self.request.get_all("rooms"),
                    expired=local_today() + timedelta(days=PENDING_LIFETIME),  # Set expected expiration date
                )
                event.put()
                log = HDLog(event=event, description="Created new event")
                log.put()
                notify_owner_confirmation(event)
                notify_new_event(event)
                set_cookie(self.response.headers, "formvalues", None)
                # self.redirect('/event/%s-%s' % (event.key().id(), slugify(event.name)))
                self.redirect("/confirm/%s-%s" % (event.key().id(), slugify(event.name)))

        except Exception, e:
            message = str(e)
            if "match format" in message:
                message = "Date is required."
            if message.startswith("Property"):
                message = message[9:].replace("_", " ").capitalize()
            # This is NOT a reliable way to handle erorrs
            # set_cookie(self.response.headers, 'formerror', message)
            # set_cookie(self.response.headers, 'formvalues', dict(self.request.POST))
            # self.redirect('/new')
            error = message
            self.response.out.write(template.render("templates/error.html", locals()))