Beispiel #1
0
  def login(self):

    body = json.JSONDecoder().decode( cherrypy.request.body.read() )
    
    check = Utils.arg_check(body, ["username","password"])
    if (check[0]):
		return check[1]

    matchingUsers = Utils.query("SELECT * FROM Users u WHERE u.username=%s AND u.password=SHA1(CONCAT(%s, u.salt))", (body["username"], body["password"]))
    
    if(len(matchingUsers) == 0):
      return json.JSONEncoder().encode({
        "status" : Utils.status(324,"Could not locate user")
      })
    elif (len(matchingUsers) == 1):
      sessionID = str(uuid.uuid4())
      Utils.execute("INSERT INTO User_Sessions(user_id, session_token) VALUES(%s, %s)",(matchingUsers[0]["user_id"], sessionID))
      
      return json.JSONEncoder().encode({
        "token": sessionID,
        "status" : Utils.status(0, "OK")
      })
    else:
      return json.JSONEncoder().encode({
        "status" : Utils.status(323,"The system is in an invalid state.")
      })
Beispiel #2
0
 def setBidPlayer(self, playerName, teamName):
   Utils.execute("""Truncate bid;
                     SET @pid = (SELECT pid from player WHERE player_name = %s);
                     SET @tid = (SELECT team_id from team WHERE teamname = %s);
                     
                     Insert into bid
                     SET bid = 0, pid = @pid, team_id = @tid;""",(playerName, teamName))
   return "OK"
Beispiel #3
0
	def add(self):
		body = json.loads( cherrypy.request.body.read() )
    
		check = Utils.arg_check(body, ['token', 'latitude', 'longitude'])	
		if (check[0]):
			return check[1]
		
		user_check = Utils.validate_user(body["token"])
		if(user_check[0]):
			return user_check[1]
		user_id = user_check[1]
		
		base = "http://maps.googleapis.com/maps/api/geocode/json?"
		params = "latlng={lat},{lon}&sensor={sen}".format(
			lat=body['latitude'],
			lon=body['longitude'],
			sen=True
		)
		url = "{base}{params}".format(base=base, params=params)
		response = requests.get(url)
		
		if (response):
			content = response.json()
			if (content and content['results'] and content['results'][0] and content['results'][0]['formatted_address']):
				savedLocations = Utils.query("""SELECT * FROM Locations WHERE address = %s""",
							    (content['results'][0]['formatted_address']))
				#print savedLocations
				if (len(savedLocations) == 1):
					location_id = savedLocations[0]["location_id"]
				elif (len(savedLocations) > 1):
					return json.JSONEncoder().encode( Utils.status_more( 34, "Inconsistet database" ) )
				else:
					location_id  = Utils.execute_id("""INSERT INTO Locations(latitude, longitude, address, place) 
							 VALUES(%s, %s, %s, %s)""", 
							(body["latitude"], body["longitude"], content['results'][0]['formatted_address'], "I don't know"))
				if (location_id  != -1):
					previousUserLocation = Utils.query("""SELECT location_id FROM Users_Locations 
													WHERE user_id = %s 
													ORDER BY time DESC LIMIT 1""", (user_id))
					is_route = False
					if previousUserLocation:
						previousLocation = Utils.query("""SELECT * FROM Locations WHERE location_id = %s""", (previousUserLocation[0]["location_id"]))
					
						if len(previousLocation) == 1 and self.checkDistance(previousLocation[0]["latitude"], previousLocation[0]["longitude"],body["latitude"],body["longitude"]) == 1: 
							is_route = True
					Utils.execute("""INSERT INTO Users_Locations(user_id, location_id, time, is_route) 
							VALUES(%s, %s, %s, %s)""",
							(user_id, location_id, datetime.now(), is_route))
					return json.JSONEncoder().encode( Utils.status_more( 0, "OK" ) )
			return json.JSONEncoder().encode( Utils.status_more( 35, "Could not save to database" ) )

		return json.JSONEncoder().encode( Utils.status_more( 33, "Could not retrieve location information" ) )
Beispiel #4
0
def add_data2(o,occurances):
  location_id = Utils.execute_id("""INSERT INTO Locations(address) VALUES('The place I am')""",())
  user_id = Utils.query("""SELECT user_id
                            FROM User_Sessions
                            WHERE session_token = %s;""", (o.loginResult['token']))

  event_id= Utils.execute_id("""INSERT INTO Events(event_type,user_id,name,location_id,locked,deleted)
                                VALUES ('cycle',%s,'test cycle',%s,TRUE,FALSE);""",
                                (user_id[0]["user_id"], location_id))

  Utils.execute("""INSERT INTO Cyclical_Events(event_id, cycle_type, occurances)
                          VALUES(%s,'weekly',%s)""", (event_id, json.JSONEncoder().encode(occurances)))

  return {"location_id" : location_id, "event_id" : event_id }
Beispiel #5
0
  def logout(self):
    body = json.loads( cherrypy.request.body.read() )

    count = Utils.execute("DELETE FROM User_Session WHERE session_token = %s",(body["token"]))
    if(count > 0):
      return json.JSONEncoder().encode({
        "status" : Utils.status(0, "OK")
      })
    else:
      return json.JSONEncoder().encode({
        "status" : Utils.status(125, "Could not locate user with provided token")
      })
Beispiel #6
0
  def accept(self): 
    body = json.JSONDecoder().decode( cherrypy.request.body.read() )
    check = Utils.arg_check(body, ["token","buddy_id"])

    if (check[0]): 
      return check[1]

    # Find the user ID of the person making the request.
    user_check = Utils.validate_user(body["token"])
    if(user_check[0]):
      return user_check[1]
    user_id = user_check[1]

    try:
        Utils.execute("""UPDATE Buddies
                         SET approved=1
                         WHERE requester_id=%s AND requestee_id=%s""",
                         (body["buddy_id"],user_id))
    except Exception:
        return json.JSONEncoder().encode({"status": Utils.status(3981,"Could not approve buddy")})

    return json.JSONEncoder().encode(Utils.status_more(0, "OK"))
Beispiel #7
0
 def deleteAccount(self):
   body = json.loads( cherrypy.request.body.read() )
   
   count = Utils.execute("DELETE u FROM User_Session us LEFT JOIN User u ON us.user_id = u.user_id WHERE username = %s and password = %s",(body["username"], body["password"]))
   
   if(count > 0):
     return json.JSONEncoder().encode({
       "status" : Utils.status(0, "OK")
     })
   else:
     return json.JSONEncoder().encode({
       "status" : Utils.status(433, "Could not delete user account.")
     })
Beispiel #8
0
  def register(self):
    body = json.loads( cherrypy.request.body.read() )

    count = Utils.execute("INSERT INTO User (username, password, email, salt) VALUES (%s, %s, %s, 'ABCDEFG')", (body['username'], body['password'], body['email']) )

    if(count == 1):
      return json.JSONEncoder().encode({
        "status" : Utils.status(0, "OK")
      })
    else:
      return json.JSONEncoder().encode({
        "status" : Utils.status(431, "Could not register user account.")
      })
Beispiel #9
0
  def request(self): 
    body = json.JSONDecoder().decode( cherrypy.request.body.read() )
    check = Utils.arg_check(body, ["token","buddy"])

    if (check[0]): 
      return check[1]

    # Find the user ID of the person making the request.
    user_check = Utils.validate_user(body["token"])
    if(user_check[0]):
      return user_check[1]
    user_id = user_check[1]

    matching_users = Utils.query("""SELECT * FROM Users WHERE username=%s OR email=%s""", 
              (body["buddy"],body["buddy"]))

    if len(matching_users) == 0:
      return json.JSONEncoder().encode( Utils.status_more( 112, "Could not locate user" ) )
    
    matching_user = matching_users[0]
    
    if matching_user["user_id"] == user_id:
      return json.JSONEncoder().encode( Utils.status_more( 115, "Cannot be buddies with yourself" ) )

    in_buddies = Utils.query("""SELECT * FROM Buddies WHERE (requester_id = %s AND requestee_id = %s) OR (requester_id = %s AND requestee_id = %s)""", (user_id,matching_user["user_id"],matching_user["user_id"],user_id))

    if any(in_buddies):
      return json.JSONEncoder().encode( Utils.status_more( 115, "Cannot request buddy when you are already buddies or there is already a pending request between you." ) )

    try:
        Utils.execute("""INSERT INTO Buddies(requester_id, requestee_id, approved) VALUE(%s,%s,0)""",
          (user_id,matching_user["user_id"]))
    except Exception:
        return json.JSONEncoder().encode({"status": Utils.status(3981,"Could not request buddy")})

    return json.JSONEncoder().encode(Utils.status_more(0, "OK"))
Beispiel #10
0
  def deleteAccount(self):

    body = json.JSONDecoder().decode( cherrypy.request.body.read() )
    check = Utils.arg_check(body, ["username","password"])
    if (check[0]):
            return check[1]
    
    count = Utils.execute("DELETE u FROM Users u WHERE u.username = %s and u.password = SHA1(CONCAT(%s, u.salt))",(body["username"], body["password"]))
    
    if(count > 0):
      return json.JSONEncoder().encode({
        "status" : Utils.status(0, "OK")
      })
    else:
      return json.JSONEncoder().encode({
        "status" : Utils.status(433, "Could not delete user account.")
      })
Beispiel #11
0
 def register(self):
   body = json.JSONDecoder().decode( cherrypy.request.body.read() )
   
   check = Utils.arg_check(body, ["username","password", "email"])
   if (check[0]):
           return check[1]
   
   
   password_hash = str(uuid.uuid4())
   count = Utils.execute("INSERT INTO Users (username, password, email, salt) VALUES (%s, SHA1(CONCAT(%s, %s)), %s, %s)", (body['username'], body['password'], password_hash, body['email'], password_hash) )
   
   if(count == 1):
     return json.JSONEncoder().encode({
       "status" : Utils.status(0, "OK")
     })
   else:
     return json.JSONEncoder().encode({
       "status" : Utils.status(431, "Could not register user account.")
     })
Beispiel #12
0
	def add(self,place,time):
		if (place != -1):
			Utils.execute("""INSERT INTO Users_Locations(user_id, location_id, time) 
								VALUES(%s, %s, %s)""", (str(self.user_id), str(place), time))
Beispiel #13
0
 def takeBreak(self):
   Utils.execute("""Truncate bid;""",())
   return "OK"
Beispiel #14
0
 def setBidAmount(self, bid):
   Utils.execute("""UPDATE bid
                     SET bid =%s""", (bid))
   return "OK"