You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.8 KiB
71 lines
1.8 KiB
|
3 years ago
|
# !/usr/bin/env python3
|
||
|
|
# -*- encoding : utf-8 -*-
|
||
|
|
# @Filename : security.py
|
||
|
|
# @Software : VSCode
|
||
|
|
# @Datetime : 2021/11/03 17:33:20
|
||
|
|
# @Author : leo liu
|
||
|
|
# @Version : 1.0
|
||
|
|
# @Description :
|
||
|
|
|
||
|
|
"""
|
||
|
|
|
||
|
|
token password 验证
|
||
|
|
|
||
|
|
pip install python-jose
|
||
|
|
|
||
|
|
pip install passlib
|
||
|
|
|
||
|
|
|
||
|
|
"""
|
||
|
|
|
||
|
|
from datetime import datetime, timedelta
|
||
|
|
from typing import Any, Union, Optional
|
||
|
|
from fastapi import Depends, Header
|
||
|
|
from jose import jwt
|
||
|
|
from passlib.context import CryptContext
|
||
|
|
from pydantic import ValidationError
|
||
|
|
|
||
|
|
from core.settings import config
|
||
|
|
from utils import custom_exc
|
||
|
|
from api.v1.auth.schemas import token_schema
|
||
|
|
|
||
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||
|
|
|
||
|
|
def create_access_token(
|
||
|
|
subject: Union[str, Any], expires_delta: timedelta = None
|
||
|
|
) -> str:
|
||
|
|
if expires_delta:
|
||
|
|
expire = datetime.utcnow() + expires_delta
|
||
|
|
else:
|
||
|
|
expire = datetime.utcnow() + timedelta(
|
||
|
|
minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES
|
||
|
|
)
|
||
|
|
to_encode = {"exp": expire, "sub": str(subject)}
|
||
|
|
encoded_jwt = jwt.encode(to_encode, config.SECRET_KEY, algorithm=config.JWT_ALGORITHM)
|
||
|
|
return encoded_jwt
|
||
|
|
|
||
|
|
|
||
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||
|
|
return pwd_context.verify(plain_password, hashed_password)
|
||
|
|
|
||
|
|
|
||
|
|
def get_password_hash(password: str) -> str:
|
||
|
|
return pwd_context.hash(password)
|
||
|
|
|
||
|
|
def check_jwt_token(
|
||
|
|
token: Optional[str] = Header(None)
|
||
|
|
) -> Union[str, Any]:
|
||
|
|
"""
|
||
|
|
只解析验证token
|
||
|
|
:param token:
|
||
|
|
:return:
|
||
|
|
"""
|
||
|
|
|
||
|
|
try:
|
||
|
|
payload = jwt.decode(
|
||
|
|
token,
|
||
|
|
config.SECRET_KEY, algorithms=config.JWT_ALGORITHM
|
||
|
|
)
|
||
|
|
return token_schema.TokenPayload(**payload)
|
||
|
|
except (jwt.JWTError, ValidationError, AttributeError):
|
||
|
|
raise custom_exc.TokenAuthError(err_desc="access token fail")
|