Format: text/x-python
⬇ Download File (1.3 KB)
   1  from flask import jsonify
   2  from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
   3  import hashlib
   4  
   5  def configure_auth(app):
   6      app.config['JWT_SECRET_KEY'] = 'super-secret'  # TODO: Replace with env var in prod
   7      app.config['JWT_ACCESS_TOKEN_EXPIRES'] = 3600  # 1 hour
   8  
   9      # Auth routes
  10      @app.route('/api/login', methods=['POST'])
  11      def login():
  12          username = request.json.get('username')
  13          password = request.json.get('password')
  14          
  15          # TODO: Implement proper user store
  16          test_user = {
  17              'username': 'admin',
  18              'password': hashlib.sha256('admin'.encode()).hexdigest()
  19          }
  20  
  21          if not username or not password:
  22              return jsonify({"error": "Missing credentials"}), 400
  23  
  24          hashed_pw = hashlib.sha256(password.encode()).hexdigest()
  25          
  26          if username == test_user['username'] and hashed_pw == test_user['password']:
  27              access_token = create_access_token(identity=username)
  28              return jsonify(access_token=access_token), 200
  29  
  30          return jsonify({"error": "Invalid credentials"}), 401
  31  
  32      # Protected route example
  33      @app.route('/api/protected', methods=['GET'])
  34      @jwt_required()
  35      def protected():
  36          current_user = get_jwt_identity()
  37          return jsonify(logged_in_as=current_user), 200