forked from superdesk/newsroom-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create new async OAuthClient resource, blueprint & helper functions […
…NHUB-528]
- Loading branch information
1 parent
b68c267
commit aa65c21
Showing
6 changed files
with
123 additions
and
78 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
from content_api import MONGO_PREFIX | ||
from typing import Optional, Annotated, List, Dict, Union | ||
from superdesk.core.resources import ResourceModel, ResourceConfig, MongoResourceConfig | ||
from superdesk.core.resources.service import AsyncResourceService | ||
from superdesk.core.web import EndpointGroup | ||
from pydantic import Field | ||
import logging | ||
from bson import ObjectId | ||
|
||
|
||
class ClientResource(ResourceModel): | ||
id: Annotated[Union[str, ObjectId], Field(alias="_id")] = None | ||
name: str | ||
password: str | ||
last_active: Optional[str] = None | ||
etag: Annotated[Optional[str], Field(alias="_etag")] = None | ||
|
||
|
||
class ClientService(AsyncResourceService[ClientResource]): | ||
"""Service class for managing OAuthClient resources""" | ||
|
||
resource_name = "oauth_clients" | ||
|
||
async def get_all_client(self) -> List[Dict]: | ||
try: | ||
# Collect all items asynchronously | ||
clients = [client async for client in self.get_all()] | ||
|
||
# Convert clients to list of dictionaries | ||
return [item.dict(by_alias=True, exclude_unset=True) for item in clients] | ||
|
||
except Exception as e: | ||
logging.error(f"Error retrieving data from clients: {e}") | ||
return [] | ||
|
||
|
||
clients_model_config = ResourceConfig( | ||
name="oauth_clients", | ||
data_class=ClientResource, | ||
mongo=MongoResourceConfig( | ||
prefix=MONGO_PREFIX, | ||
), | ||
elastic=None, | ||
service=ClientService, | ||
) | ||
|
||
clients_endpoints = EndpointGroup("oauth_clients", __name__) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,82 +1,103 @@ | ||
import re | ||
|
||
import flask | ||
from bson import ObjectId | ||
import bcrypt | ||
from flask import jsonify, current_app as app | ||
from typing import Optional | ||
|
||
from flask_babel import gettext | ||
from superdesk import get_resource_service | ||
from pydantic import BaseModel | ||
from werkzeug.exceptions import NotFound | ||
|
||
from newsroom.decorator import admin_only, account_manager_only | ||
from newsroom.oauth_clients import blueprint | ||
from newsroom.utils import query_resource, find_one, get_json_or_400 | ||
from superdesk.utils import gen_password | ||
from superdesk.core.web import Request, Response | ||
from superdesk.core.resources.fields import ObjectId | ||
|
||
from newsroom.utils import get_json_or_400_async | ||
from newsroom.decorator import admin_only, account_manager_only | ||
from .clients_async import clients_endpoints, ClientService, ClientResource | ||
|
||
def get_settings_data(): | ||
|
||
async def get_settings_data(): | ||
data = await ClientService().get_all_client() | ||
return { | ||
"oauth_clients": list(query_resource("oauth_clients")), | ||
"oauth_clients": data, | ||
} | ||
|
||
|
||
@blueprint.route("/oauth_clients/search", methods=["GET"]) | ||
class ClientSearchArgs(BaseModel): | ||
q: Optional[str] = None | ||
|
||
|
||
class ClientArgs(BaseModel): | ||
client_id: ObjectId | ||
|
||
|
||
@clients_endpoints.endpoint("/oauth_clients/search", methods=["GET"]) | ||
@account_manager_only | ||
def search(): | ||
async def search(args: None, params: ClientSearchArgs, request: Request) -> Response: | ||
lookup = None | ||
if flask.request.args.get("q"): | ||
regex = re.compile(".*{}.*".format(flask.request.args.get("q")), re.IGNORECASE) | ||
if params.q: | ||
regex = re.compile(f".*{re.escape(params.q)}.*", re.IGNORECASE) | ||
lookup = {"name": regex} | ||
companies = list(query_resource("oauth_clients", lookup=lookup)) | ||
return jsonify(companies), 200 | ||
cursor = await ClientService().search(lookup) | ||
data = await cursor.to_list_raw() | ||
return Response(data, 200, ()) | ||
|
||
|
||
@blueprint.route("/oauth_clients/new", methods=["POST"]) | ||
@clients_endpoints.endpoint("/oauth_clients/new", methods=["POST"]) | ||
@account_manager_only | ||
def create(): | ||
async def create(request: Request) -> Response: | ||
""" | ||
Creates the client with given client id | ||
""" | ||
client = get_json_or_400() | ||
client = await get_json_or_400_async(request) | ||
if not isinstance(client, dict): | ||
return request.abort(400) | ||
|
||
password = gen_password() | ||
new_company = { | ||
doc = { | ||
"name": client.get("name"), | ||
"password": bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode(), | ||
} | ||
|
||
ids = get_resource_service("oauth_clients").post([new_company]) | ||
return jsonify({"success": True, "_id": ids[0], "password": password}), 201 | ||
new_client = ClientResource.model_validate(doc) | ||
ids = await ClientService().create([new_client]) | ||
return Response({"success": True, "_id": ids[0], "password": password}, 201, ()) | ||
|
||
|
||
@blueprint.route("/oauth_clients/<_id>", methods=["GET", "POST"]) | ||
@clients_endpoints.endpoint("/oauth_clients/<string:client_id>", methods=["GET", "POST"]) | ||
@account_manager_only | ||
def edit(_id): | ||
async def edit(args: ClientArgs, params: None, request: Request) -> Response: | ||
""" | ||
Edits the client with given client id | ||
""" | ||
client = find_one("oauth_clients", _id=ObjectId(_id)) | ||
|
||
if not client: | ||
service = ClientService() | ||
original = await service.find_by_id(args.client_id) | ||
if not original: | ||
return NotFound(gettext("Client not found")) | ||
elif request.method == "GET": | ||
return Response(original, 200, ()) | ||
|
||
request_json = await get_json_or_400_async(request) | ||
if not isinstance(request_json, dict): | ||
return request.abort(400) | ||
|
||
if flask.request.method == "POST": | ||
client = get_json_or_400() | ||
updates = {} | ||
updates["name"] = client.get("name") | ||
get_resource_service("oauth_clients").patch(ObjectId(_id), updates=updates) | ||
app.cache.delete(_id) | ||
return jsonify({"success": True}), 200 | ||
return jsonify(client), 200 | ||
updates = {} | ||
updates["name"] = request_json.get("name") | ||
await service.update(args.client_id, updates) | ||
return Response({"success": True}, 200, ()) | ||
|
||
|
||
@blueprint.route("/oauth_clients/<_id>", methods=["DELETE"]) | ||
@clients_endpoints.endpoint("/oauth_clients/<string:client_id>", methods=["DELETE"]) | ||
@admin_only | ||
def delete(_id): | ||
async def delete(args: ClientArgs, params: None, request: Request) -> Response: | ||
""" | ||
Deletes the client with given client id | ||
""" | ||
get_resource_service("oauth_clients").delete_action(lookup={"_id": ObjectId(_id)}) | ||
|
||
app.cache.delete(_id) | ||
return jsonify({"success": True}), 200 | ||
service = ClientService() | ||
original = await service.find_by_id(args.client_id) | ||
|
||
if not original: | ||
raise NotFound(gettext("Client not found")) | ||
try: | ||
await service.delete(original) | ||
except Exception as e: | ||
return Response({"error": str(e)}, 400, ()) | ||
return Response({"success": True}, 200, ()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters