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.

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