2022-08-29 19:41:15 +00:00
|
|
|
import logging
|
2020-12-25 14:50:19 +00:00
|
|
|
import secrets
|
2024-01-14 19:00:30 +00:00
|
|
|
from datetime import datetime, timedelta, timezone
|
2022-08-29 19:41:15 +00:00
|
|
|
from typing import Any, Dict, Union
|
2020-12-25 14:50:19 +00:00
|
|
|
|
2020-12-26 14:54:22 +00:00
|
|
|
import jwt
|
2022-09-09 17:38:42 +00:00
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, status
|
2020-12-26 14:54:22 +00:00
|
|
|
from fastapi.security import OAuth2PasswordBearer
|
2020-12-25 14:50:19 +00:00
|
|
|
from fastapi.security.http import HTTPBasic, HTTPBasicCredentials
|
2020-12-26 14:54:22 +00:00
|
|
|
|
2021-01-02 08:07:31 +00:00
|
|
|
from freqtrade.rpc.api_server.api_schemas import AccessAndRefreshToken, AccessToken
|
2020-12-31 10:01:50 +00:00
|
|
|
from freqtrade.rpc.api_server.deps import get_api_config
|
2020-12-25 14:50:19 +00:00
|
|
|
|
|
|
|
|
2022-08-29 19:41:15 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2020-12-25 14:50:19 +00:00
|
|
|
ALGORITHM = "HS256"
|
|
|
|
|
|
|
|
router_login = APIRouter()
|
|
|
|
|
|
|
|
|
2020-12-27 14:24:49 +00:00
|
|
|
def verify_auth(api_config, username: str, password: str):
|
2020-12-26 07:48:15 +00:00
|
|
|
"""Verify username/password"""
|
2024-05-12 14:51:11 +00:00
|
|
|
return secrets.compare_digest(username, api_config.get("username")) and secrets.compare_digest(
|
|
|
|
password, api_config.get("password")
|
|
|
|
)
|
2020-12-25 14:50:19 +00:00
|
|
|
|
|
|
|
|
2020-12-26 07:48:15 +00:00
|
|
|
httpbasic = HTTPBasic(auto_error=False)
|
2024-04-20 08:10:57 +00:00
|
|
|
security = HTTPBasic()
|
2020-12-26 07:48:15 +00:00
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
|
2020-12-25 14:50:19 +00:00
|
|
|
|
|
|
|
|
2022-09-10 12:19:11 +00:00
|
|
|
def get_user_from_token(token, secret_key: str, token_type: str = "access") -> str:
|
2020-12-26 07:48:15 +00:00
|
|
|
credentials_exception = HTTPException(
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
detail="Could not validate credentials",
|
|
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
|
|
)
|
|
|
|
try:
|
2020-12-27 14:24:49 +00:00
|
|
|
payload = jwt.decode(token, secret_key, algorithms=[ALGORITHM])
|
2024-05-12 14:51:11 +00:00
|
|
|
username: str = payload.get("identity", {}).get("u")
|
2020-12-26 07:48:15 +00:00
|
|
|
if username is None:
|
2022-09-10 12:19:11 +00:00
|
|
|
raise credentials_exception
|
2020-12-26 07:48:15 +00:00
|
|
|
if payload.get("type") != token_type:
|
2022-09-10 12:19:11 +00:00
|
|
|
raise credentials_exception
|
2020-12-25 14:50:19 +00:00
|
|
|
|
2020-12-26 07:48:15 +00:00
|
|
|
except jwt.PyJWTError:
|
2022-09-10 12:19:11 +00:00
|
|
|
raise credentials_exception
|
2020-12-26 07:48:15 +00:00
|
|
|
return username
|
2020-12-25 14:50:19 +00:00
|
|
|
|
|
|
|
|
2022-08-29 19:41:15 +00:00
|
|
|
# This should be reimplemented to better realign with the existing tools provided
|
|
|
|
# by FastAPI regarding API Tokens
|
2022-09-04 16:22:10 +00:00
|
|
|
# https://github.com/tiangolo/fastapi/blob/master/fastapi/security/api_key.py
|
2022-09-10 12:19:11 +00:00
|
|
|
async def validate_ws_token(
|
2022-08-29 19:41:15 +00:00
|
|
|
ws: WebSocket,
|
2022-09-10 12:29:58 +00:00
|
|
|
ws_token: Union[str, None] = Query(default=None, alias="token"),
|
2024-05-12 14:51:11 +00:00
|
|
|
api_config: Dict[str, Any] = Depends(get_api_config),
|
2022-08-29 19:41:15 +00:00
|
|
|
):
|
2024-05-12 14:51:11 +00:00
|
|
|
secret_ws_token = api_config.get("ws_token", None)
|
|
|
|
secret_jwt_key = api_config.get("jwt_secret_key", "super-secret")
|
2022-08-29 19:41:15 +00:00
|
|
|
|
2022-09-22 00:23:00 +00:00
|
|
|
# Check if ws_token is/in secret_ws_token
|
2022-09-21 22:02:21 +00:00
|
|
|
if ws_token and secret_ws_token:
|
|
|
|
is_valid_ws_token = False
|
|
|
|
if isinstance(secret_ws_token, str):
|
|
|
|
is_valid_ws_token = secrets.compare_digest(secret_ws_token, ws_token)
|
|
|
|
elif isinstance(secret_ws_token, list):
|
2024-05-12 14:51:11 +00:00
|
|
|
is_valid_ws_token = any(
|
|
|
|
[secrets.compare_digest(potential, ws_token) for potential in secret_ws_token]
|
|
|
|
)
|
2022-09-21 22:02:21 +00:00
|
|
|
|
|
|
|
if is_valid_ws_token:
|
|
|
|
return ws_token
|
2022-09-22 00:23:00 +00:00
|
|
|
|
|
|
|
# Check if ws_token is a JWT
|
|
|
|
try:
|
|
|
|
user = get_user_from_token(ws_token, secret_jwt_key)
|
|
|
|
return user
|
|
|
|
# If the token is a jwt, and it's valid return the user
|
|
|
|
except HTTPException:
|
|
|
|
pass
|
|
|
|
|
2022-09-10 12:19:11 +00:00
|
|
|
# If it doesn't match, close the websocket connection
|
|
|
|
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
|
2021-01-08 18:27:51 +00:00
|
|
|
def create_token(data: dict, secret_key: str, token_type: str = "access") -> str:
|
2020-12-26 07:48:15 +00:00
|
|
|
to_encode = data.copy()
|
|
|
|
if token_type == "access":
|
2024-01-14 19:00:30 +00:00
|
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=15)
|
2020-12-26 07:48:15 +00:00
|
|
|
elif token_type == "refresh":
|
2024-01-14 19:00:30 +00:00
|
|
|
expire = datetime.now(timezone.utc) + timedelta(days=30)
|
2020-12-26 07:48:15 +00:00
|
|
|
else:
|
|
|
|
raise ValueError()
|
2024-05-12 14:51:11 +00:00
|
|
|
to_encode.update(
|
|
|
|
{
|
|
|
|
"exp": expire,
|
|
|
|
"iat": datetime.now(timezone.utc),
|
|
|
|
"type": token_type,
|
|
|
|
}
|
|
|
|
)
|
2020-12-27 14:24:49 +00:00
|
|
|
encoded_jwt = jwt.encode(to_encode, secret_key, algorithm=ALGORITHM)
|
2020-12-26 07:48:15 +00:00
|
|
|
return encoded_jwt
|
|
|
|
|
|
|
|
|
2024-05-12 14:51:11 +00:00
|
|
|
def http_basic_or_jwt_token(
|
|
|
|
form_data: HTTPBasicCredentials = Depends(httpbasic),
|
|
|
|
token: str = Depends(oauth2_scheme),
|
|
|
|
api_config=Depends(get_api_config),
|
|
|
|
):
|
2020-12-26 07:48:15 +00:00
|
|
|
if token:
|
2024-05-12 14:51:11 +00:00
|
|
|
return get_user_from_token(token, api_config.get("jwt_secret_key", "super-secret"))
|
2020-12-27 14:24:49 +00:00
|
|
|
elif form_data and verify_auth(api_config, form_data.username, form_data.password):
|
2020-12-26 07:48:15 +00:00
|
|
|
return form_data.username
|
|
|
|
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
2020-12-27 13:57:01 +00:00
|
|
|
detail="Unauthorized",
|
2020-12-26 07:48:15 +00:00
|
|
|
)
|
2020-12-25 14:50:19 +00:00
|
|
|
|
|
|
|
|
2024-05-12 14:51:11 +00:00
|
|
|
@router_login.post("/token/login", response_model=AccessAndRefreshToken)
|
|
|
|
def token_login(
|
|
|
|
form_data: HTTPBasicCredentials = Depends(security), api_config=Depends(get_api_config)
|
|
|
|
):
|
2020-12-27 14:24:49 +00:00
|
|
|
if verify_auth(api_config, form_data.username, form_data.password):
|
2024-05-12 14:51:11 +00:00
|
|
|
token_data = {"identity": {"u": form_data.username}}
|
|
|
|
access_token = create_token(token_data, api_config.get("jwt_secret_key", "super-secret"))
|
|
|
|
refresh_token = create_token(
|
|
|
|
token_data, api_config.get("jwt_secret_key", "super-secret"), token_type="refresh"
|
|
|
|
)
|
2020-12-25 14:50:19 +00:00
|
|
|
return {
|
|
|
|
"access_token": access_token,
|
|
|
|
"refresh_token": refresh_token,
|
|
|
|
}
|
|
|
|
else:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
detail="Incorrect username or password",
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-05-12 14:51:11 +00:00
|
|
|
@router_login.post("/token/refresh", response_model=AccessToken)
|
2020-12-27 14:24:49 +00:00
|
|
|
def token_refresh(token: str = Depends(oauth2_scheme), api_config=Depends(get_api_config)):
|
2020-12-26 07:48:15 +00:00
|
|
|
# Refresh token
|
2024-05-12 14:51:11 +00:00
|
|
|
u = get_user_from_token(token, api_config.get("jwt_secret_key", "super-secret"), "refresh")
|
|
|
|
token_data = {"identity": {"u": u}}
|
|
|
|
access_token = create_token(
|
|
|
|
token_data, api_config.get("jwt_secret_key", "super-secret"), token_type="access"
|
|
|
|
)
|
|
|
|
return {"access_token": access_token}
|