def validate(): current_app.logger.info(f"Validate token") try: token = request.json["token"] except KeyError: status = constants.statuses["tokens"]["missingData"] body = create_error(status, "No token get") current_app.logger.warn("No token for validation") return jsonify(body), constants.responses[status] current_app.logger.debug(f"Access token value {token}") body, status = Storage.check_token(token) http_status = constants.responses[status] if status == constants.statuses["tokens"]["accessOk"]: body = dict(status=status, value=body) elif status == constants.statuses["tokens"]["invalidToken"]: body = create_error(status, "Access token has invalid format", error=body) else: # status == constants.statuses["tokens"]["accessTokenExpired"]: body = create_error(status, "Access token expired", error=body) return jsonify(body), http_status
def patch_score(game_id=None): if game_id is None: game_id = request.json.get("game_id") if game_id is None: status = constants.statuses["rating"]["missingData"] http_status = constants.responses[status] return jsonify(create_error(status, "missing score data")), http_status current_app.logger.info( f"Updating score by {request.environ['user_email']} and game id {game_id}" ) request.json["user_id"] = request.environ["user_id"] request.json["game_id"] = game_id score, status = Storage.update_score(request.json, request.method) http_status = constants.responses[status] if status == constants.statuses["rating"]["modified"]: body = dict(score=score, status=status) elif status == constants.statuses["rating"]["notExists"]: body = create_error(status, "no such score") elif status == constants.statuses["rating"]["missingData"]: body = create_error(status, "missing score data") else: # status == constants.statuses["rating"]["replacingData"]: body = create_error(status, "replacing score IDs") return jsonify(body), http_status
def add_game(): current_app.logger.info(f"Creating game by {request.environ['user_email']}") new_id, status = Storage.add_game(**request.json) http_status = constants.responses[status] if status == constants.statuses["game"]["created"]: body = dict(id=new_id, status=status) elif status == constants.statuses["game"]["missingData"]: body = create_error(status, "missing game data") elif status == constants.statuses["game"]["extraFields"]: body = create_error(status, "Extra fields in data") else: # status == constants.statuses["game"]["invalidData"]: body = create_error(status, "Game data is invalid") return jsonify(body), http_status
def change_role(): current_app.logger.info("Make other user admin") if (token := request.headers.get("Authorization")) is None: status = constants.statuses["user"]["unauthorized"] body = create_error(status, "No token get") current_app.logger.warn("No token detected") return jsonify(body), constants.responses[status]
def get_games(): options = dict() if "offset" in request.args: options["offset"] = request.args.get("offset", type=int) if "count" in request.args: options["count"] = request.args.get("count", type=int) if ("offset" in options and options["offset"] < 0 or options.get("count", 0) > constants.values.MAX_ELEMENT_COUNT): status = constants.statuses["request"]["badArguments"] return ( jsonify( create_error(status, "Offset cann't be negative", offset=options["offset"])), constants.responses[status], ) games, status = Storage.get_games(**options) http_status = constants.responses[status] total_count = Storage.get_games_count() count = len(games) if len(options) != 0 or count != total_count: options["count"] = count options["offset"] = options.get("offset", 0) return ( jsonify(games=games, total_count=total_count, status=status, **options), http_status, )
def get_game_rating(game_id): game, status = Storage.get_game_rating(game_id) http_status = constants.responses[status] if status == constants.statuses["rating"]["returned"]: body = dict(rating=game, status=status) else: body = create_error(status, "no such game id: {{ID}}", ID=game_id) return jsonify(body), http_status
def check_id(): file_id = request.args.get("file_id") if file_id is None: status = constants.statuses["request"]["badArguments"] return ( jsonify(create_error(status, "One id must be specified")), constants.responses[status], ) result, status = Storage.file_status(file_id) http_status = constants.responses[status] if status == constants.statuses["batch"]["returned"]: body = dict(status=status, file=result) else: body = create_error(status, "no such file id: {{ID}}", ID=file_id) return jsonify(body), http_status
def get_game(prod_id=None): prod_id = prod_id or request.args.get("id") game, status = Storage.get_game(prod_id) rating, rt_status = Storage.get_game_rating(prod_id) http_status = constants.responses[status] if status == constants.statuses["game"]["returned"]: body = dict(game=game, rating=rating, status=status) else: body = create_error(status, "no such game id: {{ID}}", ID=prod_id) return jsonify(body), http_status
def confirm(token: str): current_app.logger.info(f"Confirming user") current_app.logger.debug(f"Confirm by token {token}") body, status = Storage.confirm_user(token) http_status = constants.responses[status] if status == constants.statuses["user"]["confirmed"]: body = dict(status=status, body=body) elif status == constants.statuses["tokens"]["invalidToken"]: body = create_error(status, "Access token has invalid format", error=body) return jsonify(body), http_status
def add_score(): current_app.logger.info( f"Add score to game {request.json.get('game_id')} by {request.environ['user_email']}" ) request.json["user_id"] = request.environ["user_id"] score, status = Storage.add_score(request.json) http_status = constants.responses[status] if status == constants.statuses["rating"]["created"]: body = dict(score=score, status=status) elif status == constants.statuses["rating"]["missingData"]: body = create_error(status, "missing score data") elif status == constants.statuses["rating"]["extraFields"]: body = create_error(status, "Extra fields in data") elif status == constants.statuses["rating"]["invalidData"]: body = create_error(status, "Rating data is invalid") else: # status == constants.statuses["rating"]["invalidGameId"]: body = create_error(status, "No game with such {{id}}", id=request.json.get("game_id")) return jsonify(body), http_status
def patch_game(prod_id=None): prod_id = prod_id or request.args.get("id") current_app.logger.info( f"Updating game by {request.environ['user_email']} and game id {prod_id}" ) game, status = Storage.update_game(prod_id, request.method, **request.json) http_status = constants.responses[status] if status == constants.statuses["game"]["modified"]: body = dict(game=game, status=status) elif status == constants.statuses["game"]["notExists"]: body = create_error(status, "no such game id: {{ID}}", ID=prod_id) elif status == constants.statuses["game"]["missingData"]: body = create_error(status, "missing game data") elif status == constants.statuses["game"]["extraFields"]: body = create_error(status, "Extra fields in data") elif status == constants.statuses["game"]["invalidData"]: body = create_error(status, "Game data is invalid") else: # status == constants.statuses["game"]["replacingData"]: body = create_error(status, "replacing game ID") return jsonify(body), http_status
def refresh_tokens(): current_app.logger.info("Refresh tokens pair") try: token = request.json["token"] except KeyError: status = constants.statuses["tokens"]["missingData"] body = create_error(status, "No token get") current_app.logger.warn("No token for refreshment") return jsonify(body), constants.responses[status] current_app.logger.debug(f"Refresh token value {token}") access, refresh, status = Storage.update_session(token) http_status = constants.responses[status] if status == constants.statuses["tokens"]["created"]: body = dict(status=status, accessToken=access, refreshToken=refresh) elif status == constants.statuses["tokens"]["noSuchToken"]: body = create_error(status, "No information about token") else: # status == constants.statuses["user"]["refreshExpired"]: body = create_error(status, "Refresh token expired") return jsonify(body), http_status
def delete_game(prod_id=None): prod_id = prod_id or request.args.get("id") current_app.logger.info( f"Deleting game by {request.environ['user_email']} and game id {prod_id}" ) game, status = Storage.delete_game(prod_id) http_status = constants.responses[status] if status == constants.statuses["game"]["deleted"]: body = dict(game=game, status=status) else: body = create_error(status, "no such game id: {{ID}}", ID=prod_id) return jsonify(body), http_status
def delete_score(game_id=None): current_app.logger.info( f"Deleting score by {request.environ['user_email']} and game id {game_id}" ) game, status = Storage.delete_score(game_id, request.environ["user_id"]) http_status = constants.responses[status] if status == constants.statuses["rating"]["deleted"]: body = dict(game=game, status=status) else: # status == constants.statuses["rating"]["notExists"]: body = create_error(status, "no your score for game id: {{ID}}", ID=game_id) return jsonify(body), http_status
def sign_in(): try: email = request.json["email"] password = request.json["password"] except KeyError: status = constants.statuses["user"]["missingData"] body = create_error(status, "missing user data") current_app.logger.warn("Not enough data for sing-in") return jsonify(body), constants.responses[status] current_app.logger.info(f"Sing in for {email}") access, refresh, status = Storage.create_session(email, password) http_status = constants.responses[status] if status == constants.statuses["tokens"]["created"]: body = dict(status=status, accessToken=access, refreshToken=refresh) elif status == constants.statuses["user"]["wrongPassword"]: body = create_error(status, "wrong password for email {{email}}", email=email) elif status == constants.statuses["user"]["notConfirmed"]: body = create_error(status, "Account not confirmed") else: # status == constants.statuses["user"]["noUser"]: body = create_error(status, "No user for email {{email}}", email=email) return jsonify(body), http_status
def get_user_scores(user_id=None): if user_id is None: user_id = request.environ.get("user_id") if user_id is None: return ( jsonify( create_error( constants.statuses["user"]["unauthorized"], "No token detected" ) ), constants.common_responses["No auth"], ) scores, status = Storage.get_user_scores(user_id=user_id) http_status = constants.responses[status] return jsonify(scores=scores, status=status), http_status
def register_user(): try: email = request.json["email"] password = request.json["password"] except (KeyError, TypeError): status = constants.statuses["user"]["missingData"] body = create_error(status, "missing user data") current_app.logger.warn("Not enough data for sing-up") return jsonify(body), constants.responses[status] current_app.logger.info(f"Sing up for {email}") user_id, status = Storage.add_user(email, password) http_status = constants.responses[status] if status == constants.statuses["user"]["created"]: body = dict(status=status, email=email, user_id=user_id) elif status == constants.statuses["user"]["invalidEmail"]: body = create_error(status, "email {{email}} is invalid", email=email) else: # status == constants.statuses["user"]["emailUsed"]: body = create_error(status, "email {{email}} is already registered", email=email) return jsonify(body), http_status
class AuthMiddleware: def __init__(self, app, base_app, logger, allowed=None): self.app = app self.base = base_app self.logger = logger self.allowed: Optional[List[Tuple[str, str]]] = allowed self.auth_method = "Bearer " self.rpc_connection = grpc.insecure_channel( self.base.config["AUTH_GRPC"]) self.validate_stub = AuthStub(self.rpc_connection) def __call__(self, environ, start_response): request = Request(environ, shallow=True) if (authorization := request.headers.get("Authorization")) is None: if request.method in [ "POST", "DELETE", "PUT", "PATCH", ]: # Modifying requests require accessToken self.logger.warn("No token for auth") res = Response( json.dumps( create_error( constants.statuses["user"]["unauthorized"], "No token detected", )), mimetype="application/json", status=constants.common_responses["No auth"], ) return res(environ, start_response) return self.app(environ, start_response) elif type(authorization) != str or not authorization.startswith( self.auth_method): self.logger.warn("Invalid Authorization method") res = Response( json.dumps( create_error( constants.statuses["user"]["unauthorized"], "Invalid Authorization method", )), mimetype="application/json", status=constants.common_responses["No auth"], ) return res(environ, start_response)
def size(): package = request.form['package'] package = package.lower() package_name, pip_name = format_package_name(package) try: package_path = get_install_path(package_name) make_package_path(package_path) install_package(package_path, pip_name) package_info = get_package_info(package_path, package_name) package_location = get_package_location(package_info) package_size = get_package_size(package_location, package_name) uninstall_package(package_path, package_name) remove_package_path(package_path) except Exception as e: return create_error(e) return {"size": package_size, 'error': None}
def __call__(self, environ, start_response): request = Request(environ, shallow=True) if (authorization := request.headers.get("Authorization")) is None: if request.method in [ "POST", "DELETE", "PUT", "PATCH", ]: # Modifying requests require accessToken self.logger.warn("No token for auth") res = Response( json.dumps( create_error( constants.statuses["user"]["unauthorized"], "No token detected", )), mimetype="application/json", status=constants.common_responses["No auth"], ) return res(environ, start_response) return self.app(environ, start_response)
def change_role(): current_app.logger.info("Make other user admin") if (token := request.headers.get("Authorization")) is None: status = constants.statuses["user"]["unauthorized"] body = create_error(status, "No token get") current_app.logger.warn("No token detected") return jsonify(body), constants.responses[status] token = token.strip("Bearer ") if (user_id := request.json.get("user_id")) is None or ( role := request.json.get("role")) is None: status = constants.statuses["user"]["missingData"] return ( jsonify(create_error(status, "Not enough data to change role")), constants.responses[status], ) status = Storage.change_role(token, user_id, role) http_status = constants.responses[status] if status == constants.statuses["user"]["roleChanged"]: body = dict(status=status) elif status == constants.statuses["tokens"]["invalidToken"]: body = create_error(status, "Invalid admin access token") else: # status == constants.statuses["user"]["requestNotAllowed"]: body = create_error(status, "User is not allowed to do this request") return jsonify(body), http_status
)), mimetype="application/json", status=constants.common_responses["No auth"], ) return res(environ, start_response) self.logger.info("Auth request") access_token: str = authorization[len(self.auth_method):] validate_request = ValidateRequest(access_token=access_token) auth: ValidateResponse = self.validate_stub.Validate(validate_request) if auth.status != constants.statuses["tokens"]["accessOk"]: self.logger.warn("Access token is not OK") res = Response( json.dumps(create_error(auth.status, auth.error)), mimetype="application/json", status=constants.common_responses["No auth"], ) return res(environ, start_response) environ["user_email"] = auth.email environ["user_id"] = auth.user_id if self._is_allowed(request, environ, auth): return self.app(environ, start_response) else: self.logger.warn("User is not allowed to do this request") response = json.dumps( create_error( constants.statuses["user"]["requestNotAllowed"],