Example #1
0
    def get(self):
        from_user, to_user, time, place = self.request.get("result").split(":")
        key = db.Key.from_path('User', from_user)
        from_user = User.get(key)
        key = db.Key.from_path('User', str(to_user))
        to_user = User.get(key)
        
        texter.text(from_user.number, "{} has accepted your invitaion!".format(to_user.name))
        
        template_values = {
			'from':from_user,
			'time':time,
			'place':place
        }
        template = jinja_environment.get_template("confirmation.html")
        self.response.out.write(template.render(template_values))
Example #2
0
def do_lookup(request,user=None):
  ans = {"logged": "yes"}
  if not user:
    user = getUser(request)

  if not user:
    ans["logged"] = "no"  # users who haven't logged in can't see any data
    return ans

  ans["user_name"] = user.name
  ans["user_email"] = user.email
  ans["is_admin"] = user.is_admin()

  # get all the users and their usernames
  all_users = User.query().fetch()  
  user_by_name = {user.name: user} 
  for useri in all_users:
    user_by_name[useri.name] = useri

  # get all the fillouts. This is not strongly consistent. We only need to do that for the current user
  fillout_query = Fillout.query().fetch()
  fillouts = {}
  for fillout in fillout_query:
    if fillout.quiz_id not in fillouts: fillouts[fillout.quiz_id] = {}
    fillouts[fillout.quiz_id][fillout.username] = fillout.to_dict()

  # information about quizzes
  query = Quiz.query().fetch()
  ans["quizzes"] = []
  for quiz in query:
    if not ans["is_admin"] and quiz.status=="editor": continue
    quiz_dict = quiz.to_dict();
    quiz_id = quiz.key.parent().id()
    quiz_dict["id"] = quiz_id

    # get the fillouts for this quiz
    this_fillouts = fillouts.get(quiz_id,{})
    fillout_user_query = Fillout.query(ancestor=fillout_key(user.name,quiz_id)).fetch()
    if len(fillout_user_query)>0:
      fillout = fillout_user_query[0].to_dict()
      this_fillouts[user.name] = fillout
      quiz_dict["fillout"] = fillout

    if user.name in this_fillouts or quiz_dict["status"]=="old":
      quiz_dict["scores"] = score_quiz(quiz,this_fillouts)
    else: # the user hasn't filled this quiz yet, and shouldn't be able to see the answers
      for question in quiz_dict["questions"]:
        del question["answer"]
        del question["source"]

    # question ratings
    ratingQuery = QuestionRatings.query(QuestionRatings.quiz_id==quiz_id,QuestionRatings.username==ans["user_name"]).fetch()
    if len(ratingQuery)>0:
      ratings = ratingQuery[0].ratings
      for idx,rating in enumerate(ratings):
        if(rating!=-1): quiz_dict["questions"][idx]["rating"] = rating

    ans["quizzes"].append(quiz_dict)

  return ans
Example #3
0
    def post(self):     
        start_times = self.request.get_all('start_time')
        end_times = self.request.get_all('end_time')
        key = db.Key.from_path('User', self.session['id'])
        current_user = User.get(key)
        current_user.clearFreeTime()
        picks = []
        checked = self.request.get_all('food')
        for c in checked:
            if c == 'other':
                picks.append(self.request.get('picks'))
                continue
            picks.append(c)
        current_user.top_picks = ", ".join(picks)
        for index, t in enumerate(start_times):
            s_time = t
            e_time = end_times[index]
            s_time = datetime.time(int(s_time.split(':')[0]), int(s_time.split(':')[1]))
            current_user.last_start_time = s_time
            s_time = datetime.datetime.combine(datetime.datetime.now().date(), s_time)
            e_time = datetime.time(int(e_time.split(':')[0]), int(e_time.split(':')[1]))
            current_user.last_end_time = e_time
            e_time = datetime.datetime.combine(datetime.datetime.now().date(), e_time) 
            free_time = FreeTimeZone(reference=current_user, startTime=s_time, endTime=e_time)
            free_time.put()

        current_user.put()
        self.redirect('/results')
Example #4
0
 def get_context(self):
     last_week = datetime.datetime.now() - datetime.timedelta(days=7)
     signups_this_week = User.select().where(User.join_date > last_week).count()
     messages_this_week = Message.select().where(Message.pub_date > last_week).count()
     return {
         'signups': signups_this_week,
         'messages': messages_this_week,
     }
Example #5
0
def login():
    """login api"""
    try:
        username = request.values['username']
        password = request.values['password']
        assert isinstance(username, basestring) \
            and isinstance(password, basestring)
    except Exception as e:
        return {'error': 'illegal login format!' + str(e)}

    auth = User(username, password)
    err = auth.get_error()
    if err:
        return err
    login_user(auth)
    log_info('user {0} succesfully logged in'.format(username))
    return {'success': 1}
Example #6
0
 def post(self):
     username = self.request.get("username")
     password = self.request.get("password")
     opt_in = True if self.request.get("receive_text") else False
     num = texter.num_parse(self.request.get("phonenumber"))
     cur_user = User.get_by_key_name(username)
     template = jinja_environment.get_template("views/signup.html")
     if cur_user:
         template_values = {'session':self.session}
         template_values['flash'] = 'Oops that username is taken!'
         self.response.out.write(template.render(template_values))
         return
     cur_user = User.get_or_insert(username, name=username, phone_number = num, password=password, text_opt_in = opt_in, money_donated=0.0, money_raised=0.0)        
         # no authentication hacks, sorry Wagner
     self.session['user_name'] = username
     self.session['num'] = num
     self.session['authenticated'] = True
     self.redirect('/')
Example #7
0
 def get(self):
     template_values = {'session':self.session}
     template_values['user'] = User.gql("WHERE name = :1", self.request.get('id')).fetch(1)[0] # shady, get the user w/ username
     template_values['unfulfilled'] = Wish.gql("WHERE user_key = :1 AND status != 'fulfilled'", self.request.get('id'))
     template_values['fulfilled'] = Wish.gql("WHERE user_key = :1 AND status = 'fulfilled'", self.request.get('id'))
     template_values['to_complete'] = Wish.gql("WHERE user_fulfiller_key = :1 AND status != 'fulfilled'", self.request.get('id'))
     template_values['completed'] = Wish.gql("WHERE user_fulfiller_key = :1 AND status = 'fulfilled'", self.request.get('id'))
     template_values['flash'] = self.request.get('flash')
     template = jinja_environment.get_template("views/user.html")
     self.response.out.write(template.render(template_values))
Example #8
0
 def get(self):
     for user in User.all():
         if user.text_opt_in:
             self.response.out.write("<b>"+user.name+"</b></br>")
             # Take three random wishes that are not from the user
             potential_wishes = [wish for wish in Wish.all() if wish.user_key != user.name]
             user_wishes = random.sample(potential_wishes, min(3, len(potential_wishes)))
             for wish in user_wishes:
                 self.response.out.write(wish.tagline+"<br>")
                 texter.send_message(user.phone_number, "Consider fulfilling " + wish.tagline + " on http://hackserendipity.appspot.com/")
Example #9
0
    def get(self):
        key = db.Key.from_path('User', self.session['id'])
        current_user = User.get(key)
        my_valid_friend = current_user.valid_friends()

        friends_times = {}
        for friend in my_valid_friend:
            friends_times[(friend, (friend.updated - datetime.timedelta(hours=8)).strftime('%b, %d - %I:%M %p'))] = current_user.shared_free(friend)
        template_values = {'friends':friends_times}
        template = jinja_environment.get_template("result.html")
        self.response.out.write(template.render(template_values))
Example #10
0
  def post(self,idStr):
    json = simplejson.loads(self.request.body)
    if "password" not in json or json["password"]!="ruilov12": return

    if "users" in json:
      for user_dict in json["users"]:
        ndb_user = User(name=user_dict["name"],email=user_dict["email"],subscribed=user_dict["subscribed"])
        if ndb_user.email=="*****@*****.**":
          ndb_user.password = ndb_user.password_hash("ruilov12")
        ndb_user.put()

    if "quizzes" in json:
      for quiz_dict in json["quizzes"]:
        quiz = getQuiz(quiz_dict["id"])
        quiz.status = quiz_dict["status"]
        if "releaseDate" in quiz_dict and quiz_dict["releaseDate"]!=None:
          quiz.releaseDate = utils.date_from_str(quiz_dict["releaseDate"])
        questionArr = []
        for question_dict in quiz_dict["questions"]:
          question = Question()
          question.text = question_dict["text"]
          question.source = question_dict["source"]
          question.answer = question_dict["answer"]
          questionArr.append(question)
        quiz.questions = questionArr
        quiz.put()

    if "fillouts" in json:
      for fillout_dict in json["fillouts"]:
        fillout = Fillout(parent=fillout_key(fillout_dict["username"],fillout_dict["quiz_id"]),
            username=fillout_dict["username"],quiz_id=fillout_dict["quiz_id"])

        fillout.ranked = fillout_dict["ranked"]
        fillout.guesses_low = [float(x) for x in fillout_dict["guesses_low"]]
        fillout.guesses_high = [float(x) for x in fillout_dict["guesses_high"]]
        fillout.put()

    if "ratings" in json:
      for rating_dict in json["ratings"]:
        rating = QuestionRatings(username=rating_dict["username"],quiz_id=rating_dict["quiz_id"],ratings=rating_dict["ratings"])
        rating.put()
Example #11
0
  def get(self,qs):
    email = urllib.unquote(self.request.get("email"))
    hashs = self.request.get("hash")

    if not utils.checkResetHash(email,hashs):
      return

    users = User.query().fetch()
    for user in users:
      if user.email != email: continue
      template = JINJA_ENVIRONMENT.get_template("html/template.html")
      template_values = {}
      self.response.write(template.render(template_values))
      return
Example #12
0
    def post(self):
        key = db.Key.from_path('User', self.session['id'])
        current_user = User.get(key)
        time = self.request.get('time')
        place = self.request.get('place')
        checked = self.request.get_all('user')
        friends = []
        for c in checked:
            key = db.Key.from_path('User', c)
            friend = User.get(key)
            friends.append(friend.name + " - " + str(friend.number))
            url = "http://food-me.appspot.com/accepted?result={}:{}:{}:{}".format(current_user.id, friend.id, time, place.replace(' ', '%20'))
            x = "http://is.gd/create.php?format=simple&url={}".format(url)
            result = urlfetch.fetch(x).content
            texter.text(friend.number, "{} has invited you to eat at {} at {}! Click here to accept: {}".format(current_user.name, place, time, result))

        template_values = {
            'friends':", ".join(friends),
            'place': place,
            'time': time
        }
        template = jinja_environment.get_template("success.html")
        self.response.out.write(template.render(template_values))
Example #13
0
 def post(self):
     if not self.session['authenticated']:
         return self.redirect('/login?redirect=true')
     template_values = {'session':self.session}
     wish = Wish.get(self.request.get("key"))
     if self.request.get('delete'):
         wish.status = 'requested'
         wish.user_fulfiller_key = None
         flash = 'You are no longer fulfilling ' + wish.tagline
     elif self.request.get('confirm'):
         wish.status = 'fulfilled'
         fulfiller =  User.get_by_key_name(wish.user_fulfiller_key)
         wisher = User.get_by_key_name(wish.user_key)
         fulfiller.money_raised += wish.cache_money
         wisher.money_donated += wish.cache_money
         fulfiller.put()
         wisher.put()
         flash = 'Your wish of ' + wish.tagline + ' has been fulfilled!'
     else:
         wish.status = 'in progress'
         wish.user_fulfiller_key = self.session['user_name']
         flash = 'Fulfilling ' + wish.tagline
     wish.put()
     return self.redirect('/wish?key=' + str(wish.key()) + '&flash=' + flash)
Example #14
0
  def post(self):
    json = simplejson.loads(self.request.body)
    all_users = User.query().fetch()

    hashs = json["resetHash"]
    email = json["email"]
    username = json["username"]
    password = json["password"]

    user = None
    if len(hashs)>0:
      if not utils.checkResetHash(email,hashs):
        utils.write_back(self,{"invalid hash": 1})
        return

      users = User.query().fetch()
      for ui in users:
        if ui.email == email:
          user = ui
          break
        
      if user == None:
        utils.write_back(self,{"invalid hash": 1})
        return

    else:
      for user in all_users:
        if user.email == email:
          utils.write_back(self,{"email exists": 1})
          return

        if user.name == username:
          utils.write_back(self,{"username exists": 1})
          return

      user = User(name=username,email=email,subscribed=True)

    user.password = user.password_hash(password)
    user.put()

    self.response.set_cookie('username', urllib.quote(user.name))
    self.response.set_cookie('hash', urllib.quote(cookieHash(user.name)))

    ans = lookup_util.do_lookup(self,user)
    utils.write_back(self,ans)
Example #15
0
 def post(self):
     username = self.request.get("username")
     password = self.request.get("password")
     cur_user = User.get_by_key_name(username)
     template = jinja_environment.get_template("views/login.html")
     
     if cur_user == None:
         template_values = {"denied": True, 'session':self.session}
         self.response.out.write(template.render(template_values))
         return
     if cur_user.password == password:
         # terrible authentication hacks, sorry Wagner
         self.session['user_name'] = username
         self.session['num'] = cur_user.phone_number
         self.session['authenticated'] = True
         self.redirect('/')
         
     else:
         self.session['authenticated'] = False
         template_values = {"denied": True, 'session':self.session}
         self.response.out.write(template.render(template_values))
Example #16
0
  def post(self):
    json = simplejson.loads(self.request.body)
    username = json["username"]

    user = None
    users = User.query().fetch()
    for ui in users:
      if ui.email == username or ui.name == username:
        user = ui
        break

    if user:
      template = JINJA_ENVIRONMENT.get_template("html/password_reset.html")
      message = mail.EmailMessage()
      message.sender = "*****@*****.**"
      message.subject = "The Market Making Game - reset your password"

      template_values = {"link": utils.resetLink(user.email,user.name)}
      message.html = template.render(template_values)
      message.to = user.email
      message.send()
Example #17
0
  def post(self):
    json = simplejson.loads(self.request.body)
    username = json["username"]

    all_users = User.query().fetch()

    for user in all_users:
      if user.name != json["username"] and user.email != json["username"]:
        continue
        
      if not user.checkPassword(json["password"]):
        utils.write_back(self,{"incorrect": 1})
        return

      self.response.set_cookie('username', urllib.quote(user.name))
      self.response.set_cookie('hash', urllib.quote(cookieHash(user.name)))
      
      ans = lookup_util.do_lookup(self,user)
      utils.write_back(self,ans)
      return

    utils.write_back(self,{"incorrect": 1})
    
Example #18
0
@app.route('/products')
def products():
    if "names" not in session:
        return redirect(url_for("login"))
    else:
        return render_template("products.html", names=session["names"])


@app.route('/logout')
def logout():
    session.pop("names")
    session.pop("id")
    return redirect(url_for("login"))


if __name__ == '__main__':
    #User.drop_table()
    try:
        Product.create_table()
    except OperationalError:
        pass

    try:
        User.create_table()
    except OperationalError:
        pass
    app.run(port=8000)

    #host="0.0.0.0" port=8000
Example #19
0
 def get(self):
     for wish in Wish.all():
         wish.delete()
     for wish in User.all():
         wish.delete()   
     self.redirect("/")
Example #20
0
 def get(self):
     template_values = {'session':self.session}
     template_values['users'] = User.gql("ORDER BY money_donated DESC")
     template = jinja_environment.get_template("views/users.html")
     self.response.out.write(template.render(template_values))
Example #21
0
    def any(self, provider_name):

        # It all begins with login.
        result = authomatic.login(Webapp2Adapter(self), provider_name)

        # Do not write anything to the response if there is no result!
        if result:
            # If there is result, the login procedure is over and we can write to response.
            self.response.write('<a href="..">Home</a>')

            if result.error:
                # Login procedure finished with an error.
                self.response.write('<h2>Damn that error: {}</h2>'.format(result.error.message))

            elif result.user:
                # Hooray, we have the user!

                # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
                # We need to update the user to get more info.
                if not (result.user.name and result.user.id):
                    result.user.update()

                # Welcome the user.
                user_name = result.user.name
                user_id = result.user.id
                #self.response.write(result.user.credentials)
                self.redirect('/pick')
                # Seems like we're done, but there's more we can do...

                # If there are credentials (only by AuthorizationProvider),
                # we can _access user's protected resources.
                if result.user.credentials:

                    # Each provider has it's specific API.
                    if result.provider.name == 'fb':
                        self.response.write('Your are logged in with Facebook.<br />')

                        # We will access the user's 5 most recent statuses.

                        url = 'https://graph.facebook.com/me/friends'
                        # Access user's protected resource.
                        response = result.provider.access(url)
                        #self.response.write(response.data['data'][4])

                        if response.status == 200:
                            # Parse response.
                            friends = {}
                            user_friends = response.data['data']
                            for item in user_friends:
                                friends[item['id']] = item['name']
                            
                            user = User.get_or_insert(user_id, id=user_id, name=user_name)
                            if self.session['number'] != None:
                                user.number = self.session['number']
                            user.friends = str(friends)
                            user.put()
                            
                            self.session['id'] = user_id
                            self.session['name'] = user_name
                            
                            error = response.data.get('error')

                            if error:
                                self.response.write('Damn that error: {}!'.format(error))
                        else:
                            self.response.write('Damn that unknown error!<br />')
                            self.response.write('Status: {}'.format(response.status))
def load_user(user_id):
    user = User()
    return user
Example #23
0
 def getUser(self):
     user = User()
     user.username = '******'
     user.email = '*****@*****.**'
     user.name = "Your Name"
     return user