server_controller.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. if model.register(username, password):
  31. return {'message': "successfully registered user"}
  32. else:
  33. bad_request('registration not successful')
  34. def not_found(msg=''):
  35. response.status = 404
  36. if debug:
  37. msg = str(response.status) + ' Page not found: ' + msg
  38. response.content_type = 'application/json'
  39. return json.dumps({"error_message": msg})
  40. def forbidden(msg=''):
  41. response.status = 403
  42. if debug:
  43. msg = str(response.status) + ' Forbidden: ' + msg
  44. response.content_type = 'application/json'
  45. return json.dumps({"error_message": msg})
  46. def bad_request(msg=''):
  47. response.status = 400
  48. if debug:
  49. msg = str(response.status) + ' Bad request: ' + msg
  50. response.content_type = 'application/json'
  51. return json.dumps({"error_message": msg})