Advertisement
Guest User

login

a guest
Jun 10th, 2017
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 23.85 KB | None | 0 0
  1. import urllib
  2. import urllib2
  3. import json
  4. import cherrypy
  5. import hashlib
  6. import socket
  7.  
  8. import profile_db
  9. import messages_db
  10. import users_db
  11. import blacklist_db
  12.  
  13. import time
  14. import sys
  15.  
  16. import base64
  17.  
  18. import threading
  19.  
  20. from json import load
  21. from urllib2 import urlopen
  22.  
  23. import atexit
  24.  
  25. # Requires:  CherryPy 3.2.2  (www.cherrypy.org)
  26. #            Python  (We use 2.7)
  27.  
  28. # The address we listen for connections on
  29. listen_ip = "0.0.0.0"
  30. listen_port = 10001
  31.    
  32.  
  33. class MainApp(object):
  34.  
  35.     #CherryPy Configuration
  36.     _cp_config = {'tools.encode.on': True,
  37.                   'tools.encode.encoding': 'utf-8',
  38.                   'tools.sessions.on' : 'True',
  39.                  }                
  40.  
  41.     login_parameters = {'username' : None, 'password' : None , 'location' : None, 'ip' : None, 'port' : None}
  42.    
  43.     sessionValid = False
  44.      
  45.    
  46.     # If they try somewhere we don't know, catch it here and send them to the right place.
  47.     @cherrypy.expose
  48.     def default(self, *args, **kwargs):
  49.         """The default page, given when we don't recognise where the request is for."""
  50.         Page = "The page that you are trying to access does not exist - 404 Error."
  51.         cherrypy.response.status = 404
  52.         return Page
  53.  
  54.     # HOME PAGE
  55.     @cherrypy.expose
  56.     def index(self):
  57.         Page = "Welcome!<br/>"
  58.        
  59.         try:
  60.        
  61.             Page += '<form action="/showOnlineUsers" method="get" enctype="multipart/form-data">'
  62.             Page += "Hello " + cherrypy.session['username'] + "!<br/>"
  63.             Page += "You have successfully logged in!<br/>"
  64.             Page += "Click here to view the online users"
  65.             Page += '<input type="submit" value="Online Users"/></form>'
  66.            
  67.             Page += '<form action="/checkMessages" method="get" enctype="multipart/form-data">'
  68.             Page += '<input type="submit" value="View Received Messages"/></form>'
  69.            
  70.             Page += '<form action="/sentMessages" method="get" enctype="multipart/form-data">'
  71.             Page += '<input type="submit" value="View Sent Messages"/></form>'
  72.            
  73.             Page += '<form action="/viewProfile" method="get" enctype="multipart/form-data">'
  74.             Page += '<input type="submit" value="View User Profile"/></form> </br>'
  75.            
  76.             Page += '</br> View a Profile: </br>'
  77.            
  78.             Page += '<form action="/getOtherProfile" method="get" enctype="multipart/form-data">'
  79.             Page += 'User: <input type="text" name="targetUser" required/><br/>'
  80.             Page += '<input type="submit" value="View"/></form></br>'
  81.            
  82.             Page += '<form action="/sendFile" method="post" enctype="multipart/form-data">'
  83.             Page += 'Send a file: </br>'
  84.             Page += 'To User: <input type="text" name="targetUser" required/><br/>'
  85.             Page += '<input type="file" name ="fileToSend" value="Upload File" required/>'
  86.             Page += '<input type="submit" value="Send"/></form></br>'
  87.            
  88.            
  89.             Page += '<form action="/listUsers" method="get" enctype="multipart/form-data">'
  90.             Page += '<input type="submit" value="View All Users"/></form></br>'
  91.            
  92.            
  93.             Page += '<form action="/logoff" method="get" enctype="multipart/form-data">'
  94.             Page += '<input type="submit" value="Logout"/></form>'
  95.            
  96.         except KeyError: #There is no username
  97.            
  98.             Page += "Click here to <a href='login'>login</a>."
  99.         return Page
  100.        
  101.     @cherrypy.expose
  102.     def login(self):
  103.         Page = '<form action="/signin" method="post" enctype="multipart/form-data">'
  104.         Page += 'Username: <input type="text" name="username" required/><br/>'
  105.         Page += 'Password: <input type="password" name="password" required/></br>'
  106.         Page += 'Location: <input type="text" name="userLocation"/>'
  107.         Page += '</br> (Location:    0 - University Desktop;    1 - University Wireless;    2 - External)</br> '  
  108.         Page += '<input type="submit" value="Login"/></form>'
  109.         return Page
  110.  
  111.     @cherrypy.expose
  112.     def loginFailed(self):
  113.         Page = '<form action="/signin" method="post" enctype="multipart/form-data">'        
  114.     Page += 'Username: <input type="text" name="username" required/><br/>'
  115.         Page += 'Password: <input type= "password" name="password" required/></br>'
  116.         Page += 'Location: <input type="text" name="userLocation"/>'
  117.         Page += '</br> (Location:    0 - University Desktop;    1 - University Wireless;    2 - External)</br> '  
  118.         Page += '<input type="submit" value="Login"/></form></br>'
  119.         Page += 'Failed to log in. Please try again.</br>'
  120.        
  121.         return Page
  122.  
  123.     # Exception Handling
  124.     @cherrypy.expose
  125.     def actionFailed(self):
  126.         Page = "The action you are trying to do is not valid, or you are currently not logged in to the application or do not have a valid session.</br>"
  127.         Page += "Click <a href = 'index'>here</a> to go back to the main menu."
  128.         return Page
  129.    
  130.     @cherrypy.expose
  131.     def userOffline(self):
  132.         Page = "The user that you are trying to reach is currently offline or is currently unavailable</br>"
  133.         Page += "Click <a href = 'index'>here</a> to go back to the main menu."
  134.        
  135.         return Page
  136.        
  137.     # Online Users
  138.     @cherrypy.expose
  139.     def showOnlineUsers(self):
  140.        
  141.         getList()
  142.        
  143.         Page = "<h1><b>List of People Online:</b></h1> </br>"
  144.         Page += users_db.dispOnlineUsers()
  145.         Page += '<meta http-equiv="refresh" content="10" >'
  146.         Page += '<form action="/sendMessageToUser" method="get" enctype="multipart/form-data">'
  147.         Page += '</br> Click this button to send a message to a user '
  148.         Page += '<input type="submit" value="Send Message"/></form> </br>'
  149.        
  150.         Page += "Click <a href = 'index'>here</a> to go back to the main menu"
  151.        
  152.         return Page
  153.    
  154.    
  155.     @cherrypy.expose
  156.     def listAPI(self):
  157.    
  158.     Page = "Available APIs: "
  159.     Page += "/ping "
  160.     Page += "/listAPI "
  161.     Page += "/receiveMessage [sender] [destination] [message] [stamp] "
  162.     Page += "/getProfile [profile_username] [sender] "
  163.     Page += "/receiveFile [sender] [destination] [file] [filename] [content_type] [stamp] "
  164.     Page += "/getStatus [profile_username] "
  165.  
  166.     return Page
  167.    
  168.    
  169.    
  170.     # ------------- RECEIVING/SENDING MESSAGES ------------------ #
  171.     @cherrypy.expose
  172.     def checkMessages(self):
  173.                
  174.         Page = "<h1>These are your messages:</h1> </br>"      
  175.         Page += messages_db.displayMessages(cherrypy.session['username'],"RECEIVED")
  176.         Page += '<meta http-equiv="refresh" content="5" >'
  177.         Page += "<h3></br>Click <a href = 'index'>here</a> to return to the main menu</h3>"  
  178.        
  179.         return Page
  180.    
  181.     @cherrypy.expose
  182.     def sentMessages(self):
  183.                
  184.         Page = "<h1>Sent Messages:</h1> </br>"      
  185.         Page += messages_db.displayMessages(cherrypy.session['username'],"SENT")
  186.         Page += '<meta http-equiv="refresh" content="5" >'
  187.         Page += "<h3></br>Click <a href = 'index'>here</a> to return to the main menu</h3>"  
  188.        
  189.         return Page
  190.        
  191.     @cherrypy.expose  
  192.     def sendMessageToUser(self):
  193.    
  194.         Page = "Type your message below"
  195.         Page += '<form accept-charset="utf-8" action="/sendMessage" method="post" enctype="multipart/form-data">'
  196.         Page += '<input type="text" size="100" name="message" required/><br/>'
  197.         Page += 'Destination: <input type="text" size="20" name="destination" required/>'
  198.         Page += '<input type="submit" value="Send"/></form>'
  199.                                
  200.         return Page
  201.    
  202.     @cherrypy.expose
  203.     @cherrypy.tools.json_in()
  204.     def receiveMessage(self):
  205.            
  206.         try:
  207.         message_dict = cherrypy.request.json
  208.    
  209.         if (blacklist_db.checkList(message_dict["sender"])):
  210.            
  211.             messages_db.storeMessage(message_dict)
  212.             Page = '0' #If there are no errors
  213.            
  214.             print "MESSAGE RECEIVED"
  215.         else:
  216.             Page = '11'
  217.                
  218.         except:
  219.         Page = '4'    
  220.        
  221.         return Page
  222.            
  223.     @cherrypy.expose
  224.     def sendMessage(self,message,destination):
  225.                        
  226.        
  227.     pingUser = ping(destination)
  228.        
  229.     if (pingUser == "0"):          
  230.  
  231.         url = users_db.getURL(destination) + "/receiveMessage" 
  232.  
  233.         time_stamp = time.time()
  234.         payload = {'sender' : cherrypy.session['username'], 'destination' : destination, 'message' : message , 'stamp' : time_stamp }
  235.         data = json.dumps(payload)
  236.         req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
  237.        
  238.         try:
  239.             response = urllib2.urlopen(req, timeout = 1)
  240.        
  241.         except urllib2.URLError, e:
  242.             raise cherrypy.HTTPRedirect("/actionFailed")
  243.        
  244.         except urllib2.HTTPError:
  245.             raise cherrypy.HTTPRedirect("/actionFailed")
  246.        
  247.         # TODO: Check for responses
  248.         if (response.read() == "0"):
  249.             messages_db.storeMessage(payload)
  250.             raise cherrypy.HTTPRedirect("/showOnlineUsers")
  251.         else:
  252.  
  253.             print "MESSAGE DID NOT SEND"
  254.             raise cherrypy.HTTPRedirect("/actionFailed")
  255.        
  256.    
  257.     @cherrypy.expose
  258.     def ping(self,sender):
  259.                
  260.         return '0'
  261.    
  262.     # ----------------------END MESSAGES----------------------------------#
  263.    
  264.     #---------------------- PROFILE --------------------- #
  265.     @cherrypy.expose
  266.     def viewProfile(self):
  267.    
  268.         try:
  269.            
  270.             Page = profile_db.getProfile(cherrypy.session['username'],"view") + '</br>'
  271.  
  272.             Page += '<b>Status: </b>' + profile_db.getStatus(cherrypy.session['username'],"Profile")
  273.            
  274.             Page += '<form action="/updateProfilePrompt" method="get" enctype="multipart/form-data">'
  275.             Page += '<input type="submit" value="Update Profile"/></form> </br>'
  276.            
  277.             Page += '<form action="/updateStatus" method="post" enctype="multipart/form-data">'
  278.                 Page += 'Update Status: <input type="text" name="status"/>'
  279.                 Page += ' Valid Status = ["Online", "Idle", "Away", "Do Not Disturb", "Offline"] </br>'
  280.             Page += '<input type="submit" value="Update"/></form></br>'
  281.            
  282.             Page += '<form action="/index" method="get" enctype="multipart/form-data">'
  283.             Page += '<input type="submit" value="Main Menu"/></form> </br>'
  284.            
  285.         except:
  286.             raise cherrypy.HTTPRedirect('/actionFailed')
  287.            
  288.         return  Page
  289.        
  290.     @cherrypy.expose
  291.     def updateProfilePrompt(self):
  292.    
  293.         Page = '<form action="/updateProfile" method="post" enctype="multipart/form-data">'
  294.         Page += '<embed type="application/x-vlc-plugin" pluginspage="http://www.videolan.org" />'
  295.         Page += 'Full Name: <input type="text" name="FULLNAME" required/><br/>'
  296.         Page += 'Position: <input type="text" name="POSITION"/></br>'
  297.         Page += 'Description: <input type="text" name="DESCRIPTION"/></br>'
  298.         Page += 'Location: <input type="text" name="LOCATION"/></br>'
  299.         Page += 'New Profile Picture: <input type="text" name="IMAGE_URL"/> (please put a URL link)</br> '
  300.         Page += '<input type="submit" value="Update"/></form>'
  301.        
  302.         return Page
  303.    
  304.     @cherrypy.expose
  305.     def updateProfile(self,FULLNAME,POSITION,DESCRIPTION,LOCATION, IMAGE_URL):
  306.        
  307.         profile_db.updateProfileValues(cherrypy.session['username'],FULLNAME,POSITION,DESCRIPTION,LOCATION, IMAGE_URL)
  308.    
  309.         raise cherrypy.HTTPRedirect('/viewProfile')
  310.    
  311.        
  312.     @cherrypy.expose
  313.     @cherrypy.tools.json_in()
  314.     def getProfile(self):
  315.                            
  316.         input_data = cherrypy.request.json     
  317.        
  318.         if (blacklist_db.checkList(input_data["sender"])):
  319.        
  320.             output_dict = profile_db.getProfile(input_data["profile_username"],"dictionary")
  321.            
  322.            
  323.         else:
  324.        
  325.             output_dict = {'fullname' : 'BLOCKED', 'position' : 'BLOCKED' , 'description' : 'BLOCKED', 'location' : 'BLOCKED' , 'picture' : 'https://pbs.twimg.com/profile_images/600060188872155136/st4Sp6Aw.jpg'}
  326.        
  327.         data = json.dumps(output_dict)
  328.        
  329.         return data
  330.    
  331.    
  332.    
  333.     @cherrypy.expose
  334.     def getOtherProfile(self, targetUser):
  335.    
  336.         url = users_db.getURL(targetUser) + "/getProfile"
  337.        
  338.         payload = {'profile_username' : targetUser, 'sender' : cherrypy.session['username']}
  339.        
  340.         data = json.dumps(payload)
  341.     req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
  342.        
  343.         try:
  344.             response = urllib2.urlopen(req, timeout = 1)
  345.         except urllib2.URLError, e:
  346.             #raise MyException("There was an error: %r" % e)
  347.             raise cherrypy.HTTPRedirect('/actionFailed')
  348.            
  349.                
  350.        
  351.         input_dict = json.loads(response.read())
  352.            
  353.         profile_db.updateProfileValues(targetUser, input_dict["fullname"], input_dict["position"], input_dict["description"], input_dict["location"], input_dict["picture"])
  354.        
  355.         #TODO: Check for each parameter to 
  356.  
  357.     Page = '<h1>User: ' + targetUser + '</h1></br>'
  358.     Page += '<b>Full Name:</b> ' + input_dict["fullname"] + '</br>'
  359.     Page += '<b>Position:</b> ' + input_dict["position"] + '</br>'
  360.     Page += '<b>Description:</b> ' + input_dict["description"] + '</br>'
  361.     Page += '<b>Location:</b> ' + input_dict["location"] + '</br>'
  362.     Page += '<img src=' + "\"" + input_dict["picture"] + "\"" + "></br>"
  363.     Page += '<b>Status:</b> : '+ self.getPeerStatus(targetUser)
  364.     profile_db.updateStatus(targetUser,self.getPeerStatus(targetUser))
  365.                    
  366.     Page += '<form action="/index" method="post" enctype="multipart/form-data">'
  367.     Page += '<input type="submit" value="Main Menu"/></form>'      
  368.        
  369.        
  370.     return Page
  371.            
  372.    
  373.          
  374.    
  375.    
  376.     ### ---- STATUS --- ###
  377.     @cherrypy.expose
  378.     @cherrypy.tools.json_in()
  379.     def getStatus(self):
  380.    
  381.         input_data = cherrypy.request.json
  382.        
  383.         if (blacklist_db.checkList(input_data["sender"])):     
  384.        
  385.             output_dict = profile_db.getStatus(self.login_parameters['username'], "others")
  386.         else:
  387.            
  388.             output_dict = {'status': 'Offline' }
  389.        
  390.         data = json.dumps(output_dict)
  391.        
  392.         return data
  393.        
  394.     @cherrypy.expose
  395.     def getPeerStatus(self,targetUser):
  396.    
  397.         pingUser = ping(targetUser)
  398.                
  399.         payload = {'profile_username' : targetUser}
  400.        
  401.         url = users_db.getURL(targetUser) + "/getStatus"
  402.        
  403.         data = json.dumps(payload)
  404.    
  405.     req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
  406.    
  407.     try:
  408.        
  409.         response = urllib2.urlopen(req)
  410.    
  411.         output = json.loads(response.read())
  412.     except:
  413.         output = {'status' : 'Offline'}  
  414.    
  415.         return output['status']
  416.    
  417.  
  418.     @cherrypy.expose
  419.     def updateStatus(self,status):
  420.        
  421.         validStatus = ["Online", "Idle", "Away", "Do Not Disturb", "Offline"]
  422.        
  423.         if status not in validStatus:
  424.             raise cherrypy.HTTPRedirect('/actionFailed') #TODO: Must say invalid status
  425.         else:
  426.             profile_db.updateStatus(cherrypy.session['username'],status)
  427.             raise cherrypy.HTTPRedirect('/viewProfile')
  428.        
  429.         return status
  430.    
  431.    
  432.     # -----------------END PROFILE---------------------------#     
  433.    
  434.     # ----------------- FILES -------------------------------#
  435.     @cherrypy.expose
  436.     def sendFile(self,fileToSend,targetUser):  
  437.        
  438.         userPing = ping(targetUser)
  439.        
  440.     file_read = fileToSend.file.read()
  441.    
  442.     fileSize = len (file_read)
  443.    
  444.     if fileSize > 5000000:
  445.                  raise cherrypy.HTTPRedirect('/actionFailed')
  446.                  
  447.    
  448.     if (userPing == "0"):  
  449.        
  450.         file_64_encode = base64.encodestring(file_read)
  451.    
  452.         url = users_db.getURL(targetUser) + "/receiveFile"
  453.    
  454.         filenameList = (fileToSend.filename).split(".")
  455.    
  456.         filename = fileToSend.filename
  457.    
  458.         content_type = "." + filenameList[1]
  459.        
  460.        
  461.             payload = {'sender' : cherrypy.session['username'], 'destination' : targetUser, 'file' : file_64_encode, 'filename' : filename,
  462.          'content_type' : content_type, 'stamp' : time.time()}
  463.    
  464.         data = json.dumps(payload)
  465.         req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
  466.    
  467.         try:
  468.             response = urllib2.urlopen(req)
  469.             raise cherrypy.HTTPRedirect('/index')
  470.    
  471.         except urllib2.URLError as err:
  472.                 raise cherrypy.HTTPRedirect('/actionFailed')
  473.    
  474.  
  475.  
  476.        
  477.     @cherrypy.expose
  478.     @cherrypy.tools.json_in()
  479.     def receiveFile(self):
  480.    
  481.         input_data = cherrypy.request.json
  482.        
  483.         if (blacklist_db.checkList(input_data["sender"])):
  484.        
  485.             receivedFile = base64.decodestring(input_data["file"])     
  486.        
  487.             fileSize = len(receivedFile)
  488.        
  489.             if (fileSize > 5000000):
  490.        
  491.                 return "6" #
  492.        
  493.             else:
  494.                 fileName = input_data["filename"]
  495.                
  496.                 file_result = open(fileName, 'wb')
  497.                 file_result.write(receivedFile)
  498.        
  499.                 return "0"
  500.         else:
  501.             return "11"
  502.        
  503.    
  504.    
  505.     # ------------ END FILES --------------------------------#
  506.    
  507.     ### ------------ USERS -------------------------#
  508.    
  509.     # Viewing all the users in the login server        
  510.     @cherrypy.expose  #TODO: Fix this database!
  511.     def listUsers(self):
  512.         ''' List all of the users currently registered in the login server.'''
  513.        
  514.         url = "http://cs302.pythonanywhere.com/listUsers"
  515.        
  516.         f = urllib.urlopen(url)
  517.                
  518.         Page = f.read() + '</br>'
  519.         #TODO:Update list of users
  520.         #store_registered_users(f)
  521.        
  522.         Page += '</br> Add a user to a black list:'
  523.         Page += '<form action="/addToBlacklist" method="post" enctype="multipart/form-data">'
  524.         Page += 'User: <input type="text" name="UPI" required/><br/>'
  525.         Page += 'Reasoning: <input type="text" name="Reason" required/></br>'
  526.         Page += '<input type="submit" value="Add"/></form>'
  527.        
  528.         Page += '<form action="/showBlacklist" method="get" enctype="multipart/form-data">'
  529.         Page += '<input type="submit" value="View Blacklist"/></form></br>'
  530.        
  531.         Page += "Click <a href = 'index'>here</a> to go back to the main menu"
  532.        
  533.         return Page
  534.        
  535.     @cherrypy.expose
  536.     def addToBlacklist(self,UPI,Reason):
  537.    
  538.         blacklist_db.addToList(UPI,Reason)
  539.        
  540.         raise cherrypy.HTTPRedirect('/listUsers')
  541.    
  542.     #Blackisting
  543.     @cherrypy.expose
  544.     def blockUser(self,UPI,Reason):
  545.    
  546.         blacklist_db.addToList(UPI,Reason)
  547.        
  548.         raise cherrypy.HTTPRedirect('/index')
  549.  
  550.     @cherrypy.expose       
  551.     def showBlacklist(self):
  552.    
  553.         blockedUsers = "<h1>Blocked Users</h1>"
  554.        
  555.         blockedUsers += blacklist_db.viewList() + '</br>'
  556.        
  557.         blockedUsers += "</br>Remove a user from the black list:</br>"
  558.         blockedUsers += '<form action="/removeFromBlacklist" method="post" enctype="multipart/form-data">'
  559.         blockedUsers += 'User: <input type="text" name="UPI" required/><br/>'
  560.         blockedUsers += '<input type="submit" value="Delete"/></form>'
  561.         blockedUsers += "Click <a href = 'index'>here</a> to return to the main menu."
  562.        
  563.        
  564.         return blockedUsers
  565.        
  566.     @cherrypy.expose
  567.     def removeFromBlacklist(self,UPI):
  568.    
  569.         blacklist_db.removeFromList(UPI)
  570.        
  571.         raise cherrypy.HTTPRedirect('/listUsers')
  572.    
  573.    
  574.        
  575.     # -----------------LOGGING IN AND OUT -------------------#
  576.     @cherrypy.expose
  577.     def signin(self, username=None, password=None, userLocation = None):
  578.         """Check their name and password and send them either to the main page, or back to the main login screen."""
  579.                
  580.         saltedPW = str(password) + "COMPSYS302-2017"   
  581.     hashedPW = hashlib.sha256(saltedPW).hexdigest()
  582.        
  583.        
  584.         if (userLocation == '0'):
  585.         my_ip = socket.gethostbyname(socket.gethostname())
  586.     else:
  587.         my_ip = load(urlopen('http://jsonip.com'))['ip']
  588.        
  589.         # Checks whether the user incorrectly types in 2 instead of 0
  590.         if (my_ip[0:3] == "130"):
  591.             userLocation = '0'
  592.             my_ip = socket.gethostbyname(socket.gethostname())
  593.        
  594.        
  595.        
  596.         self.login_parameters = {'username': username, 'password': hashedPW, 'location' : userLocation, 'ip' : my_ip , 'port' : listen_port }
  597.        
  598.         #print hex(id(login_parameters))
  599.        
  600.         url = "http://cs302.pythonanywhere.com/report"
  601.      
  602.    
  603.     payload = urllib.urlencode({'username': username, 'password': hashedPW, 'location' : userLocation, 'ip' : my_ip , 'port' : listen_port  })
  604.     f = urllib.urlopen(url,payload)
  605.        
  606.         error = f.read()[0]
  607.                
  608.         if (error == '0'):
  609.             cherrypy.session['username'] = username;
  610.             cherrypy.session['password'] = hashlib.sha256(password + "COMPSYS302-2017").hexdigest()
  611.             cherrypy.session['userLocation'] = userLocation
  612.                        
  613.             profile_db.createProfile(cherrypy.session['username'])
  614.            
  615.             self.sessionValid = True
  616.                        
  617.             self.report()
  618.                        
  619.             raise cherrypy.HTTPRedirect('/')
  620.        
  621.         else:
  622.             raise cherrypy.HTTPRedirect('/loginFailed')
  623.  
  624.    
  625.     # Threading
  626.     @cherrypy.expose
  627.     def report(self):
  628.    
  629.     url = "http://cs302.pythonanywhere.com/report"
  630.  
  631.          
  632.     if (self.sessionValid == True):
  633.         f = urllib.urlopen(url,urllib.urlencode(self.login_parameters))
  634.    
  635.         #print self.login_parameters
  636.        
  637.         print f.read()
  638.        
  639.         print "REPORT"
  640.         #MAKE SURE TO not have report() as it will be a recursive threading
  641.         threading.Timer(30.0, self.report).start()
  642.        
  643.            
  644.        
  645.    
  646.     @cherrypy.expose
  647.     def logoff(self):
  648.         """Logs the current user out, expires their session"""
  649.     self.sessionValid = False
  650.     print "GOES HERE"
  651.        
  652.     url = "http://cs302.pythonanywhere.com/logoff"
  653.        
  654.     try:
  655.         payload = urllib.urlencode({'username': cherrypy.session['username'], 'password' : cherrypy.session['password']})
  656.     except:
  657.         raise cherrypy.HTTPRedirect('/actionFailed')
  658.            
  659.     try:
  660.         f = urllib.urlopen(url,payload)
  661.         if (f.read()[0] == "0"):
  662.             print "Logged Off"
  663.        
  664.             raise cherrypy.HTTPRedirect('/logout')
  665.     except:
  666.         raise cherrypy.HTTPRedirect('/logout')
  667.    
  668.  
  669.        
  670.     @cherrypy.expose
  671.     def logout(self):
  672.         Page = "You have successfully logged out. "
  673.         self.sessionValid = False
  674.         cherrypy.lib.sessions.expire()
  675.         return Page
  676.        
  677.  
  678.    
  679. # ---------- HELPER FUNCTIONS ----------- #
  680.        
  681. # Gets all the users who are currently online
  682. def getList():
  683.    
  684.     try:
  685.         url = "http://cs302.pythonanywhere.com/getList"
  686.            
  687.         payload = urllib.urlencode({'username': cherrypy.session['username'], 'password' : cherrypy.session['password'], 'json' : '1'})
  688.    
  689.         f = urllib.urlopen(url,payload)
  690.    
  691.         online_users = f.read()
  692.        
  693.         users_db.update_online_users(json.loads(online_users))
  694.        
  695.         return online_users
  696.     except:
  697.         raise cherrypy.HTTPRedirect('/actionFailed')
  698.    
  699. #PING to check if user is still available  
  700. def ping(destination):
  701.  
  702.     ping_url = users_db.getURL(destination) + "/ping?" + "sender=" + cherrypy.session['username']
  703.     req = urllib2.Request(ping_url)
  704.        
  705.     try:
  706.            
  707.         f = urllib2.urlopen(req, timeout = 1)
  708.        
  709.     except urllib2.URLError, err:
  710.         print err
  711.         raise cherrypy.HTTPRedirect('/userOffline')
  712.        
  713.    
  714.     return f.read()
  715.  
  716.  
  717.  
  718.  
  719.  
  720.  
  721.  
  722.          
  723. def runMainApp():
  724.     # Create an instance of MainApp and tell Cherrypy to send all requests under / to it. (ie all of them)
  725.     cherrypy.tree.mount(MainApp(), "/")
  726.  
  727.     # Tell Cherrypy to listen for connections on the configured address and port.
  728.     cherrypy.config.update({'server.socket_host': listen_ip,
  729.                             'server.socket_port': listen_port,
  730.                             'engine.autoreload.on': True,
  731.                            })
  732.  
  733.     print "========================="
  734.     print "University of Auckland"
  735.     print "COMPSYS302 - Software Design Application"
  736.     print "========================================"                      
  737.    
  738.     # Start the web server
  739.     cherrypy.engine.start()
  740.  
  741.     # And stop doing anything else. Let the web server take over.
  742.     cherrypy.engine.block()
  743.  
  744. #Run the function to start everything
  745. runMainApp()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement