PageRenderTime 67ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/New.py

https://bitbucket.org/dlrrb4714/uoa-cs302-2018-p2-ilee471
Python | 623 lines | 608 code | 3 blank | 12 comment | 1 complexity | f0d5a272ade5019cd0b677f58d99765c MD5 | raw file
  1. #!/usr/bin/python
  2. """ cherrypy_example.py
  3. COMPSYS302 - Software Design
  4. Author: Andrew Chen (andrew.chen@auckland.ac.nz)
  5. Last Edited: 19/02/2018
  6. This program uses the CherryPy web server (from www.cherrypy.org).
  7. """
  8. # Requires: CherryPy 3.2.2 (www.cherrypy.org)
  9. # Python (We use 2.7)
  10. # The address we listen for connections on
  11. listen_ip = "0.0.0.0"
  12. listen_port = 10002
  13. import cherrypy
  14. import hashlib
  15. import urllib2
  16. import sqlite3
  17. import json
  18. import time
  19. import socket
  20. import base64
  21. import mimetypes
  22. import os
  23. import os.path
  24. import threading
  25. import atexit
  26. openUser = ""
  27. loggedIn = 0
  28. user_id = ""
  29. user_password = ""
  30. class MainApp(object):
  31. #CherryPy Configuration
  32. _cp_config = {'tools.encode.on': True,
  33. 'tools.encode.encoding': 'utf-8',
  34. 'tools.sessions.on' : 'True',
  35. }
  36. # If they try somewhere we don't know, catch it here and send them to the right place.
  37. def __init__(self):
  38. cherrypy.engine.subscribe("stop", self.logoutOnExit)
  39. @cherrypy.expose
  40. def default(self, *args, **kwargs):
  41. """The default page, given when we don't recognise where the request is for."""
  42. Page = "I don't know where you're trying to go, so have a 404 Error."
  43. cherrypy.response.status = 404
  44. return Page
  45. # PAGES (which return HTML that can be viewed in browser)
  46. @cherrypy.expose
  47. def index(self):
  48. Page = "Welcome! This is a test website for COMPSYS302!<br/>"
  49. try:
  50. # Page += "Hello " + cherrypy.session['username'] + "!<br/>"
  51. # Page += "Here is some bonus text because you've logged in!<br/>"
  52. # Page += "Click here to <a href = 'usersOnline'>check online users.<a/><br/>"
  53. # Page += '<form action = "/sendMessage" method = "post" enctype="multipart/form-data">'
  54. # Page += 'To : <input type = "text" name = "destination"/><br/>'
  55. # Page += 'Message : <input type = "text" name = "message"/>'
  56. # Page += '<input type = "submit" value = "Send"/></form>'
  57. # Page += '<form action="/messages" method="post" enctype="multipart/form-data">'
  58. # Page += '<input type = "submit" value = "Check Messages"/></form>'
  59. # Page += '<form action="/retrieveProfile" method="post" enctype="multipart/form-data">'
  60. # Page += '<input type = "text" name = "prof"/>'
  61. # Page += '<input type = "submit" value = "Check Profile"/></form>'
  62. # Page += '<form action="/updateProfile" method="post" >'
  63. # Page += 'Name : <input type = "text" name = "fullname"/>'
  64. # Page += 'Position : <input type = "text" name = "position"/>'
  65. # Page += 'Description : <input type = "text" name = "description"/>'
  66. # Page += 'Location : <input type = "text" name = "location"/>'
  67. # Page += 'Picture : <input type = "file" name = "profile"/>'
  68. # Page += '<input type = "submit" value = "Update Profile"/></form>'
  69. # Page += '<form action="/sendFile" method="post" enctype="multipart/form=data">'
  70. # Page += 'To : <input type = "text" name = "destination"/><br/>'
  71. # Page += 'File : <input type = "file" name = "file"/>'
  72. # Page += '<input type = "submit" value = "Send"/></form>'
  73. # Page += '<form action="/logout" method="post" enctype="multipart/form-data">'
  74. # Page += '<input type ="submit" value = "Logout"/></form>'
  75. return self.loadMainPage()
  76. except KeyError: #There is no username
  77. Page += "Click here to <a href='login'>login</a>."
  78. return Page
  79. @cherrypy.expose
  80. def loadMainPage(self):
  81. conn = sqlite3.connect("profiles.db")
  82. c = conn.cursor()
  83. c.execute('''SELECT fullname, position, description, location, picture FROM profiles WHERE username = ?''',
  84. (cherrypy.session['username'],))
  85. rows = c.fetchall()
  86. print rows
  87. self.usersOnline()
  88. return open('html/mainpage.html').read().format(username=self.makeUserList(), fullname=rows[0][0],
  89. position=rows[0][1], description=rows[0][2],
  90. location=rows[0][3], picture=rows[0][4])
  91. def makeUserList(self):
  92. users = json.loads(self.getList())
  93. userlist = '<form action="/loadMessages" method="post">'
  94. for i in users:
  95. userlist += '<button name="username" value="' + users[i]["username"] + '">' + users[i]["username"] + "</button><br/>"
  96. userlist += '</form>'
  97. return userlist
  98. @cherrypy.expose
  99. def loadUpdateProfile(self):
  100. return open('html/updateprofile.html').read().format(username=self.makeUserList())
  101. @cherrypy.expose
  102. def loadMessages(self, username=None):
  103. global openUser
  104. openUser = username
  105. users = json.loads(self.getList())
  106. messageList = ""
  107. conn = sqlite3.connect("messages.db")
  108. c = conn.cursor()
  109. try:
  110. c.execute(
  111. '''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
  112. except sqlite3.OperationalError:
  113. pass
  114. if openUser == cherrypy.session['username']:
  115. c.execute(
  116. '''SELECT sender, destination, message, stamp, file, filetype FROM messages WHERE sender = ? AND destination = ?''',
  117. (cherrypy.session['username'],cherrypy.session['username']))
  118. rows = c.fetchall()
  119. print rows
  120. for i in rows:
  121. if i[4] == 0:
  122. messageList += '<h1 class = "mine">' + i[2] + "<h1/><br/>"
  123. else:
  124. if i[4] == 1:
  125. if i[5].find("image") != -1:
  126. messageList += '<img class = "mine" width="20%" src ="' + i[2] + '" alt = "Received File"><img/>'
  127. elif i[5].find("video") != -1:
  128. messageList += '<video class = "mine" width="20%" controls src="' + i[2] + '"><video/>'
  129. elif i[5].find("audio") != -1:
  130. messageList += '<audio class = "mine" controls src="' + i[2] + '"><audio/>'
  131. elif i[5].find("application") != -1:
  132. messageList += '<a class = "mine pdf" ' + "href = '" + i[2] + "'>" + i[2] + "<a/>"
  133. else:
  134. for i in users:
  135. if users[i]["username"] == username:
  136. c.execute('''SELECT sender, destination, message, stamp, file, filetype FROM messages WHERE sender = ? OR destination = ?''', (username, username))
  137. rows = c.fetchall()
  138. print rows
  139. for i in rows:
  140. if i[0] == cherrypy.session['username']:
  141. if i[4] == 0:
  142. messageList += '<h1 class = "mine">' + i[2] + "<h1/><br/>"
  143. else:
  144. if i[5].find("image") != -1:
  145. messageList += '<img class = "mine" src ="' + i[2] + '" alt = "Received File"><img/><br/>'
  146. elif i[5].find("video") != -1:
  147. messageList += '<video class = "mine" width="300" height = "200" controls src="' + i[2] + '"><video/><br/>'
  148. elif i[5].find("audio") != -1:
  149. messageList += '<audio class = "mine" controls src="' + i[2] + '"><audio/><br/>'
  150. elif i[5].find("application") != -1:
  151. messageList += '<a class = "mine pdf" ' + "href = '" + i[2] + "'>" + i[2] + "<a/><br/>"
  152. else:
  153. if i[4] == 0:
  154. messageList += '<h1 class = "theirs">' + i[2] + "<h1/><br/>"
  155. else:
  156. if i[4] == 1:
  157. if i[5].find("image") != -1:
  158. messageList += '<img class = "theirs" src ="' + i[2] + '" alt = "Received File"><img/><br/>'
  159. elif i[5].find("video") != -1:
  160. messageList += '<video class = "theirs" width="300" height = "200" controls src="' + i[2] + '"><video/><br/>'
  161. elif i[5].find("audio") != -1:
  162. messageList += '<audio class = "theirs" controls src="' + i[2] + '"><audio/><br/>'
  163. elif i[5].find("application") != -1:
  164. messageList += '<a class = "mine pdf" ' + "href = '" + i[2] + "'>" + i[2] + "<a/><br/>"
  165. print messageList
  166. self.retrieveProfile(openUser)
  167. conn = sqlite3.connect("profiles.db")
  168. c = conn.cursor()
  169. c.execute('''SELECT fullname, position, description, location, picture FROM profiles WHERE username = ?''', (openUser,))
  170. rows = c.fetchall()
  171. return open('html/messages.html').read().format(username=self.makeUserList(), messages=messageList,
  172. fullname=rows[0][0], position=rows[0][1],
  173. description=rows[0][2], location=rows[0][3],
  174. picture=rows[0][4])
  175. @cherrypy.expose
  176. def loadOnlineUsers(self):
  177. users = json.loads(self.getList())
  178. list = ""
  179. for i in users:
  180. list += "<button>" + i + "</button>"
  181. open('html/mainpage.html').read().format(username = list)
  182. @cherrypy.expose
  183. def login(self):
  184. return open('html/1.html').read()
  185. # Page = '<form action="/signin" method="post" enctype="multipart/form-data">'
  186. # Page += 'Username: <input type="text" name="username"/><br/>'
  187. # Page += 'Password: <input type="password" name="password"/>'
  188. # Page += '<input type="submit" value="Poos"/></form>'
  189. # return Page
  190. @cherrypy.expose
  191. def loggedoff(self):
  192. Page = "You have successfully logged off!<br/>"
  193. Page += "Click here to <a href = 'login'>login again</a>."
  194. return Page
  195. @cherrypy.expose
  196. def logofferror(self):
  197. Page = 'Something went wrong! You may have not been logged in.<br/>'
  198. Page += "Click here to <a href = 'login'>return to the login page</a>."
  199. return Page
  200. @cherrypy.expose
  201. def messages(self):
  202. Page = 'Messages:<br/><br/>'
  203. conn = sqlite3.connect("messages.db")
  204. c = conn.cursor()
  205. try:
  206. c.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
  207. except sqlite3.OperationalError:
  208. pass
  209. c.execute('''SELECT * FROM messages''')
  210. rows = c.fetchall()
  211. print rows
  212. for i in rows:
  213. Page += "Sender : " + str(i[1]) + "<br/>"
  214. Page += "Destination : " + str(i[2]) + "<br/>"
  215. Page += "Message : " + str(i[3]) + "<br/>"
  216. Page += "Stamp : " + str(i[4]) + "<br/>" + "<br/>"
  217. conn.close()
  218. return Page
  219. @cherrypy.expose
  220. def sum(self, a=0, b=0): #All inputs are strings by default
  221. output = int(a)+int(b)
  222. return str(output)
  223. @cherrypy.expose
  224. def ping(self, sender):
  225. return '0'
  226. @cherrypy.expose
  227. def getList(self):
  228. username = cherrypy.session['username']
  229. password = cherrypy.session['password']
  230. res = urllib2.urlopen("http://cs302.pythonanywhere.com/getList?username=" + username
  231. + "&password=" + password
  232. + "&json=1").read()
  233. return res
  234. @cherrypy.tools.json_in()
  235. @cherrypy.expose
  236. def receiveMessage(self):
  237. received = cherrypy.request.json
  238. conn = sqlite3.connect("messages.db")
  239. c = conn.cursor()
  240. try:
  241. c.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
  242. except sqlite3.OperationalError:
  243. pass
  244. if received["sender"] == received["destination"]:
  245. pass
  246. else:
  247. c.execute('''INSERT INTO messages(sender, destination, message, stamp, file, filetype) VALUES(?,?,?,?,?,?)''', (received["sender"], received["destination"], received["message"], received["stamp"], 0, ""))
  248. conn.commit()
  249. conn.close()
  250. return '0'
  251. @cherrypy.expose
  252. def sendMessage(self, message = None):
  253. username = cherrypy.session['username']
  254. users = json.loads(self.getList())
  255. # url = "http://" + users[i]["ip"] + ":" + users[i]["port"] + "/ping?sender=" + username
  256. # if urllib2.urlopen(url).read() == '0':
  257. conn = sqlite3.connect("messages.db")
  258. c = conn.cursor()
  259. try:
  260. c.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
  261. except sqlite3.OperationalError:
  262. pass
  263. for i in users:
  264. if users[i]["username"] == openUser and urllib2.urlopen("http://" + users[i]["ip"] + ":" + users[i]["port"] + "/ping?sender=" + username).read() == '0':
  265. url = "http://" + users[i]["ip"] + ":" + users[i]["port"] + "/receiveMessage"
  266. mes = { "sender" : cherrypy.session['username'], "destination" : openUser, "message" : message, "stamp" : time.time()}
  267. data = json.dumps(mes)
  268. req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
  269. urllib2.urlopen(req)
  270. c.execute('''INSERT INTO messages(sender, destination, message, stamp, file, filetype) VALUES(?,?,?,?,?,?)''', (username, openUser, message, time.time(), 0, "None"))
  271. conn.commit()
  272. conn.close()
  273. return self.loadMessages(openUser)
  274. # raise cherrypy.HTTPRedirect(/loadMessages?openUser)
  275. @cherrypy.expose
  276. def usersOnline(self):
  277. res = json.loads(self.getList())
  278. conn = sqlite3.connect("list.db")
  279. c = conn.cursor()
  280. try:
  281. c.execute('''CREATE TABLE users(id INTEGER PRIMARY KEY, username TEXT, ip TEXT, location TEXT, lastLogin TEXT, port TEXT)''')
  282. except sqlite3.OperationalError:
  283. pass
  284. c.execute('''DELETE FROM users''')
  285. for i in res:
  286. c.execute('''INSERT INTO users(username, ip, location, lastLogin, port) VALUES(?,?,?,?,?)''', (res[i]["username"],res[i]["ip"],res[i]["location"],res[i]["lastLogin"],res[i]["port"]))
  287. conn.commit()
  288. Page = ''
  289. c.execute('''SELECT * FROM users''')
  290. rows = c.fetchall()
  291. for row in rows:
  292. Page += "Username : " + str(row[1]) + "<br/>"
  293. Page += "IP : " + str(row[2]) + "<br/>"
  294. Page += "Location :" + str(row[3]) + "<br/>"
  295. Page += "Last Login : " + str(row[4]) + "<br/>"
  296. Page += "Port : " + str(row[5]) + "<br/>" + "<br/>"
  297. conn.close()
  298. return Page
  299. @cherrypy.expose
  300. def retrieveProfile(self, prof = None):
  301. users = json.loads(self.getList())
  302. conn = sqlite3.connect("profiles.db")
  303. c = conn.cursor()
  304. try:
  305. c.execute('''CREATE TABLE profiles(username TEXT PRIMARY KEY, lastUpdated TEXT, fullname TEXT, position TEXT, description TEXT, location TEXT, picture TEXT, encoding TEXT, encryption TEXT, decryptionKey TEXT)''')
  306. except sqlite3.OperationalError:
  307. pass
  308. for i in users:
  309. if users[i]["username"] == prof:
  310. url = 'http://' + users[i]["ip"] + ":" + users[i]["port"] + "/getProfile"
  311. data = json.dumps({"profile_username" : prof, "sender" : cherrypy.session['username']})
  312. req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
  313. received = json.loads(urllib2.urlopen(req).read())
  314. try:
  315. c.execute('''INSERT INTO profiles(username, lastUpdated, fullname, position, description, location, picture) VALUES(?,?,?,?,?,?,?)''', (prof, received["lastUpdated"], received["fullname"], received["position"], received["description"], received["location"], received["picture"]))
  316. except sqlite3.IntegrityError:
  317. c.execute('''UPDATE profiles SET lastUpdated = ?, fullname = ?, position = ?, description = ?, location = ?, picture = ? WHERE username = ?''', (received["lastUpdated"], received["fullname"], received["position"], received["description"], received["location"], received["picture"], prof))
  318. except KeyError:
  319. print "Error! Profile not valid"
  320. raise cherrypy.HTTPRedirect('/')
  321. conn.commit()
  322. conn.close()
  323. @cherrypy.tools.json_in()
  324. @cherrypy.expose
  325. def getProfile(self):
  326. received = cherrypy.request.json
  327. conn = sqlite3.connect("profiles.db")
  328. c = conn.cursor()
  329. c.execute('''SELECT lastUpdated, fullname, position, description, location, picture FROM profiles WHERE username = ?''', (received['profile_username'],))
  330. rows = c.fetchall()
  331. profile = {"lastUpdated" : str(rows[0][0]), "fullname" : str(rows[0][1]), "position" : str(rows[0][2]), "description" : str(rows[0][3]), "location" : str(rows[0][4]), "picture" : str(rows[0][5])}
  332. print profile
  333. data = json.dumps(profile)
  334. return data
  335. @cherrypy.expose
  336. def createInitialProfile(self):
  337. conn = sqlite3.connect("profiles.db")
  338. c = conn.cursor()
  339. try:
  340. c.execute('''CREATE TABLE profiles(username TEXT PRIMARY KEY, lastUpdated TEXT, fullname TEXT, position TEXT, description TEXT, location TEXT, picture TEXT, encoding TEXT, encryption TEXT, decryptionKey TEXT)''')
  341. except sqlite3.OperationalError:
  342. print "1"
  343. pass
  344. try:
  345. c.execute(
  346. '''INSERT INTO profiles(username, lastUpdated, fullname, position, description, location, picture) VALUES(?,?,?,?,?,?,?)''',
  347. (cherrypy.session['username'], time.time(), "(No Name)", "", "", "", "static/whitesquare.jpg"))
  348. except sqlite3.IntegrityError:
  349. pass
  350. conn.commit()
  351. conn.close()
  352. @cherrypy.expose
  353. def updateProfile(self, fullname = None, position = None, description = None, location = None, profile = None):
  354. username = cherrypy.session['username']
  355. conn = sqlite3.connect("list.db")
  356. c = conn.cursor()
  357. c.execute('''SELECT ip, port FROM users WHERE username = ?''', (username,))
  358. rows = c.fetchall()
  359. conn = sqlite3.connect("profiles.db")
  360. c = conn.cursor()
  361. try:
  362. f = open(profile, "r")
  363. pic = f.name
  364. except IOError:
  365. pic = "whitesquare.jpg"
  366. print pic
  367. if fullname == "":
  368. fullname = "(No Name)"
  369. print fullname
  370. try:
  371. c.execute('''CREATE TABLE profiles(username TEXT PRIMARY KEY, username TEXT, lastUpdated TEXT, fullname TEXT, position TEXT, description TEXT, location TEXT, picture TEXT, encoding TEXT, encryption TEXT, decryptionKey TEXT)''')
  372. except sqlite3.OperationalError:
  373. pass
  374. c.execute('''UPDATE profiles SET lastUpdated = ?, fullname = ?, position = ?, description = ?, location = ?, picture = ? WHERE username = ?''',
  375. (time.time(), fullname, position, description, location, "http://" + rows[0][0] + ":" + rows[0][1] + "/static/" + pic, "ilee471"))
  376. conn.commit()
  377. conn.close()
  378. raise cherrypy.HTTPRedirect('/')
  379. @cherrypy.tools.json_in()
  380. @cherrypy.expose
  381. def receiveFile(self):
  382. received = cherrypy.request.json
  383. decoded = base64.decodestring(received["file"])
  384. cwd = os.getcwd()
  385. os.chdir(cwd+"/files")
  386. res = open(received["filename"], "wb")
  387. res.write(decoded)
  388. res.close()
  389. os.chdir(cwd)
  390. conn = sqlite3.connect("messages.db")
  391. c = conn.cursor()
  392. print received["content_type"]
  393. try:
  394. c.execute('''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
  395. except sqlite3.OperationalError:
  396. pass
  397. c.execute('''INSERT INTO messages(sender, destination, message, stamp, file, filetype) VALUES (?,?,?,?,?,?)''',
  398. (received["sender"], received["destination"], "static/files/" + received["filename"], received["stamp"],
  399. 1, received["content_type"]))
  400. conn.commit()
  401. conn.close()
  402. return '0'
  403. @cherrypy.expose
  404. def sendFile(self, destination = None, file = None):
  405. destination = openUser
  406. # if destination is None or file is None:
  407. # raise cherrypy.HTTPRedirect('/')
  408. users = json.loads(self.getList())
  409. for i in users:
  410. if users[i]["username"] == destination and urllib2.urlopen("http://" + users[i]["ip"] + ":" + users[i]["port"] + "/ping?sender=" + cherrypy.session['username']).read() == '0':
  411. r = file.file.read()
  412. file_data = base64.encodestring(r) # base 64 encoding of file data
  413. filename = file.filename
  414. cwd = os.getcwd()
  415. os.chdir(cwd + "/files")
  416. save = open(filename, "wb")
  417. save.write(r)
  418. save.close()
  419. os.chdir(cwd)
  420. if os.path.getsize("files/" + filename) < 5000000:
  421. print filename
  422. content_type = str(file.content_type)
  423. conn = sqlite3.connect("messages.db")
  424. c = conn.cursor()
  425. try:
  426. c.execute(
  427. '''CREATE TABLE messages(id INTEGER PRIMARY KEY, sender TEXT, destination TEXT, message TEXT, stamp TEXT, file INTEGER, filetype TEXT)''')
  428. except sqlite3.OperationalError:
  429. pass
  430. c.execute(
  431. '''INSERT INTO messages(sender, destination, message, stamp, file, filetype) VALUES (?,?,?,?,?,?)''',
  432. (user_id, destination, "static/files/" + filename, time.time(), 1, content_type))
  433. conn.commit()
  434. conn.close()
  435. json_data = {"sender": cherrypy.session['username'], "destination": destination, "file": file_data,
  436. "filename": filename, "content_type": content_type, "stamp": time.time()}
  437. data = json.dumps(json_data)
  438. url = "http://" + users[i]["ip"] + ":" + users[i]["port"] + "/receiveFile"
  439. req = urllib2.Request(url, data, {'Content-Type' : 'application/json'})
  440. urllib2.urlopen(req)
  441. return self.loadMessages(openUser)
  442. # LOGGING IN AND OUT
  443. @cherrypy.expose
  444. def signin(self, username=None, password=None):
  445. """Check their name and password and send them either to the main page, or back to the main login screen."""
  446. self.location()
  447. error = self.authoriseUserLogin(username,password, cherrypy.session['location'])
  448. if error == 0:
  449. cherrypy.session['username'] = username
  450. cherrypy.session['password'] = hashlib.sha256(password+username).hexdigest()
  451. global user_id
  452. global user_password
  453. user_id = cherrypy.session['username']
  454. user_password = cherrypy.session['password']
  455. self.initializeLoginThread()
  456. self.createInitialProfile()
  457. raise cherrypy.HTTPRedirect('/')
  458. else:
  459. raise cherrypy.HTTPRedirect('/login')
  460. @cherrypy.expose
  461. def logout(self):
  462. error = self.signout()
  463. if error == 0:
  464. raise cherrypy.HTTPRedirect('/loggedoff')
  465. else:
  466. raise cherrypy.HTTPRedirect('/logofferror')
  467. @cherrypy.expose
  468. def location(self):
  469. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  470. s.connect(("8.8.8.8", 80))
  471. ip = (s.getsockname()[0])
  472. s.close()
  473. if ip.find("10.103") == 0:
  474. lo = "0"
  475. elif ip.find("172.23") == 0:
  476. lo = "1"
  477. else:
  478. lo = "2"
  479. cherrypy.session['location'] = lo
  480. @cherrypy.expose
  481. def signout(self):
  482. """Logs the current user out, expires their session"""
  483. print user_id
  484. print user_password
  485. res = urllib2.urlopen("http://cs302.pythonanywhere.com/logoff?username=" + user_id
  486. + "&password=" + user_password)
  487. num = res.read()
  488. try:
  489. cherrypy.lib.sessions.expire()
  490. except KeyError:
  491. pass
  492. print num
  493. if num[0] == '0':
  494. return 0
  495. else:
  496. return 1
  497. def initializeLoginThread(self):
  498. if cherrypy.session['username'] is None:
  499. raise cherrypy.HTTPRedirect('/login')
  500. else:
  501. cherrypy.session['logged'] = threading.Event()
  502. cherrypy.session['logged'].set()
  503. thread = threading.Thread(target = self.autorelogin, args=(cherrypy.session['username'], cherrypy.session['password'],
  504. cherrypy.session['logged'], cherrypy.session['location']))
  505. thread.daemon = True
  506. thread.start()
  507. def autorelogin(self, username = "", password = "", logged = "", location = ""):
  508. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  509. s.connect(("8.8.8.8", 80))
  510. ip = (s.getsockname()[0])
  511. #ip = "172.23.20.177"
  512. s.close()
  513. while logged.isSet():
  514. req = urllib2.Request("http://cs302.pythonanywhere.com/report?username=" + username
  515. + "&password=" + password
  516. + "&location=" + location
  517. + "&ip=" + ip
  518. + "&port=" + str(listen_port))
  519. num = urllib2.urlopen(req).read()
  520. time.sleep(60)
  521. def authoriseUserLogin(self, username, password, location):
  522. print username
  523. print password
  524. password = hashlib.sha256(password + username).hexdigest()
  525. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  526. s.connect(("8.8.8.8", 80))
  527. ip = (s.getsockname() [0])
  528. #ip = "172.23.20.177"
  529. s.close()
  530. res = urllib2.urlopen("http://cs302.pythonanywhere.com/report?username=" + username
  531. + "&password=" + password
  532. + "&location=" + location
  533. + "&ip=" + ip
  534. + "&port=" + str(listen_port))
  535. num = res.read()
  536. if num[0] == '0':
  537. global loggedIn
  538. loggedIn = 1
  539. return 0
  540. else:
  541. return 1
  542. @cherrypy.expose
  543. def logoutOnExit(self):
  544. if loggedIn == 1:
  545. print 1
  546. cherrypy.session['logged'].clear()
  547. self.signout()
  548. def runMainApp():
  549. # Create an instance of MainApp and tell Cherrypy to send all requests under / to it. (ie all of them)
  550. cherrypy.tree.mount(MainApp(), "/")
  551. c = { '/static' : {
  552. 'tools.staticdir.on' : True,
  553. 'tools.staticdir.dir' : os.path.abspath(os.getcwd())
  554. }}
  555. cherrypy.tree.mount(MainApp(), "/", c)
  556. # Tell Cherrypy to listen for connections on the configured address and port.
  557. cherrypy.config.update({'server.socket_host': listen_ip,
  558. 'server.socket_port': listen_port,
  559. 'engine.autoreload.on': True,
  560. })
  561. print "========================="
  562. print "University of Auckland"
  563. print "COMPSYS302 - Software Design Application"
  564. print "========================================"
  565. # Start the web server
  566. cherrypy.engine.start()
  567. # And stop doing anything else. Let the web server take over.
  568. cherrypy.engine.block()
  569. #Run the function to start everything
  570. runMainApp()