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.

83 lines
2.2 KiB

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 json
  3. from . 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. args = request.form
  57. print(args)
  58. username = args['username']
  59. passsword = utils.md5(args['password'])
  60. for user in users:
  61. if user['username'] == username:
  62. if user['password'] == passsword:
  63. return {'message': 'Login successful!', 'id': user['id']}
  64. return {'error': 'Wrong password!'}
  65. return {'error': 'User not found!'}
  66. if __name__ == '__main__':
  67. api.add_resource(Users, '/users', '/users/')
  68. api.add_resource(User, '/users/<path:user_id>', '/users/<path:user_id>/')
  69. api.add_resource(Login, '/login', '/login/')
  70. app.run(host='0.0.0.0', port=5000)