You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.3 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. import os
  2. import copy
  3. import json
  4. from api.modules import utils
  5. from flask import Flask, request
  6. from flask_restful import Resource, Api, abort
  7. app = Flask(__name__)
  8. api = Api(app)
  9. db_path = os.path.join(app.root_path, 'databases', 'users.json')
  10. with open(db_path, 'r') as f:
  11. users = json.load(f)
  12. class Users(Resource):
  13. def post(self):
  14. """
  15. Example POST Data:
  16. username=<username>&
  17. password=<password>&
  18. realname=<realname>& # OPTIONAL
  19. avatar=<avatar_url>& # OPTIONAL
  20. """
  21. args = request.form
  22. user_id = utils.generate_id()
  23. user = {
  24. 'id': user_id,
  25. 'username': args['username'],
  26. 'realname': args.get('realname'),
  27. 'avatar' : args.get('avatar'),
  28. 'password': utils.md5( args[ 'password' ] ),
  29. 'stats': {
  30. 'bus_usage_week': 0,
  31. 'bus_usage_month': 0,
  32. 'bus_usage_year': 0
  33. },
  34. 'daily_electricity_usage': [],
  35. 'points': 0
  36. }
  37. users.append(user)
  38. with open(db_path, 'w') as f:
  39. json.dump(users, f, indent=4)
  40. return user
  41. class User(Resource):
  42. def get(self, user_id):
  43. try:
  44. user = utils.find_by_id( users.values(), user_id )
  45. if not user:
  46. raise Exception('User not found!')
  47. del user['password']
  48. return user
  49. except:
  50. abort(404, error="User {} doesn't exist".format(user_id))
  51. class Login(Resource):
  52. def post(self):
  53. """
  54. Example POST Data:
  55. username=<username>&
  56. password=<password>
  57. """
  58. #Password for efe is 12345
  59. args = request.form
  60. username = args['username']
  61. password = utils.md5( args[ 'password' ] )
  62. if not username in users:
  63. return [False, {}]
  64. user = copy.deepcopy(users[username])
  65. if user['password'] == password:
  66. del user["password"]
  67. return [True, json.dumps(user)]
  68. else:
  69. return [False, {}]
  70. if __name__ == '__main__':
  71. api.add_resource(Users, '/users', '/users/')
  72. api.add_resource(User, '/users/<path:user_id>', '/users/<path:user_id>/')
  73. api.add_resource(Login, '/login', '/login/')
  74. app.run(host='0.0.0.0', port=5000)