#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from exceptions import AuthException
import urllib
import hashlib
from fastapi import Request
from extensions import * 

class AuthUser:
    user_id: int
    user_name: str
    nick_name: str
    is_yzy_user: int

def data_auth_sign(data):
    sorted(data.items(),key=lambda item:item[0],reverse=True)
    res = urllib.parse.urlencode(data)
    sha = hashlib.sha1(res.encode('utf-8'))
    encrypts = sha.hexdigest()
    return encrypts

def get_auth_user(request: Request):
    try:
        auth = request.session.get('user_auth')
        if auth is not None:
            user_auth_sign = request.session['user_auth_sign']
            if user_auth_sign == data_auth_sign(auth):
                authUser = AuthUser()
                authUser.user_id = auth['user_id']
                authUser.user_name = auth['user_name']
                authUser.nick_name = auth['nick_name']
                authUser.is_yzy_user = int(auth['is_yzy_user'])
                return authUser
    except Exception as e:
        raise AuthException(str(e))
    return None