Exemplo n.º 1
0
def getUser(user_id):
  users = UserDB.query(UserDB.user_id == user_id)
  if users.count() > 1:
    raise endpoints.InternalServerErrorException('Multiple Users for %s found.' %
                                            (user_id,))
  elif users.count() == 1:
    return UserResponse(msg='User '+user_id, code='OK', data=[userDB_to_user(users.get())])

  raise endpoints.NotFoundException('User %s not found.' %
                                            (user_id,))
Exemplo n.º 2
0
    def get_memberlist( self ):
        users = User.all()
        tmp   = []
        logging.info("COUNT %d" % users.count())

        # Build list of everyone in this troupe
        i = 0
        for u in users:
            if u.troupe.name == self.name:
                if u.first_name and u.last_name and u.email:
                    tmp.append( (u.score, u.first_name, u.last_name[0]) )
                    logging.info( "%s" % str(tmp[i]) )
                    i += 1
        
        # Sort list
        tmp = sorted( tmp, key=lambda x: -x[0] ) # Sort in desc order by score

        # Construct list to return
        ret = []
        i   = 1
        for t in tmp:
            ret.append( "%d. %s %s." % (i, t[1], t[2]) )
            i += 1

        return ret
  def _insert_item_all_users(self):
    """Insert a timeline item to all authorized users."""
    logging.info('Inserting timeline item to all users')
    users = Credentials.all()
    total_users = users.count()

    if total_users > 10:
      return 'Total user count is %d. Aborting broadcast to save your quota' % (
          total_users)
    body = {
        'text': 'Hello Everyone!',
        'notification': {'level': 'DEFAULT'}
    }

    batch_responses = _BatchCallback()
    batch = BatchHttpRequest(callback=batch_responses.callback)
    for user in users:
      creds = StorageByKeyName(
          Credentials, user.key().name(), 'credentials').get()
      mirror_service = util.create_service('mirror', 'v1', creds)
      batch.add(
          mirror_service.timeline().insert(body=body),
          request_id=user.key().name())

    batch.execute(httplib2.Http())
    return 'Successfully sent cards to %d users (%d failed).' % (
        batch_responses.success, batch_responses.failure)
Exemplo n.º 4
0
    def get_memberlist(self):
        users = User.all()
        tmp = []
        logging.info("COUNT %d" % users.count())

        # Build list of everyone in this troupe
        i = 0
        for u in users:
            if u.troupe.name == self.name:
                if u.first_name and u.last_name and u.email:
                    tmp.append((u.score, u.first_name, u.last_name[0]))
                    logging.info("%s" % str(tmp[i]))
                    i += 1

        # Sort list
        tmp = sorted(tmp, key=lambda x: -x[0])  # Sort in desc order by score

        # Construct list to return
        ret = []
        i = 1
        for t in tmp:
            ret.append("%d. %s %s." % (i, t[1], t[2]))
            i += 1

        return ret
Exemplo n.º 5
0
 def post(self, error_msg=None):
     email = self.request.get("email")
     username = self.request.get("username")
     users = User.all().filter('email', email)
     user = User()
     user.email = email
     user.username = username
     user.fullname = self.request.get("firstname")+" "+self.request.get("lastname")
     user.birthday = datetime.datetime.strptime(self.request.get("birthday"), '%Y-%m-%d')
     user.set_password(self.request.get("password")) #set password. need encrypt. 
     user.firstname = self.request.get("firstname")
     user.lastname = self.request.get("lastname")
     user.country = self.request.get("country")
     gender = self.request.get("gender")
     if gender:
         gender_ = str(gender)[0:1]
         user.gender = gender_
     if users.count() == 0:
         user.put()
         #init() the session
         sessions.Session().login_user(user)
         self.redirect("/")
         return
     else:
         error_msg = "That email address has already been registered."
     template_values = {
        "temp_user": user,
        "error": error_msg
     }
     self.generate('signup.html',template_values)
Exemplo n.º 6
0
def authenticate(credential):
    """
    If the given credentials are valid, return a User object.
    """
    if credential is None:
        return None

    query = db.Query(User)
    users = query.filter('username ='******'%s' " %
                      credential[0])
        return None

    users = query.filter('is_active =', True)
    user = users.get()

    if user and credential[1] is not None:
        if (not user.check_password(raw_password=credential[1])):
            user = None

    logging.debug('authenticate: %s' % str(user))

    return user
Exemplo n.º 7
0
 def DeleteOpenID(self,request):
     openid = request.get("openid")
     users = User.all().filter('openids', openid)
     if users.count() != 0:
         user = users[0]
         user.openids.remove(db.Category(openid.strip().encode('utf8')))
         user.put()
     return True
Exemplo n.º 8
0
 def list_users(self, message=None):
   logging.debug(  "processing 'list users' command" )
   #
   # List the users in the Db
   google_id =  db.IM("xmpp", message.sender).address.split('/')[0]
   users = db.GqlQuery("SELECT * FROM User WHERE google_id = :1", google_id)
   if ( users.count() == 0  ) :
       notification = "You haven't registered any YTMT ids.  Use the 'add' command to register an Id."
   else:
       notification = "You are monitoring the following YTMT users: "
       for u in users:
               notification = notification + "  " + u.ytmt_id
   message.reply(notification)
Exemplo n.º 9
0
def addUser(new_user_id='', new_email='', new_name='', new_description='', new_image_url='', new_tag='', new_disabled=''):
  response = Response(msg="Unknown Error", code="ERROR", data=[])
  users = UserDB.query(UserDB.user_id == new_user_id)

  if users.count() >= 1:
    return UserResponse(msg="User with user_id "+new_user_id+" already exists!", code="ERROR", data=[])

  user = UserDB(user_id=new_user_id,
                email=new_email,
                name=new_name,
                description=new_description,
                image_url=new_image_url,
                tag=new_tag,
                disabled=new_disabled)
  user.put()
  response = UserResponse(msg="User "+new_user_id+" added succesfully", code="OK", data=[userDB_to_user(user)])

  return response
Exemplo n.º 10
0
    def status(self):
        token = cgi.escape(self.request.get('token'))
        
        # check user doesn't already have a request
        users = db.GqlQuery("SELECT * FROM InstanceUser WHERE token = :token", token=token)
        if users.count() == 0:
            self.message("Invalid token - nice try!")
            return

        user = users[0]
        
        conn = boto.ec2.connect_to_region(REGION,
            aws_access_key_id=ACCESS_KEY,
            aws_secret_access_key=SECRET_KEY)
        
        # if user doesn't have a reservation, then launch some instances
        if user.reservation is None:
            self.launch(conn, user)
        
        # Get the reservation object
        params = {"Filter.0.Name": "reservation-id", "Filter.0.Value.0" : user.reservation}
        reservations = conn.get_list('DescribeInstances', params,
                             [('item', boto.ec2.instance.Reservation)], verb='POST')
        
        if len(reservations) == 0:
            self.message("Something went wrong - not your fault!  Tell Tom.")
            return
        
        reservation = reservations[0]
        pending = []
        running = []
        
        for instance in reservation.instances:
            instance.update()
            
            if instance.state != "running":
                pending.append({'id': instance.id, 'state': instance.state })
            else:
                running.append({'id': instance.id, 'address': instance.public_dns_name })

        path = os.path.join(os.path.dirname(__file__), 'templates/status.html')
        self.response.out.write(template.render(path, {'pending': pending, 'running': running}))
Exemplo n.º 11
0
def retrieve(usr):
    """Reads the user info from the database.

    :param usr: The GAE user object.
    :return: The User retrieved, or a client created appropriately if not found.
    """
    toret = None

    if usr:
        usr_email = usr.email()
        users = User.query(User.email == usr_email).order(-User.added)

        if not users or users.count() < 1:
            if usr_email.endswith(AppInfo.AllowedUserEmailNamespace):
                toret = create(usr, User.Level.Client)
        else:
            toret = users.iter().next()
            toret.usr = usr

    return toret
Exemplo n.º 12
0
 def post(self, error_msg=None):
     email = self.request.get("email")
     password = self.request.get("password")
     if(email.find('@')!=-1):
         users = User.all().filter('email', email)
     else:
         users = User.all().filter('username', email)
     if users.count() == 0:
         error_msg = "You have entered an incorrect e-mail address or username."
     else:
         user = users.get()
         if not user.check_password(password):
             error_msg = "You have entered an incorrect password."
         else:
             sessions.Session().login_user(user)
             self.redirect("/")
             return
     template_values = {
        "email": email,
        "error": error_msg
     }
     self.generate('login.html',template_values)
Exemplo n.º 13
0
    def get_uuid_memberlist(self):
        users = User.all()
        tmp = []
        logging.info("COUNT %d" % users.count())

        # Build list of everyone in this troupe
        i = 0
        for u in users:
            if u.troupe.name == self.name:
                if u.first_name and u.last_name and u.email:
                    tmp.append((u.score, u.uuid))
                    logging.info("%s" % str(tmp[i]))
                    i += 1

        # Sort list
        tmp = sorted(tmp, key=lambda x: -x[0])  # Sort in desc order by score

        logging.error("ORDER")
        for t in tmp:
            logging.error("%s %s" % (t[0], t[1]))

        return tmp
Exemplo n.º 14
0
    def get_uuid_memberlist( self ):
        users = User.all()
        tmp = []
        logging.info("COUNT %d" % users.count())

        # Build list of everyone in this troupe
        i = 0
        for u in users:
            if u.troupe.name == self.name:
                if u.first_name and u.last_name and u.email:
                    tmp.append( (u.score, u.uuid) )
                    logging.info( "%s" % str(tmp[i]) )
                    i += 1
        
        # Sort list
        tmp = sorted( tmp, key=lambda x: -x[0] ) # Sort in desc order by score

        logging.error("ORDER")
        for t in tmp:
            logging.error( "%s %s" % (t[0], t[1]) )

        return tmp
Exemplo n.º 15
0
 def get(self):
     self.response.headers['Content-Type'] = 'application/json'
     data = {}
     users = User.query().order(User.id)
     userData = ''
     i = users.count()
     j = 0
     for user in users:
         print user.id
         data['id'] = user.id
         data['fname'] = user.firstName
         data['mname'] = user.middleName
         data['lname'] = user.lastName
         data['email'] = user.email
         data['password'] = user.password
         """data['messages'] = user.messages"""
         j += 1
         if j != i:
             userData += json.dumps(data) + ","
         else:
             userData += json.dumps(data)
     userData = "[" + userData + "]"
     self.response.out.write(userData)
Exemplo n.º 16
0
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
	data = {}
        users = User.query().order(User.id)
        userData = ''
        i = users.count()
        j = 0
        for user in users:
           print user.id
	   data['id'] = user.id
	   data['fname'] = user.firstName
           data['mname'] = user.middleName
           data['lname'] = user.lastName
           data['email'] = user.email
           data['password'] = user.password
           """data['messages'] = user.messages"""
           j += 1
           if j != i:
           	userData += json.dumps(data) + ","
           else:
		userData += json.dumps(data)
        userData = "[" + userData + "]"
        self.response.out.write(userData)
Exemplo n.º 17
0
def authenticate(credential):
    """
    If the given credentials are valid, return a User object.
    """
    if credential is None:
        return None
        
    query = db.Query(User)
    users = query.filter('username ='******'%s' " % credential[0])
        return None
    
    users = query.filter('is_active =', True)
    user = users.get()

    if user and credential[1] is not None:
        if (not user.check_password(raw_password = credential[1])): 
            user = None

    logging.debug('authenticate: %s' % str(user))
    
    return user
Exemplo n.º 18
0
def getUser(email):
  logging.info(email)
  users = database.User.all()
  users.filter('email =', email)
  return users.get() if users.count(limit=1) else None
Exemplo n.º 19
0
 def PreCheckOrRedirect(self):
     users = User.all().filter("google_user =", self.google_user)
     if users.count() > 0:
         self.RedirectAndRaise('/')
Exemplo n.º 20
0
    def get(self):
        self.response.out.write('<html><body>')
        google_user = self.request.get("google_user")
        if ( google_user != "" ) :
            self.response.out.write( "<h1>Alerts for User " + google_user + "</h1>" )
            users = db.GqlQuery("SELECT * FROM User WHERE google_id = :1", google_user)
        else :
            #
            # Forget the current list of games in a web document for all users
            users = db.GqlQuery("SELECT * FROM User")

        #
        # Handle case of no users being registered
        if ( users.count() == 0  ) :
            logging.debug(  "No users registered " )
            self.response.out.write( "<h2>No Users Registered</h2>" )
            self.response.out.write( "To register YTMT ids, use google talk to connect to [email protected] ")
            self.response.out.write("then use the 'add {ytmt_id}' command to register your YTMT id.")
        #
        # Or handle each registered user
        else:
            for u in users:
                logging.debug(  "Processing " + u.ytmt_id)
                name = u.ytmt_id
                google_id = u.google_id
                self.response.out.write( "<h2>" + name + "'s Turn (alerting " +  google_id+ ")</h2>")
                #
                # Download the user's overview page
                s = Ytmt.ReadGamesPage_NotLoggedIn( name )
                if ( s != None ):

                    #
                    #
                    # First parse out games where it is your turn
                    games = Ytmt.FindGamesinPage_YourTurn( name, s)
                    #
                    # Save away the old "your turn" games list for this user to
                    # a dictionary and clear the database
                    old_dict = copy_gamesDb_to_dict_and_purge(name, games)
                    if (len(games) == 0):
                        self.response.out.write( "(No games)"  )
                    else:
                        self.response.out.write( "<hr>" )
                        self.response.out.write( "<ul>" )

                        for key in games:
                            g = games[key]
                            #
                            # Compare the old and new games list
                            # TODO: do this by querying the database & do away with dictionary
                            # If this is an old game and it was your turn last time then just print it - dont send IM
                            game_details = g.opponent +" in " + g.type + " game <a href=\"" + g.clicklink + "\">"+ g.game  + "</a>"
                            IM_game_details = g.opponent +" in " + g.type + " game "+ g.clicklink
                            if ( old_dict.has_key(g.game) == True and old_dict[g.game].whoseturn == g.player):
                                notification =  g.player + " still your turn against " + game_details
                                self.response.out.write( "<li>" + notification )
                            else:
                            # Else, new game or newly your turn - send the notification and save the game
                                logging.debug(  "saved game " + g.game + " " + name)
                                notification =  g.player + " it's now your turn against "
                                self.response.out.write( "<li><b>" + notification + game_details)
                                Notifier().notify(google_id, notification + IM_game_details)
                                logging.debug(  "Notifying google_id: " + notification + game_details)
                                save_game(g) # write game to database

                        self.response.out.write( "</ul>" )
                        self.response.out.write( "<hr>" )
                    #
                    # Now list games where it's not your turn
                    self.response.out.write( "<h2>" + name + "'s Opponent's Turn</h2>")
                    #
                    # List games where it's not your turn
                    games = Ytmt.FindGamesinPage_OpponentsTurn( name, s)
                    if (len(games) == 0):
                        self.response.out.write( "(No games)"  )
                    else:
                        self.response.out.write( "<ul>" )
                        for key in games:
                            g = games[key]
                            g.clicklink = g.clicklink.replace(" ", "+")
                            game_details = g.player +" in " + g.type + " game <a href=\"" + g.clicklink + "\">"+ g.game  + "</a>"
                            notification =  g.opponent + "'s turn against " + game_details
                            self.response.out.write( "<li>" + notification )

                        self.response.out.write( "</ul>" )
                    self.response.out.write( "<hr>" )

                else:
                    self.response.out.write( "No games to play or web access failed")


        self.response.out.write(   "</body></html>"   )
Exemplo n.º 21
0
  def get(self):

    action = self.request.get('action')
    logging.error(action)
    logging.error(action)
    if action == 'signout':
      self.response.headers['Set-Cookie'] = 'email=none;'
    
    if action == 'getSignin':

      email = self.request.get('email')
      password = self.request.get('password')
      autologin = self.request.get('autologin')

      
      
      users = db.GqlQuery("SELECT * FROM User where email = :1 and password = :2", email, password )
      
      if users.count() > 0:
        if autologin == "true":
          self.response.headers['Set-Cookie'] = 'email='+email+";"
        else:
          self.response.headers['Set-Cookie'] = 'email=none;'
        logging.error("logging in .....")
      else:
        users = db.GqlQuery("SELECT * FROM User where email = :1", "*****@*****.**" )
        for user in users:
          user.delete()
        newuser = User()
        newuser.email = "*****@*****.**"
        newuser.firstName = "David"
        newuser.lastName = "Kjos"
        newuser.password = "******"
        newuser.put()
      
        self.error(666)
      
    if action == 'getinsurance':
      logging.error("get insurance2.....")
      email = self.request.get('email')
      insurances = db.GqlQuery("SELECT * FROM Insurance where email = :1", email)
      self.response.out.write('<insurances>')
      for insurance in insurances:
        logging.error(insurance.data)
        self.response.out.write(insurance.data)
      self.response.out.write('</insurances>')
      
        
    if action == 'getpurchases':  
      logging.error("get purchases.....")
      email = self.request.get('email')
      self.response.out.write('<purchases>')
      purchases = db.GqlQuery("SELECT * FROM Purchase where email = :1", email)
      for purchase in purchases:
        logging.error(purchase.purchase)
        self.response.out.write(purchase.purchase)
      self.response.out.write('</purchases>')  
      plantings = db.GqlQuery("SELECT * FROM Planting where email = :1", email)

   
    if action == 'getplantings':  
      logging.error("get plantings.....")
      email = self.request.get('email')
      self.response.out.write('<plantings>')
      plantings = db.GqlQuery("SELECT * FROM Planting where email = :1", email)
      for planting in plantings:
        logging.error(planting.planting)
        self.response.out.write(planting.planting)
      self.response.out.write('</plantings>')   
 
    if action == 'getapplicants':  
      logging.error("getapplicants.....")
      email = self.request.get('email')
      self.response.out.write('<applicants>')
      applicants = db.GqlQuery("SELECT * FROM Applicant where email = :1", email)
      for applicant in applicants:
        logging.error(applicant.applicant)
        self.response.out.write(applicant.applicant)
      self.response.out.write('</applicants>')         
     
    if action == 'getharvests':  
      logging.error("get harvests.....")
      email = self.request.get('email')
      self.response.out.write('<harvests>')
      harvests = db.GqlQuery("SELECT * FROM Harvest where email = :1", email)
      for harvest in harvests:
        logging.error(harvest.harvest)
        self.response.out.write(harvest.harvest)
      self.response.out.write('</harvests>')         
 
    if action == 'getfertilizers':  
      logging.error("get fertilizers.....")
      email = self.request.get('email')
      self.response.out.write('<fertilizers>')
      fertilizers = db.GqlQuery("SELECT * FROM Fertilize where email = :1", email)
      for fertilize in fertilizers:
        logging.error(fertilize.fertilize)
        self.response.out.write(fertilize.fertilize)
      self.response.out.write('</fertilizers>') 
      
    if action == 'getstorages':  
      logging.error("get storages.....")
      email = self.request.get('email')
      self.response.out.write('<storages>')
      storages = db.GqlQuery("SELECT * FROM Storage where email = :1", email)
      for storage in storages:
        logging.error(storage.storage)
        self.response.out.write(storage.storage)
      self.response.out.write('</storages>')
      
    if action == 'getsales':  
      logging.error("get sales.....")
      email = self.request.get('email')
      self.response.out.write('<sales>')
      sales = db.GqlQuery("SELECT * FROM Sale where email = :1", email)
      for sale in sales:
        logging.error(sale.sale)
        self.response.out.write(sale.sale)
      self.response.out.write('</sales>')        
 
      
    if action == 'getseeds':
      logging.error("get seeds.....")
      email = self.request.get('email')
      self.response.out.write('<seeds>')      
      seeds = db.GqlQuery("SELECT * FROM Seed where email = :1", email)
      for seed in seeds:
        logging.error(seed.seed)
        self.response.out.write(seed.seed)
      self.response.out.write('</seeds>') 
 
    if action == 'gettreatments':
      logging.error("get treatments.....")
      email = self.request.get('email')
      self.response.out.write('<treatments>')      
      treatments = db.GqlQuery("SELECT * FROM Treatment where email = :1", email)
      for treatment in treatments:
        logging.error(treatment.treatment)
        self.response.out.write(treatment.treatment)
      self.response.out.write('</treatments>') 
           
      
    if action == 'getpayments':  
      logging.error("get payments.....")
      email = self.request.get('email')
      self.response.out.write('<payments>')
      payments = db.GqlQuery("SELECT * FROM Payment where email = :1", email)
      for payment in payments:
        logging.error(payment.payment)
        self.response.out.write(payment.payment)
      self.response.out.write('</payments>') 

    if action == 'getreceipts':  
      logging.error("get receipts.....")
      email = self.request.get('email')
      self.response.out.write('<receipts>')
      receipts = db.GqlQuery("SELECT * FROM Receipt where email = :1", email)
      for receipt in receipts:
        logging.error(receipt.receipt)
        self.response.out.write(receipt.receipt)
      self.response.out.write('</receipts>') 
      
    if action == 'getchemicals':  
      logging.error("get chemicals.....")
      email = self.request.get('email')
      self.response.out.write('<chemicals>')
      chemicals = db.GqlQuery("SELECT * FROM Chemical where email = :1", email)
      for chemical in chemicals:
        logging.error(chemical.chemical)
        self.response.out.write(chemical.chemical)
      self.response.out.write('</chemicals>')        
      
    if action == 'getfields':
      email = self.request.get('email')
      logging.error("get fields.....")
      fields = db.GqlQuery("SELECT * FROM Field where farm_creator_email = :1", email )
      self.response.out.write('<fields>')
      
      for field in fields:
        logging.error(field.name)
        self.response.out.write('<field name="')
        self.response.out.write(field.name)
        self.response.out.write('" township="')
        self.response.out.write(field.township)
        self.response.out.write('" north="')
        self.response.out.write(field.north)
        self.response.out.write('" west="')
        self.response.out.write(field.west)
        self.response.out.write('" section="')
        self.response.out.write(field.section)
        self.response.out.write('" corn_yield="')
        self.response.out.write(field.corn_yield)
        self.response.out.write('" wheat_yield="')
        self.response.out.write(field.wheat_yield)
        self.response.out.write('" soybean_yield="')
        self.response.out.write(field.soybean_yield)
        self.response.out.write('" acreage="')
        self.response.out.write(field.acreage)
        self.response.out.write('" farm="')
        self.response.out.write(field.farm)
        self.response.out.write('">')
        self.response.out.write(field.polygon)
        self.response.out.write('</field>')
      self.response.out.write('</fields>')
    if action == 'getuser2':   
      logging.error("changing township numbers")
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Garfield")
      for township in townships:
        logging.error("_____________________")
        logging.error(township.north)
        logging.error(township.west)
        logging.error("_____________________")
        township.north="148"
        township.west="54"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Morgan")
      for township in townships:
        township.north="148"
        township.west="53"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Buxton")
      for township in townships:
        township.north="148"
        township.west="52"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Stavenger")
      for township in townships:
        township.north="148"
        township.west="51"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Belmont")
      for township in townships:
        township.north="148"
        township.west="50"
        township.put()
        
        
        
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Viking")
      for township in townships:
        township.north="147"
        township.west="54"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Lindaas")
      for township in townships:
        township.north="147"
        township.west="53"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Wold")
      for township in townships:
        township.north="147"
        township.west="52"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Ervin")
      for township in townships:
        township.north="147"
        township.west="51"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Bingham")
      for township in townships:
        township.north="147"
        township.west="50"
        township.put()
      
        
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Roseville")
      for township in townships:
        township.north="146"
        township.west="54"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Mayville")
      for township in townships:
        township.north="146"
        township.west="53"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Norway")
      for township in townships:
        township.north="146"
        township.west="52"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "El Dorado")
      for township in townships:
        township.north="146"
        township.west="51"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Caledonia")
      for township in townships:
        township.north="146"
        township.west="50"
        township.put()
        
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Norman")
      for township in townships:
        township.north="145"
        township.west="54"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Blanchard")
      for township in townships:
        township.north="145"
        township.west="53"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Bloomfield")
      for township in townships:
        township.north="145"
        township.west="52"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Hillsboro")
      for township in townships:
        township.north="145"
        township.west="51"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Herberg")
      for township in townships:
        township.north="145"
        township.west="50"
        township.put()
        
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Galesberg")
      for township in townships:
        township.north="144"
        township.west="54"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Greenfield")
      for township in townships:
        township.north="144"
        township.west="53"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Bohnsack")
      for township in townships:
        township.north="144"
        township.west="52"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Kelso")
      for township in townships:
        township.north="144"
        township.west="51"
        township.put()
      townships = db.GqlQuery("SELECT * FROM Township where name = :1", "Elm river")
      for township in townships:
        township.north="144"
        township.west="50"
        township.put()   
      
        
      fields = db.GqlQuery("SELECT * FROM Field")  
      for field in fields:
        logging.error("_____________________")
        logging.error(field.name)
        logging.error(field.township)
        logging.error(field.north)
        logging.error(field.west)
        logging.error("_____________________")
        townshipName=field.township
        townships = db.GqlQuery("SELECT * FROM Township where name =:1", townshipName)  
        for township in townships:
          logging.error("SETTING FIELD NUMS_________________")
          logging.error(field.name)
          logging.error(field.north)
          logging.error(field.west)
          logging.error("_____________________")
          field.north = township.north
          field.west = township.west
          field.put()
        
    if action == 'getuser':
      logging.error("getting users farms .....")
      
      
      email = self.request.get('email')
      logging.error(email)
      farms = db.GqlQuery("SELECT * FROM Farm where farm_creator_email = :1", email)
      self.response.out.write('<data>')      
      self.response.out.write('<farms>')
      for farm in farms:
        self.response.out.write('<farm number="')
        self.response.out.write(farm.number)
        self.response.out.write('" key="')
        self.response.out.write(farm.key())
        self.response.out.write('" creator_email="')
        self.response.out.write(farm.farm_creator_email)
        self.response.out.write('">')
        fields = db.GqlQuery("SELECT * FROM Field where farm_creator_email = :1 and farm = :2", "*****@*****.**", farm.number )
        for field in fields:
          logging.error("___________________________________")
          logging.error(field.name)
          logging.error(field.acreage)
          logging.error("___________________________________")
          self.response.out.write('<field name="')
          self.response.out.write(field.name)
          self.response.out.write('" township="')
          self.response.out.write(field.township)
          self.response.out.write('" north="')
          self.response.out.write(field.north)
          self.response.out.write('" west="')
          self.response.out.write(field.west)
          self.response.out.write('" section="')
          self.response.out.write(field.section)
          self.response.out.write('" acreage="')
          self.response.out.write(field.acreage)
          self.response.out.write('" farm="')
          self.response.out.write(farm.number)
          
          
          self.response.out.write('">')
          self.response.out.write(field.polygon)
          ingredients = db.GqlQuery("SELECT * FROM Ingredient where field = :1", field.name )
          
          self.response.out.write('<ingredients>')
          for ingredient in ingredients:
            
            self.response.out.write('<ingredient application="')
            self.response.out.write(ingredient.application)
            self.response.out.write('" field="')
            self.response.out.write(ingredient.field)
            self.response.out.write('" rate="')
            self.response.out.write(ingredient.rate)
            self.response.out.write('" type="')
            self.response.out.write(ingredient.ing_type)
            self.response.out.write('" crop_type="')
            logging.error("((((((((((((((((((((((((((((((((((")
            logging.error(ingredient.crop_type)
            logging.error(ingredient.ing_type)
            self.response.out.write(ingredient.crop_type)
            self.response.out.write('" product="')
            self.response.out.write(ingredient.product)
            self.response.out.write('" acres="')
            self.response.out.write(ingredient.acres)
            self.response.out.write('" acre_units="')
            self.response.out.write(ingredient.acre_units)
            self.response.out.write('" cost="')
            self.response.out.write(ingredient.cost)
            self.response.out.write('" cost_units="')
            self.response.out.write(ingredient.cost_units)
            self.response.out.write('" />')
          self.response.out.write('</ingredients>')  
          self.response.out.write('</field>')
          
          
          sectionResult = db.GqlQuery("SELECT * FROM Section where township = :1 and number = :2", field.township, field.section )
          self.response.out.write('<section township="')
          self.response.out.write(field.township)
          self.response.out.write('" section="')          
          self.response.out.write(field.section)
          self.response.out.write('">')
          self.response.out.write('</section>')

          appFields = db.GqlQuery("SELECT * FROM AppField where field = :1", field.name )
          
       
        self.response.out.write('</farm>')
       
       
          
        
      self.response.out.write('</farms>') 
      
      self.response.out.write('<purchases>')
      purchases = db.GqlQuery("SELECT * FROM Purchase where email = :1", email)
      for purchase in purchases:
        logging.error(purchase.purchase)
        self.response.out.write(purchase.purchase)
      self.response.out.write('</purchases>')
        
      
      
     
      self.response.out.write('</data>')    
      logging.error("::::::::::::::::::::::::::::::::::::::") 
 
    if action == 'getSections':
      logging.error("get sections .....")
      townshipName = self.request.get('parameter')
      sections = db.GqlQuery("SELECT * FROM Section where township = :1", townshipName)
      self.response.out.write('<sections>')
      for section in sections:
        self.response.out.write("<section number='")
        self.response.out.write(section.number)
        self.response.out.write("' >")
        logging.error("asdasdasdasdasd")
        logging.error("asdasdasdasdasd")
        logging.error(section.polygon)
        self.response.out.write(section.polygon)
        self.response.ouct.write("</section>")
      self.response.out.write("</sections>")
    if action == 'getsection':
      logging.error("getsection.......")
      number = self.request.get('number')
      north = self.request.get('north')
      west = self.request.get('west')
      townships = db.GqlQuery("SELECT * FROM Township where north = :1 and west = :2 ", north, west)
      for township in townships:
        name = township.name
        logging.error("township name::::::::")
        logging.error(name)
        logging.error(number)
        sections = db.GqlQuery("SELECT * FROM Section where township = :1 and number = :2", name, number)
        for section in sections:
          logging.error(section.polygon)
        
          self.response.out.write('<section number="')
          self.response.out.write(section.number)
          self.response.out.write('">')
          self.response.out.write(section.polygon)
          self.response.out.write('</section>')  
    
      
    self.response.CacheControl = "no-cache"
    self.response.Expires = -1
    self.response.headers['Pragma'] = "no-cache"
    self.response.headers['Content-Type'] = "application/xml"
    

    
    if len(action) == 0:
      self.redirect("html/cropusoft_3.htm")
Exemplo n.º 22
0
 def get(self):
     users = UserModel.all().order('processed')
     bucket = users.count() / 3 + 1
     for user in users.fetch(bucket):
         user.queue_to_twit()
Exemplo n.º 23
0
    def get(self):
        args = self.args_to_dict()
    
        s = {}
        self.session = sessions.Session()
        if self.session['openid_stuff']:
            try:
                s = pickle.loads(str(self.session['openid_stuff']))
            except:
                pass
    
        consumer = Consumer(s, store.DatastoreStore())
        if not consumer:
            return
        fetchers.setDefaultFetcher(fetcher.UrlfetchFetcher())
        auth_response = consumer.complete(args, self.request.uri)
        if auth_response.status == 'success':
            openid = auth_response.getDisplayIdentifier()

            #when user add openid from profile setting, just return status.
            if self.session['openid_userid']:
                user = User.get(self.session['openid_userid'])
                if user:
                    users = User.all().filter('openids', openid)
                    if users.count() == 0:
                        user.openids += [db.Category(openid.strip().encode('utf8'))]
                        user.put()
                    else:
                        msg = "OpenID had already been attached to another user."
                        if users.count()==1 and users.get() == user:
                            msg = "OpenID had already been attached to you."
                        self.generate('user/user_profile_openid_verify.html',
                                      {"status":"fail","msg":msg})
                        return
                self.generate('user/user_profile_openid_verify.html',
                              {"status":"success","msg":"Attach OpenID to user successfully."})
                return

            sreg_data = sreg.SRegResponse.fromSuccessResponse(auth_response)
            users = User.all().filter('openids', openid)
            if users.count() == 0:
                user = User()
                user.openids = [db.Category(openid.strip().encode('utf8'))]
                if sreg_data:
                    user.username = sreg_data["nickname"]
                    user.fullname = sreg_data["fullname"]
                    user.country = sreg_data["country"]
                    user.birthday = datetime.datetime.strptime(sreg_data["dob"], '%Y-%m-%d')
                    user.gender = sreg_data["gender"]
                    user.language = sreg_data["language"]
                    user.postcode = sreg_data["postcode"]
                    #user.email = sreg_data["email"]
                else:
                    user.username = openid
                user.put()
                self.session.login_user(user)
                self.redirect('/user')
                return
            else:
                user = users[0]

            self.session.login_user(user)
            self.redirect('/')
            return
        else:
            #when user add openid from profile setting, just return status.
            if self.session['openid_userid']:
                self.generate('user/user_profile_openid_verify.html',
                              {"status":"fail","msg":"Attach OpenID to user unsuccessfully: OpenID verification failed."})
                return
            self.show_main_page('OpenID verification failed.')
Exemplo n.º 24
0
    def initial_request(self):
        
        first_name = cgi.escape(self.request.get('first-name'))
        last_name = cgi.escape(self.request.get('last-name'))
        phone = cgi.escape(self.request.get('phone'))
        company = cgi.escape(self.request.get('company'))
        email = cgi.escape(self.request.get('email'))
        challenge = cgi.escape(self.request.get('recaptcha_challenge_field'))
        response  = cgi.escape(self.request.get('recaptcha_response_field'))
        remoteip  = os.environ['REMOTE_ADDR']
        
        params={
            "first_name": first_name,
            "last_name": last_name,
            "phone": phone,
            "company": company,
            "email": email,
        }
        
        # Do a bunch of form verification
        
        cResponse = captcha.submit(challenge, response, RECAPTCHA_PRIVATE, remoteip)

        error = False

        if len(first_name) > 100 or " " in first_name:
            params["name_error"] = "Invalid name."
            error = True

        if not re.match(email_re, email):
            params["email_error"] = "That email address is not valid.  Nice try Adrien!"
            error = True
            
        # check user doesn't already have a request
        users = db.GqlQuery("SELECT * FROM InstanceUser WHERE email = :email", email=email)
        if users.count() > 0:
            params["email_error"] = "That email address has already been used.  Sorry!"
            error = True

        if not cResponse.is_valid:
            self.show_index(c_error=cResponse.error_code, params=params)
            return
            
        if error:
            self.show_index(params=params)
            return
        
        # Now bung a record in out datastore for later perusal, after we 
        # confirm email if accurate

        token = hashlib.sha1('%s$%s' % (email, SALT)).hexdigest()
        
        # Store email, token
        user = InstanceUser(first_name=first_name, last_name=last_name,
            company=company, phone=phone, email=email, token=token);
        user.put()
        
        # Send email
        mail.send_mail(sender="Acunu.com Downloads <*****@*****.**>",
                      to=email,
                      subject="Your Acunu trial instance",
                      body= EMAIL % {"first_name": first_name, "token": token, "domain_name": self.request.host_url})

        self.message("Please check your email for further instructions")