from pot_libs.aredis_util.aredis_utils import RedisUtils
from pot_libs.logger import log
from jwt.utils import base64url_decode
from pot_libs.aes_util.aes_util import PrpCrypt
import json


def jwt_user(request):
    """从jwt中解析user_id"""
    token = request.token
    if not token:
        return None
    try:
        payload = base64url_decode(token.split(".")[1])
    except:
        return None
    payload = json.loads(payload.decode("utf-8"))
    user_id = payload.get("user_id")
    return user_id


async def auth_phone_verify(phone, verify):
    """检验手机验证码"""
    verify_server = await RedisUtils().get(f"sms:sms_{phone}")
    log.info(f"auth_phone_verify phone:{phone}, verify_server:{verify_server},"
             f"verify:{verify}")
    if not verify_server:
        return False
    if isinstance(verify_server, str) and verify != verify_server:
        return False
    if isinstance(verify_server, bytes) and verify != verify_server.decode():
        return False
    return True


def check_password(password):
    """加密密码"""
    pc = PrpCrypt()
    password_enc_b = pc.encrypt(str(password))
    password_enc = str(password_enc_b, encoding='utf-8')
    return password_enc

