Advertisement
Guest User

Untitled

a guest
Dec 19th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.28 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. """
  4. This module provides a set of reuseable functions
  5. which provide the main app functionality.
  6. We could even go a stage further and separate
  7. database interactions from logic...
  8. """
  9.  
  10. # import modules from Python standard library
  11. from bson.objectid import ObjectId
  12. from datetime import datetime
  13. import bcrypt
  14.  
  15. def insert_cat( db, form):
  16.  
  17. status = False
  18. try:
  19. # get the username from the form
  20. imgLink = form['imageUrl'].value
  21. imgDesc = form['imageDesc'].value
  22. # get the unhashed password sent in the form
  23. except KeyError:
  24. # a field must be missing from the form data
  25. response = "I don't think you filled all the fields"
  26. else:
  27. # look for an account with the username
  28. result = db.images.insert( {
  29. "url" : imgLink,
  30. "created" : datetime.now(),
  31. "alt" : imgDesc,
  32. })
  33. status = True
  34. response = "Image added"
  35.  
  36. return {"status":status, "msg":response}
  37.  
  38. def login( db, form ):
  39. """ Logs a user in if the Username and Password
  40. submitted in a form match a record in database
  41.  
  42. Params:
  43. db: handle to a database
  44. form: FieldStorage object
  45.  
  46. Returns:
  47. Dict
  48. """
  49. # login status is false by default
  50. status = False
  51. try:
  52. # get the username from the form
  53. username = form['username'].value
  54. # get the unhashed password sent in the form
  55. pw = form['password'].value
  56. except KeyError:
  57. # a field must be missing from the form data
  58. response = "I don't think you filled all the fields in..."
  59. else:
  60. # look for an account with the username
  61. account = db.accounts.find_one({
  62. "username":username,
  63. })
  64. # check if an account came back
  65. if account is not None:
  66. # compare the unhashed password from the form
  67. # with the hashed version in the database
  68. if bcrypt.checkpw( pw.encode('utf-8'), account['password'].encode('utf-8') ):
  69. # if they match, output a personal greeting
  70. # was this a DP student?
  71. if account['username'] == "Sunday":
  72. response = "What a good kitty. Now fill in the <a href='https://moduleevaluation.gold.ac.uk/surveyPrivacyStatement/Kf4iWgP74kSxYCxRA'>module feedback form</a> and you shall have some pie."
  73. else:
  74. response = "Hello {}!".format( account['name']['first'] )
  75. status = True
  76. else:
  77. # if not, we know it was a wrong password
  78. response = "Wrong password."
  79. else:
  80. # their username didn't match, so tell them that
  81. response = "Sorry, I don't think I know you!"
  82. # return a dict with the result and a message
  83. return {"status":status,"msg":response}
  84.  
  85. def register_account( db, form ):
  86. """ Registers a new user by inserting an account
  87. in the accounts collection
  88.  
  89. Params:
  90. db: handle to a database
  91. form: FieldStorage object
  92.  
  93. Returns:
  94. Dict
  95. """
  96. # registration status false by default
  97. status = False
  98. try:
  99. # get the username from the form
  100. username = form['username'].value
  101. # get the email from the form
  102. email = form['email'].value
  103. # get the unhashed password from the form
  104. password = form['password'].value
  105. except KeyError:
  106. # a field must be missing from the form data
  107. response = "I don't think you filled all the fields in..."
  108. else:
  109. # check if there is already an account with the email
  110. # or username
  111. result = db.accounts.find_one( { '$or': [
  112. { 'username' : username },
  113. { 'email': email }
  114. ]} )
  115. # if so, send back a useful response
  116. if result:
  117. if email in result.values():
  118. response = "Email address already registered."
  119. else:
  120. response = "Username taken."
  121. # otherwise go ahead and make the account
  122. else:
  123. hashed_pw = bcrypt.hashpw( password.encode('utf-8'), bcrypt.gensalt() )
  124. query = {
  125. "username": username,
  126. "password": hashed_pw.decode('utf-8'),
  127. "is_admin": 0,
  128. "created" : datetime.now().timestamp()
  129. }
  130. # make sure name fields aren't empty
  131. # if they are, give them empty string values
  132. if 'first' in form:
  133. first = form['first'].value
  134. else:
  135. first = ""
  136. if 'last' in form:
  137. last = form['last'].value
  138. else:
  139. last = ""
  140. # append name to query
  141. query["name"] = { "first": first, "last": last }
  142. # insert the account in the database
  143. doc = db.accounts.insert( query )
  144. if doc:
  145. status = True
  146. response = "New account registered. <a href='/cgi-bin/.py' title='login'>Click here</a> to go Log in!"
  147. else:
  148. response = "Problem registering your account. Please refresh the page to try again."
  149. # return something useful...
  150. return {'status': status, 'msg': response}
  151. l
  152. def latest_fluck( db ):
  153. """ Returns details of the most recently flucked
  154. cat in the database
  155.  
  156. Params:
  157. db: handle to a database
  158.  
  159. Returns:
  160. Dict
  161. """
  162. # start with an empty dict
  163. image = {}
  164. # get details of last flucked cat
  165. result = db.flucks.find({"is_flucked":1}).sort([('timestamp', -1)]).limit(1)
  166. # get the associated image
  167. for fluck in result:
  168. result2 = db.images.find({"_id":fluck["image_id"]})
  169. # if a doc was returned, put the bits we want in the image dict
  170. for doc in result2:
  171. image = {"url":doc["url"],"alt":doc["alt"]}
  172. return image
  173.  
  174. def most_flucked( db ):
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement