-
Notifications
You must be signed in to change notification settings - Fork 108
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Generation of API key on pbench-server (#3368)
POST `/api/v1/key` call generates a unique API key for the authenticated user. Reworked `active_token` table to `api_keys`. Co-authored-by: siddardh <sira@redhat27!>
- Loading branch information
1 parent
6c8bb0a
commit e6c3a54
Showing
15 changed files
with
585 additions
and
197 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 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
from http import HTTPStatus | ||
|
||
from flask import jsonify | ||
from flask.wrappers import Request, Response | ||
|
||
from pbench.server import PbenchServerConfig | ||
from pbench.server.api.resources import ( | ||
APIAbort, | ||
ApiAuthorizationType, | ||
ApiBase, | ||
ApiContext, | ||
APIInternalError, | ||
ApiMethod, | ||
ApiParams, | ||
ApiSchema, | ||
) | ||
import pbench.server.auth.auth as Auth | ||
from pbench.server.database.models.api_keys import APIKey, DuplicateApiKey | ||
from pbench.server.database.models.audit import AuditType, OperationCode | ||
|
||
|
||
class APIKeyManage(ApiBase): | ||
def __init__(self, config: PbenchServerConfig): | ||
super().__init__( | ||
config, | ||
ApiSchema( | ||
ApiMethod.POST, | ||
OperationCode.CREATE, | ||
audit_type=AuditType.API_KEY, | ||
audit_name="apikey", | ||
authorization=ApiAuthorizationType.NONE, | ||
), | ||
) | ||
|
||
def _post( | ||
self, params: ApiParams, request: Request, context: ApiContext | ||
) -> Response: | ||
""" | ||
Post request for generating a new persistent API key. | ||
Required headers include | ||
Content-Type: application/json | ||
Accept: application/json | ||
Returns: | ||
Success: 201 with api_key | ||
Raises: | ||
APIAbort, reporting "UNAUTHORIZED" | ||
APIInternalError, reporting the failure message | ||
""" | ||
user = Auth.token_auth.current_user() | ||
|
||
if not user: | ||
raise APIAbort( | ||
HTTPStatus.UNAUTHORIZED, | ||
"User provided access_token is invalid or expired", | ||
) | ||
try: | ||
new_key = APIKey.generate_api_key(user) | ||
except Exception as e: | ||
raise APIInternalError(str(e)) from e | ||
|
||
try: | ||
key = APIKey(api_key=new_key, user=user) | ||
key.add() | ||
status = HTTPStatus.CREATED | ||
except DuplicateApiKey: | ||
status = HTTPStatus.OK | ||
except Exception as e: | ||
raise APIInternalError(str(e)) from e | ||
|
||
context["auditing"]["attributes"] = {"key": new_key} | ||
response = jsonify({"api_key": new_key}) | ||
response.status_code = status | ||
return response |
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
53 changes: 53 additions & 0 deletions
53
lib/pbench/server/database/alembic/versions/80c8c690f09b_api_key.py
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,53 @@ | ||
""" Update table for storing api_key and removing auth_token | ||
Revision ID: 80c8c690f09b | ||
Revises: f628657bed56 | ||
Create Date: 2023-04-11 19:20:36.892126 | ||
""" | ||
from alembic import op | ||
import sqlalchemy as sa | ||
from sqlalchemy.dialects import postgresql | ||
|
||
from pbench.server.database.models import TZDateTime | ||
|
||
# revision identifiers, used by Alembic. | ||
revision = "80c8c690f09b" | ||
down_revision = "f628657bed56" | ||
branch_labels = None | ||
depends_on = None | ||
|
||
|
||
def upgrade() -> None: | ||
op.create_table( | ||
"api_keys", | ||
sa.Column("api_key", sa.String(length=500), nullable=False), | ||
sa.Column("created", TZDateTime(), nullable=False), | ||
sa.Column("user_id", sa.String(), nullable=False), | ||
sa.ForeignKeyConstraint( | ||
["user_id"], | ||
["users.id"], | ||
), | ||
sa.PrimaryKeyConstraint("api_key"), | ||
) | ||
op.drop_index("ix_auth_tokens_expiration", table_name="auth_tokens") | ||
op.drop_index("ix_auth_tokens_token", table_name="auth_tokens") | ||
op.drop_table("auth_tokens") | ||
|
||
|
||
def downgrade() -> None: | ||
op.create_table( | ||
"auth_tokens", | ||
sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False), | ||
sa.Column("token", sa.VARCHAR(length=500), autoincrement=False, nullable=False), | ||
sa.Column( | ||
"expiration", postgresql.TIMESTAMP(), autoincrement=False, nullable=False | ||
), | ||
sa.PrimaryKeyConstraint("id", name="auth_tokens_pkey"), | ||
) | ||
op.create_index("ix_auth_tokens_token", "auth_tokens", ["token"], unique=False) | ||
op.create_index( | ||
"ix_auth_tokens_expiration", "auth_tokens", ["expiration"], unique=False | ||
) | ||
op.drop_table("api_keys") |
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
Oops, something went wrong.