|
| 1 | +# Copyright © 2011-2026 Splunk, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"): you may |
| 4 | +# not use this file except in compliance with the License. You may obtain |
| 5 | +# a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | +# License for the specific language governing permissions and limitations |
| 13 | +# under the License. |
| 14 | + |
| 15 | + |
| 16 | +from typing import cast |
| 17 | + |
| 18 | +from pydantic import BaseModel |
| 19 | + |
| 20 | +from splunklib.client import Service |
| 21 | + |
| 22 | + |
| 23 | +def get_splunk_username(service: Service) -> str: |
| 24 | + if service.username: |
| 25 | + return cast(str, service.username) |
| 26 | + |
| 27 | + class Content(BaseModel): |
| 28 | + username: str |
| 29 | + |
| 30 | + class Entry(BaseModel): |
| 31 | + content: Content |
| 32 | + |
| 33 | + class ResponseBody(BaseModel): |
| 34 | + entry: list[Entry] |
| 35 | + |
| 36 | + # In case service.username is unavailable, query Splunk API for the username. |
| 37 | + # This can happen when a service is created with a token, without username/password. |
| 38 | + res = service.get( |
| 39 | + path_segment="authentication/current-context", |
| 40 | + output_mode="json", |
| 41 | + ) |
| 42 | + |
| 43 | + body = ResponseBody.model_validate_json(str(res.body)) # pyright: ignore[reportUnknownArgumentType] |
| 44 | + if len(body.entry) == 0: |
| 45 | + return "" |
| 46 | + return body.entry[0].content.username |
0 commit comments