server_controller.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import json
  2. from bottle import request, response
  3. import model
  4. from util import debug
  5. def missing_attributes(attributes):
  6. for attr in attributes:
  7. if attr not in request.json:
  8. return attr
  9. else:
  10. return False
  11. def login():
  12. missing = missing_attributes(['username', 'password'])
  13. if missing:
  14. return bad_request('Missing value for attribute ' + str(missing))
  15. username = request.json['username']
  16. password = request.json['password']
  17. session_id = model.login(username, password)
  18. if session_id:
  19. return {'session_id': session_id}
  20. else:
  21. return forbidden('Invalid login data')
  22. def register():
  23. missing = missing_attributes(['username', 'password'])
  24. if missing:
  25. return bad_request('Missing value for attribute ' + str(missing))
  26. username = request.json['username']
  27. password = request.json['password']
  28. if model.user_exists(username):
  29. return forbidden('User already exists.')
  30. game_key = None
  31. if 'game_key' in request.json:
  32. game_key = request.json['game_key']
  33. if game_key not in model.unused_keys():
  34. return bad_request('Game key is not valid.')
  35. if model.register(username, password, game_key):
  36. return {'message': "successfully registered user"}
  37. else:
  38. return bad_request('registration not successful')
  39. def not_found(msg=''):
  40. response.status = 404
  41. if debug:
  42. msg = str(response.status) + ' Page not found: ' + msg
  43. response.content_type = 'application/json'
  44. return json.dumps({"error_message": msg})
  45. def forbidden(msg=''):
  46. response.status = 403
  47. if debug:
  48. msg = str(response.status) + ' Forbidden: ' + msg
  49. response.content_type = 'application/json'
  50. return json.dumps({"error_message": msg})
  51. def bad_request(msg=''):
  52. response.status = 400
  53. if debug:
  54. msg = str(response.status) + ' Bad request: ' + msg
  55. response.content_type = 'application/json'
  56. return json.dumps({"error_message": msg})