Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 1 addition & 81 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse, PlainTextResponse, FileResponse
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_pagination import add_pagination, pagination_ctx

Check warning on line 32 in api/main.py

View workflow job for this annotation

GitHub Actions / Lint

Unused pagination_ctx imported from fastapi_pagination
from fastapi_versioning import VersionedFastAPI
from bson import ObjectId, errors
from pymongo.errors import DuplicateKeyError

Check warning on line 35 in api/main.py

View workflow job for this annotation

GitHub Actions / Lint

Unused DuplicateKeyError imported from pymongo.errors
from fastapi_users import FastAPIUsers
from beanie import PydanticObjectId
from pydantic import BaseModel
from kernelci.api.models import (

Check failure on line 39 in api/main.py

View workflow job for this annotation

GitHub Actions / Lint

Unable to import 'kernelci.api.models'
Node,
Hierarchy,
PublishEvent,
Expand Down Expand Up @@ -386,86 +386,6 @@
)


# -----------------------------------------------------------------------------
# User groups


@app.post('/group', response_model=UserGroup, response_model_by_alias=False)
async def post_user_group(
group: UserGroup,
current_user: User = Depends(get_current_superuser)):
"""Create new user group"""
metrics.add('http_requests_total', 1)
try:
obj = await db.create(group)
except DuplicateKeyError as error:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Group '{group.name}' already exists. \
Use a different group name."
) from error
await pubsub.publish_cloudevent('user_group', {'op': 'created',
'id': str(obj.id)})
return obj


@app.get('/groups', response_model=PageModel)
async def get_user_groups(request: Request):
"""Get all the user groups if no request parameters have passed.
Get all the matching user groups otherwise."""
metrics.add('http_requests_total', 1)
query_params = dict(request.query_params)

# Drop pagination parameters from query as they're already in arguments
for pg_key in ['limit', 'offset']:
query_params.pop(pg_key, None)

paginated_resp = await db.find_by_attributes(UserGroup, query_params)
paginated_resp.items = serialize_paginated_data(
UserGroup, paginated_resp.items)
return paginated_resp


@app.get('/group/{group_id}', response_model=Union[UserGroup, None],
response_model_by_alias=False)
async def get_group(group_id: str):
"""Get user group information from the provided group id"""
metrics.add('http_requests_total', 1)
return await db.find_by_id(UserGroup, group_id)


@app.delete('/group/{group_id}',
dependencies=[Depends(pagination_ctx(PageModel))],
status_code=status.HTTP_204_NO_CONTENT)
async def delete_group(group_id: str,
current_user: User = Depends(get_current_superuser)):
"""Delete user group matching the provided group id"""
metrics.add('http_requests_total', 1)
group_from_id = await db.find_by_id(UserGroup, group_id)
if not group_from_id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Group not found with id: {group_id}"
)
# Remove users from the group before deleting it
users = await db.find_by_attributes(
User, {"groups.name": group_from_id.name})
for user in users.items:
user['groups'].remove(group_from_id)
await db.update(User(**user))

# Remove group from user groups that are permitted to update node
nodes = await db.find_by_attributes(
Node, {"user_groups": group_from_id.name})
for node in nodes.items:
node['user_groups'].remove(group_from_id.name)
await db.update(Node(**node))

await db.delete_by_id(UserGroup, group_id)


# -----------------------------------------------------------------------------
# EventHistory
def _get_eventhistory(evdict):
"""Get EventHistory object from dictionary"""
evhist = EventHistory()
Expand Down Expand Up @@ -1100,7 +1020,7 @@


@app.get('/maintenance/purge-old-nodes')
async def purge_old_nodes(current_user: User = Depends(get_current_superuser)):
async def purge_handler(current_user: User = Depends(get_current_superuser)):
"""Purge old nodes from the database
This is a maintenance operation and should be performed
only by superusers.
Expand Down
48 changes: 0 additions & 48 deletions doc/api-details.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,54 +249,6 @@ $ curl -X 'DELETE' \
-H 'Authorization: Bearer <ADMIN-USER-AUTHORIZATION-TOKEN>'
```


## User groups

User accounts can be added to different user groups. This section
explains different API endpoints for user group management operations.

### Create a user group (Admin only)

Admin users can create user groups using `POST /group` endpoint:
```
$ curl -X 'POST' \
'http://localhost:8001/group' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <ADMIN-USER-AUTHORIZATION-TOKEN>' \
-d '{"name": "test-user-group"}'
```


### Get all existing user groups

Get all existing user groups using `GET /groups` endpoint:
```
$ curl 'http://localhost:8001/groups'
{"items":[{"id":"648ff894bd39930355ed16ad","name":"kernelci"},{"id":"6704f354ffaa8f6fa017faa3","name":"test"}],"total":2,"limit":50,"offset":0}
```


### Get user group matching ID

To get user group by ID, use `/group` endpoint with group ID as a path parameter:
```
$ curl 'http://localhost:8001/group/648ff894bd39930355ed16ad'
{"id":"648ff894bd39930355ed16ad","name":"kernelci"}
```


### Delete user group matching ID (Admin only)

Only admin users can delete existing user groups by providing group ID to
`DELETE /group/<group-id>` endpoint:
```
$ curl -X 'DELETE' \
'http://localhost:8001/group/6704f354ffaa8f6fa017faa3' \
-H 'Authorization: Bearer <ADMIN-USER-AUTHORIZATION-TOKEN>'
```


## Nodes

`Node` objects form the basis of the API models to represent tests runs,
Expand Down
61 changes: 0 additions & 61 deletions tests/e2e_tests/test_user_group_handler.py

This file was deleted.

Loading