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.

88 lines
2.2 KiB

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