"src/vscode:/vscode.git/clone" did not exist on "4944824544775d6c1d412948c92b24837ecf27e7"
utils.py 2.08 KB
Newer Older
1
2
3
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import HTTPException, status, Depends
from apps.web.models.users import Users
4
5
from pydantic import BaseModel
from typing import Union, Optional
6
from constants import ERROR_MESSAGES
7
8
9
10
11
12
13
from passlib.context import CryptContext
from datetime import datetime, timedelta
import requests
import jwt

import config

14
JWT_SECRET_KEY = config.WEBUI_JWT_SECRET_KEY
15
16
17
18
19
20
21
22
23
24
25
ALGORITHM = "HS256"

##############
# Auth Utils
##############

bearer_scheme = HTTPBearer()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def verify_password(plain_password, hashed_password):
26
27
    return (pwd_context.verify(plain_password, hashed_password)
            if hashed_password else None)
28
29
30
31
32
33


def get_password_hash(password):
    return pwd_context.hash(password)


34
35
def create_token(data: dict,
                 expires_delta: Union[timedelta, None] = None) -> str:
36
37
38
39
40
41
42
43
44
45
46
47
    payload = data.copy()

    if expires_delta:
        expire = datetime.utcnow() + expires_delta
        payload.update({"exp": expire})

    encoded_jwt = jwt.encode(payload, JWT_SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def decode_token(token: str) -> Optional[dict]:
    try:
48
49
50
        decoded = jwt.decode(token,
                             JWT_SECRET_KEY,
                             options={"verify_signature": False})
51
52
53
54
55
56
        return decoded
    except Exception as e:
        return None


def extract_token_from_auth_header(auth_header: str):
57
    return auth_header[len("Bearer "):]
58
59


60
61
def get_current_user(auth_token: HTTPAuthorizationCredentials = Depends(
    HTTPBearer())):
62
63
64
65
66
67
68
    data = decode_token(auth_token.credentials)
    if data != None and "email" in data:
        user = Users.get_user_by_email(data["email"])
        if user is None:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=ERROR_MESSAGES.INVALID_TOKEN,
69
            )
70
        return user
71
72
73
74
75
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=ERROR_MESSAGES.UNAUTHORIZED,
        )